context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
#pragma warning disable 0414
namespace System.Reflection.Tests
{
public class FieldInfoPropertyTests
{
//Verify Static int FieldType
[Fact]
public void TestFieldType_intstatic()
{
String fieldname = "intFieldStatic";
FieldInfo fi = getField(fieldname);
FieldInfoPropertyTests myInstance = new FieldInfoPropertyTests();
Assert.NotNull(fi);
Assert.True(fi.Name.Equals(fieldname));
Assert.True(fi.IsStatic);
}
//Verify Non Static int FieldType
[Fact]
public void TestFieldType_intnonstatic()
{
String fieldname = "intFieldNonStatic";
FieldInfo fi = getField(fieldname);
FieldInfoPropertyTests myInstance = new FieldInfoPropertyTests();
Assert.NotNull(fi);
Assert.True(fi.Name.Equals(fieldname));
Assert.False(fi.IsStatic);
}
//Verify Static String FieldType
[Fact]
public void TestFieldType_strstatic()
{
String fieldname = "static_strField";
FieldInfo fi = getField(fieldname);
FieldInfoPropertyTests myInstance = new FieldInfoPropertyTests();
Assert.NotNull(fi);
Assert.True(fi.Name.Equals(fieldname));
Assert.True(fi.IsStatic);
}
//Verify Non Static String FieldType
[Fact]
public void TestFieldType_strnonstatic()
{
String fieldname = "nonstatic_strField";
FieldInfo fi = getField(fieldname);
FieldInfoPropertyTests myInstance = new FieldInfoPropertyTests();
Assert.NotNull(fi);
Assert.True(fi.Name.Equals(fieldname));
Assert.False(fi.IsStatic);
}
//Verify Public String FieldType using IsPublic
[Fact]
public void TestIsPublic1()
{
String fieldname = "nonstatic_strField";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.IsPublic);
}
//Verify Public int FieldType using IsPublic
[Fact]
public void TestIsPublic2()
{
String fieldname = "intFieldStatic";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.IsPublic);
}
//Verify Private int FieldType using IsPublic
[Fact]
public void TestIsPublic3()
{
String fieldname = "_privateInt";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsPublic);
}
//Verify Private String FieldType using IsPublic
[Fact]
public void TestIsPublic4()
{
String fieldname = "_privateStr";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsPublic);
}
//Verify Private int FieldType using IsPrivate
[Fact]
public void TestIsPrivate1()
{
String fieldname = "_privateInt";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.IsPrivate);
}
//Verify Private String FieldType using IsPrivate
[Fact]
public void TestIsPrivate2()
{
String fieldname = "_privateStr";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.IsPrivate);
}
//Verify Public String FieldType using IsPrivate
[Fact]
public void TestIsPrivate3()
{
String fieldname = "nonstatic_strField";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsPrivate);
}
//Verify Public int FieldType using IsPrivate
[Fact]
public void TestIsPrivate4()
{
String fieldname = "intFieldStatic";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsPrivate);
}
//Verify Private int FieldType using IsStatic
[Fact]
public void TestIsStatic1()
{
String fieldname = "_privateInt";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsStatic);
}
//Verify public static int FieldType using IsStatic
[Fact]
public void TestIsStatic2()
{
String fieldname = "intFieldStatic";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.IsStatic);
}
//Verify IsAssembly for static object
[Fact]
public void TestIsAssembly1()
{
String fieldname = "s_field_Assembly1";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsAssembly);
}
//Verify IsAssembly for private static object
[Fact]
public void TestIsAssembly2()
{
String fieldname = "s_field_Assembly2";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsAssembly);
}
//Verify IsAssembly for protected static object
[Fact]
public void TestIsAssembly3()
{
String fieldname = "Field_Assembly3";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsAssembly);
}
//Verify IsAssembly for public static object
[Fact]
public void TestIsAssembly4()
{
String fieldname = "Field_Assembly4";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsAssembly);
}
//Verify IsAssembly for internal static object
[Fact]
public void TestIsAssembly5()
{
String fieldname = "Field_Assembly5";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.IsAssembly);
}
//Verify IsFamily for static object
[Fact]
public void TestIsFamily1()
{
String fieldname = "s_field_Assembly1";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamily);
}
//Verify IsFamily for private static object
[Fact]
public void TestIsFamily2()
{
String fieldname = "s_field_Assembly2";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamily);
}
//Verify IsFamily for protected static object
[Fact]
public void TestIsFamily3()
{
String fieldname = "Field_Assembly3";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.IsFamily);
}
//Verify IsFamily for public static object
[Fact]
public void TestIsFamily4()
{
String fieldname = "Field_Assembly4";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamily);
}
//Verify IsFamily for internal static object
[Fact]
public void TestIsFamily5()
{
String fieldname = "Field_Assembly5";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamily);
}
//Verify IsFamilyAndAssembly for s_field_FamilyAndAssembly1
[Fact]
public void TestIsFamilyAndAssembly1()
{
String fieldname = "s_field_FamilyAndAssembly1";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamilyAndAssembly);
}
//Verify IsFamilyAndAssembly for s_field_FamilyAndAssembly2
[Fact]
public void TestIsFamilyAndAssembly2()
{
String fieldname = "s_field_FamilyAndAssembly2";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamilyAndAssembly);
}
//Verify IsFamilyAndAssembly for Field_FamilyAndAssembly3
[Fact]
public void TestIsFamilyAndAssembly3()
{
String fieldname = "Field_FamilyAndAssembly3";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamilyAndAssembly);
}
//Verify IsFamilyAndAssembly for Field_FamilyAndAssembly4
[Fact]
public void TestIsFamilyAndAssembly4()
{
String fieldname = "Field_FamilyAndAssembly4";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamilyAndAssembly);
}
//Verify IsFamilyAndAssembly for Field_FamilyAndAssembly5
[Fact]
public void TestIsFamilyAndAssembly5()
{
String fieldname = "Field_FamilyAndAssembly5";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamilyAndAssembly);
}
//Verify IsFamilyOrAssembly for s_field_FamilyOrAssembly1
[Fact]
public void TestIsFamilyOrAssembly1()
{
String fieldname = "s_field_FamilyOrAssembly1";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamilyOrAssembly);
}
//Verify IsFamilyOrAssembly for s_field_FamilyOrAssembly2
[Fact]
public void TestIsFamilyOrAssembly2()
{
String fieldname = "s_field_FamilyOrAssembly2";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamilyOrAssembly);
}
//Verify IsFamilyOrAssembly for Field_FamilyOrAssembly3
[Fact]
public void TestIsFamilyOrAssembly3()
{
String fieldname = "Field_FamilyOrAssembly3";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamilyOrAssembly);
}
//Verify IsFamilyOrAssembly for Field_FamilyOrAssembly4
[Fact]
public void TestIsFamilyOrAssembly4()
{
String fieldname = "Field_FamilyOrAssembly4";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamilyOrAssembly);
}
//Verify IsFamilyOrAssembly for Field_FamilyOrAssembly5
[Fact]
public void TestIsFamilyOrAssembly5()
{
String fieldname = "Field_FamilyOrAssembly5";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsFamilyOrAssembly);
}
//Verify IsInitOnly for readonly field
[Fact]
public void TestIsInitOnly1()
{
String fieldname = "rointField";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.IsInitOnly);
}
//Verify IsInitOnly for non- readonly field
[Fact]
public void TestIsInitOnly2()
{
String fieldname = "intFieldNonStatic";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsInitOnly);
}
//Verify IsLiteral for literal fields like constant
[Fact]
public void TestIsLiteral1()
{
String fieldname = "constIntField";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.IsLiteral);
}
//Verify IsLiteral for non constant fields
[Fact]
public void TestIsLiteral2()
{
String fieldname = "intFieldNonStatic";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsLiteral);
}
//Verify FieldType for int field
[Fact]
public void TestFieldType1()
{
String fieldname = "intFieldNonStatic";
FieldInfo fi = getField(fieldname);
string typeStr = "System.Int32";
Assert.NotNull(fi);
Assert.True(fi.FieldType.ToString().Equals(typeStr));
}
//Verify FieldType for string field
[Fact]
public void TestFieldType2()
{
String fieldname = "nonstatic_strField";
FieldInfo fi = getField(fieldname);
string typeStr = "System.String";
Assert.NotNull(fi);
Assert.True(fi.FieldType.ToString().Equals(typeStr), "Failed!! Expected FieldType to return " + typeStr);
}
//Verify FieldType for Object field
[Fact]
public void TestFieldType3()
{
String fieldname = "s_field_Assembly1";
FieldInfo fi = getField(fieldname);
string typeStr = "System.Object";
Assert.NotNull(fi);
Assert.True(fi.FieldType.ToString().Equals(typeStr), "Failed!! Expected FieldType to return " + typeStr);
}
//Verify FieldAttributes
[Fact]
public void TestFieldAttribute1()
{
String fieldname = "intFieldNonStatic";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.Attributes.Equals(FieldAttributes.Public), "Failed!! Expected Field Attribute to be of type Public");
}
//Verify FieldAttributes
[Fact]
public void TestFieldAttribute2()
{
String fieldname = "intFieldStatic";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.Attributes.Equals(FieldAttributes.Public | FieldAttributes.Static), "Failed!! Expected Field Attribute to be of type Public and static");
}
//Verify FieldAttributes
[Fact]
public void TestFieldAttribute3()
{
String fieldname = "_privateInt";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.Attributes.Equals(FieldAttributes.Private), "Failed!! Expected Field Attribute to be of type Private");
}
//Verify FieldAttributes
[Fact]
public void TestFieldAttribute4()
{
String fieldname = "rointField";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.True(fi.Attributes.Equals(FieldAttributes.Public | FieldAttributes.InitOnly), "Failed!! Expected Field Attribute to be of type InitOnly");
}
//Verify IsSpecialName for FieldInfo
[Fact]
public void TestIsSpecialName()
{
String fieldname = "intFieldNonStatic";
FieldInfo fi = getField(fieldname);
Assert.NotNull(fi);
Assert.False(fi.IsSpecialName, "Failed: FieldInfo IsSpecialName returned True for field: " + fieldname);
}
private static FieldInfo getField(string field)
{
Type t = typeof(FieldInfoPropertyTests);
TypeInfo ti = t.GetTypeInfo();
FieldInfo fi = null;
fi = ti.DeclaredFields.Single(x => x.Name == field);
return fi;
}
//Fields for Reflection Metadata
public static int intFieldStatic = 100; // Field for Reflection
public int intFieldNonStatic = 101; //Field for Reflection
public static string static_strField = "Static string field"; // Field for Reflection
public string nonstatic_strField = "NonStatic string field"; // Field for Reflection
private int _privateInt = 1; // Field for Reflection
private string _privateStr = "_privateStr"; // Field for Reflection
private static Object s_field_Assembly1 = null; // without keyword
private static Object s_field_Assembly2 = null; // with private keyword
protected static Object Field_Assembly3 = null; // with protected keyword
public static Object Field_Assembly4 = null; // with public keyword
internal static Object Field_Assembly5 = null; // with internal keyword
private static Object s_field_FamilyAndAssembly1 = null; // without keyword
private static Object s_field_FamilyAndAssembly2 = null; // with private keyword
protected static Object Field_FamilyAndAssembly3 = null; // with protected keyword
public static Object Field_FamilyAndAssembly4 = null; // with public keyword
internal static Object Field_FamilyAndAssembly5 = null; // with internal keyword
private static Object s_field_FamilyOrAssembly1 = null; // without keyword
private static Object s_field_FamilyOrAssembly2 = null; // with private keyword
protected static Object Field_FamilyOrAssembly3 = null; // with protected keyword
public static Object Field_FamilyOrAssembly4 = null; // with public keyword
internal static Object Field_FamilyOrAssembly5 = null; // with internal keyword
public readonly int rointField = 1;
public const int constIntField = 1222;
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Placeholder projectile and explosion with required sounds, debris, and
// particle datablocks. These datablocks existed in now removed scripts, but
// were used within some that remain: see Lurker.cs, Ryder.cs, ProxMine.cs
//
// These effects should be made more generic or new fx created for unique usage.
//
// I've removed all effects that are not required for the current weapons. On
// reflection I really went overboard when originally making these effects!
// ----------------------------------------------------------------------------
$GrenadeUpVectorOffset = "0 0 1";
// ---------------------------------------------------------------------------
// Sounds
// ---------------------------------------------------------------------------
datablock SFXProfile(GrenadeExplosionSound)
{
filename = "data/FPSGameplay/sound/weapons/GRENADELAND.wav";
description = AudioDefault3d;
preload = true;
};
datablock SFXProfile(GrenadeLauncherExplosionSound)
{
filename = "data/FPSGameplay/sound/weapons/Crossbow_explosion";
description = AudioDefault3d;
preload = true;
};
// ----------------------------------------------------------------------------
// Lights for the projectile(s)
// ----------------------------------------------------------------------------
datablock LightDescription(GrenadeLauncherLightDesc)
{
range = 1.0;
color = "1 1 1";
brightness = 2.0;
animationType = PulseLightAnim;
animationPeriod = 0.25;
//flareType = SimpleLightFlare0;
};
// ---------------------------------------------------------------------------
// Debris
// ---------------------------------------------------------------------------
datablock ParticleData(GrenadeDebrisFireParticle)
{
textureName = "data/FPSGameplay/art/particles/impact";
dragCoeffiecient = 0;
gravityCoefficient = -1.00366;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 300;
lifetimeVarianceMS = 100;
useInvAlpha = false;
spinSpeed = 1;
spinRandomMin = -280.0;
spinRandomMax = 280.0;
colors[0] = "1 0.590551 0.188976 0.0944882";
colors[1] = "0.677165 0.590551 0.511811 0.496063";
colors[2] = "0.645669 0.645669 0.645669 0";
sizes[0] = 0.2;
sizes[1] = 0.5;
sizes[2] = 0.2;
times[0] = 0.0;
times[1] = 0.494118;
times[2] = 1.0;
animTexName = "data/FPSGameplay/art/particles/impact";
colors[3] = "1 1 1 0.407";
sizes[3] = "0.5";
};
datablock ParticleEmitterData(GrenadeDebrisFireEmitter)
{
ejectionPeriodMS = 10;
periodVarianceMS = 0;
ejectionVelocity = 0;
velocityVariance = 0;
thetaMin = 0.0;
thetaMax = 25;
phiReferenceVel = 0;
phiVariance = 360;
ejectionoffset = 0.3;
particles = "GrenadeDebrisFireParticle";
orientParticles = "1";
blendStyle = "NORMAL";
};
datablock DebrisData(GrenadeDebris)
{
shapeFile = "data/FPSGameplay/art/shapes/weapons/Grenade/grenadeDebris.dae";
emitters[0] = GrenadeDebrisFireEmitter;
elasticity = 0.4;
friction = 0.25;
numBounces = 3;
bounceVariance = 1;
explodeOnMaxBounce = false;
staticOnMaxBounce = false;
snapOnMaxBounce = false;
minSpinSpeed = 200;
maxSpinSpeed = 600;
render2D = false;
lifetime = 4;
lifetimeVariance = 1.5;
velocity = 15;
velocityVariance = 5;
fade = true;
useRadiusMass = true;
baseRadius = 0.3;
gravModifier = 1.0;
terminalVelocity = 20;
ignoreWater = false;
};
// ----------------------------------------------------------------------------
// Splash effects
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeSplashMist)
{
dragCoeffiecient = 1.0;
windCoefficient = 2.0;
gravityCoefficient = 0.3;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 600;
lifetimeVarianceMS = 100;
useInvAlpha = false;
spinRandomMin = -90.0;
spinRandomMax = 500.0;
spinSpeed = 1;
textureName = "data/FPSGameplay/art/particles/smoke";
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.5";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.2;
sizes[1] = 0.4;
sizes[2] = 0.8;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeSplashMistEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 3.0;
velocityVariance = 2.0;
ejectionOffset = 0.15;
thetaMin = 85;
thetaMax = 85;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvance = false;
lifetimeMS = 250;
particles = "GrenadeSplashMist";
};
datablock ParticleData(GrenadeSplashParticle)
{
dragCoeffiecient = 1;
windCoefficient = 0.9;
gravityCoefficient = 0.3;
inheritedVelFactor = 0.2;
constantAcceleration = -1.4;
lifetimeMS = 600;
lifetimeVarianceMS = 200;
textureName = "data/FPSGameplay/art/particles/droplet";
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.5";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.5;
sizes[1] = 0.25;
sizes[2] = 0.25;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeSplashEmitter)
{
ejectionPeriodMS = 4;
periodVarianceMS = 0;
ejectionVelocity = 7.3;
velocityVariance = 2.0;
ejectionOffset = 0.0;
thetaMin = 30;
thetaMax = 80;
phiReferenceVel = 00;
phiVariance = 360;
overrideAdvance = false;
orientParticles = true;
orientOnVelocity = true;
lifetimeMS = 100;
particles = "GrenadeSplashParticle";
};
datablock ParticleData(GrenadeSplashRingParticle)
{
textureName = "data/FPSGameplay/art/particles/wake";
dragCoeffiecient = 0.0;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.0;
lifetimeMS = 2500;
lifetimeVarianceMS = 200;
windCoefficient = 0.0;
useInvAlpha = 1;
spinRandomMin = 30.0;
spinRandomMax = 30.0;
spinSpeed = 1;
animateTexture = true;
framesPerSec = 1;
animTexTiling = "2 1";
animTexFrames = "0 1";
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.5";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 2.0;
sizes[1] = 4.0;
sizes[2] = 8.0;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeSplashRingEmitter)
{
lifetimeMS = "100";
ejectionPeriodMS = 200;
periodVarianceMS = 10;
ejectionVelocity = 0;
velocityVariance = 0;
ejectionOffset = 0;
thetaMin = 89;
thetaMax = 90;
phiReferenceVel = 0;
phiVariance = 1;
alignParticles = 1;
alignDirection = "0 0 1";
particles = "GrenadeSplashRingParticle";
};
datablock SplashData(GrenadeSplash)
{
// SplashData doesn't have a render function in the source,
// so everything but the emitter array is useless here.
emitter[0] = GrenadeSplashEmitter;
emitter[1] = GrenadeSplashMistEmitter;
emitter[2] = GrenadeSplashRingEmitter;
//numSegments = 15;
//ejectionFreq = 15;
//ejectionAngle = 40;
//ringLifetime = 0.5;
//lifetimeMS = 300;
//velocity = 4.0;
//startRadius = 0.0;
//acceleration = -3.0;
//texWrap = 5.0;
//texture = "data/FPSGameplay/art/images/particles//splash";
//colors[0] = "0.7 0.8 1.0 0.0";
//colors[1] = "0.7 0.8 1.0 0.3";
//colors[2] = "0.7 0.8 1.0 0.7";
//colors[3] = "0.7 0.8 1.0 0.0";
//times[0] = 0.0;
//times[1] = 0.4;
//times[2] = 0.8;
//times[3] = 1.0;
};
// ----------------------------------------------------------------------------
// Explosion Particle effects
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeExpFire)
{
textureName = "data/FPSGameplay/art/particles/fireball.png";
dragCoeffiecient = 0;
windCoeffiecient = 0.5;
gravityCoefficient = -1;
inheritedVelFactor = 0;
constantAcceleration = 0;
lifetimeMS = 1200;//3000;
lifetimeVarianceMS = 100;//200;
useInvAlpha = false;
spinRandomMin = 0;
spinRandomMax = 1;
spinSpeed = 1;
colors[0] = "0.886275 0.854902 0.733333 0.795276";
colors[1] = "0.356863 0.34902 0.321569 0.266";
colors[2] = "0.0235294 0.0235294 0.0235294 0.207";
sizes[0] = 1;//2;
sizes[1] = 5;
sizes[2] = 7;//0.5;
times[0] = 0.0;
times[1] = 0.25;
times[2] = 0.5;
animTexName = "data/FPSGameplay/art/particles/fireball.png";
times[3] = "1";
dragCoeffiecient = "1.99902";
sizes[3] = "10";
colors[3] = "0 0 0 0";
};
datablock ParticleEmitterData(GrenadeExpFireEmitter)
{
ejectionPeriodMS = 10;
periodVarianceMS = 5;//0;
ejectionVelocity = 1;//1.0;
velocityVariance = 0;//0.5;
thetaMin = 0.0;
thetaMax = 45;
lifetimeMS = 250;
particles = "GrenadeExpFire";
blendStyle = "ADDITIVE";
};
datablock ParticleData(GrenadeExpDust)
{
textureName = "data/FPSGameplay/art/particles/smoke.png";
dragCoeffiecient = 0.498534;
gravityCoefficient = 0;
inheritedVelFactor = 1;
constantAcceleration = 0.0;
lifetimeMS = 2000;
lifetimeVarianceMS = 250;
useInvAlpha = 0;
spinSpeed = 1;
spinRandomMin = -90.0;
spinRandomMax = 90.0;
colors[0] = "0.992126 0.992126 0.992126 0.96063";
colors[1] = "0.11811 0.11811 0.11811 0.929134";
colors[2] = "0.00392157 0.00392157 0.00392157 0.362205";
sizes[0] = 1.59922;
sizes[1] = 4.99603;
sizes[2] = 9.99817;
times[0] = 0.0;
times[1] = 0.494118;
times[2] = 1.0;
animTexName = "data/FPSGameplay/art/particles/smoke.png";
colors[3] = "0.996078 0.996078 0.996078 0";
sizes[3] = "15";
};
datablock ParticleEmitterData(GrenadeExpDustEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 8;
velocityVariance = 0.0;
ejectionOffset = 0.0;
thetaMin = 85;
thetaMax = 85;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = 0;
lifetimeMS = 2000;
particles = "GrenadeExpDust";
blendStyle = "NORMAL";
};
datablock ParticleData(GrenadeExpSpark)
{
textureName = "data/FPSGameplay/art/particles/Sparkparticle";
dragCoeffiecient = 1;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.2;
constantAcceleration = 0.0;
lifetimeMS = 500;
lifetimeVarianceMS = 250;
colors[0] = "0.6 0.4 0.3 1";
colors[1] = "0.6 0.4 0.3 1";
colors[2] = "1.0 0.4 0.3 0";
sizes[0] = 0.5;
sizes[1] = 0.75;
sizes[2] = 1;
times[0] = 0;
times[1] = 0.5;
times[2] = 1;
};
datablock ParticleEmitterData(GrenadeExpSparkEmitter)
{
ejectionPeriodMS = 2;
periodVarianceMS = 0;
ejectionVelocity = 20;
velocityVariance = 10;
ejectionOffset = 0.0;
thetaMin = 0;
thetaMax = 120;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
orientParticles = true;
lifetimeMS = 100;
particles = "GrenadeExpSpark";
};
datablock ParticleData(GrenadeExpSparks)
{
textureName = "data/FPSGameplay/art/particles/droplet";
dragCoeffiecient = 1;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.2;
constantAcceleration = 0.0;
lifetimeMS = 500;
lifetimeVarianceMS = 350;
colors[0] = "0.6 0.4 0.3 1.0";
colors[1] = "0.6 0.4 0.3 0.6";
colors[2] = "1.0 0.4 0.3 0.0";
sizes[0] = 0.5;
sizes[1] = 0.5;
sizes[2] = 0.75;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeExpSparksEmitter)
{
ejectionPeriodMS = 2;
periodVarianceMS = 0;
ejectionVelocity = 12;
velocityVariance = 6.75;
ejectionOffset = 0.0;
thetaMin = 0;
thetaMax = 60;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
orientParticles = true;
lifetimeMS = 100;
particles = "GrenadeExpSparks";
};
datablock ParticleData(GrenadeExpSmoke)
{
textureName = "data/FPSGameplay/art/particles/smoke";
dragCoeffiecient = 0;
gravityCoefficient = -0.40293;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 800;
lifetimeVarianceMS = 299;
useInvAlpha = true;
spinSpeed = 1;
spinRandomMin = -80.0;
spinRandomMax = 0;
colors[0] = "0.8 0.8 0.8 0.4";
colors[1] = "0.5 0.5 0.5 0.5";
colors[2] = "0.75 0.75 0.75 0";
sizes[0] = 4.49857;
sizes[1] = 7.49863;
sizes[2] = 11.2495;
times[0] = 0;
times[1] = 0.498039;
times[2] = 1;
animTexName = "data/FPSGameplay/art/particles/smoke";
times[3] = "1";
};
datablock ParticleEmitterData(GrenadeExpSmokeEmitter)
{
ejectionPeriodMS = 15;
periodVarianceMS = 5;
ejectionVelocity = 2.4;
velocityVariance = 1.2;
thetaMin = 0.0;
thetaMax = 180.0;
ejectionOffset = 1;
particles = "GrenadeExpSmoke";
blendStyle = "NORMAL";
};
// ----------------------------------------------------------------------------
// Dry/Air Explosion Objects
// ----------------------------------------------------------------------------
datablock ExplosionData(GrenadeExplosion)
{
soundProfile = GrenadeExplosionSound;
lifeTimeMS = 400; // Quick flash, short burn, and moderate dispersal
// Volume particles
particleEmitter = GrenadeExpFireEmitter;
particleDensity = 75;
particleRadius = 2.25;
// Point emission
emitter[0] = GrenadeExpDustEmitter;
emitter[1] = GrenadeExpSparksEmitter;
emitter[2] = GrenadeExpSmokeEmitter;
// Camera Shaking
shakeCamera = true;
camShakeFreq = "10.0 11.0 9.0";
camShakeAmp = "15.0 15.0 15.0";
camShakeDuration = 1.5;
camShakeRadius = 20;
// Exploding debris
debris = GrenadeDebris;
debrisThetaMin = 10;
debrisThetaMax = 60;
debrisNum = 4;
debrisNumVariance = 2;
debrisVelocity = 25;
debrisVelocityVariance = 5;
lightStartRadius = 4.0;
lightEndRadius = 0.0;
lightStartColor = "1.0 1.0 1.0";
lightEndColor = "1.0 1.0 1.0";
lightStartBrightness = 4.0;
lightEndBrightness = 0.0;
lightNormalOffset = 2.0;
};
// ----------------------------------------------------------------------------
// Water Explosion
// ----------------------------------------------------------------------------
datablock ParticleData(GLWaterExpDust)
{
textureName = "data/FPSGameplay/art/particles/steam";
dragCoeffiecient = 1.0;
gravityCoefficient = -0.01;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 2500;
lifetimeVarianceMS = 250;
useInvAlpha = false;
spinSpeed = 1;
spinRandomMin = -90.0;
spinRandomMax = 500.0;
colors[0] = "0.6 0.6 1.0 0.5";
colors[1] = "0.6 0.6 1.0 0.3";
sizes[0] = 0.25;
sizes[1] = 1.5;
times[0] = 0.0;
times[1] = 1.0;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpDustEmitter)
{
ejectionPeriodMS = 1;
periodVarianceMS = 0;
ejectionVelocity = 10;
velocityVariance = 0.0;
ejectionOffset = 0.0;
thetaMin = 85;
thetaMax = 85;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
lifetimeMS = 75;
particles = "GLWaterExpDust";
};
datablock ParticleData(GLWaterExpSparks)
{
textureName = "data/FPSGameplay/art/particles/spark_wet";
dragCoeffiecient = 1;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.2;
constantAcceleration = 0.0;
lifetimeMS = 500;
lifetimeVarianceMS = 250;
colors[0] = "0.6 0.6 1.0 1.0";
colors[1] = "0.6 0.6 1.0 1.0";
colors[2] = "0.6 0.6 1.0 0.0";
sizes[0] = 0.5;
sizes[1] = 0.5;
sizes[2] = 0.75;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpSparkEmitter)
{
ejectionPeriodMS = 2;
periodVarianceMS = 0;
ejectionVelocity = 12;
velocityVariance = 6.75;
ejectionOffset = 0.0;
thetaMin = 0;
thetaMax = 60;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
orientParticles = true;
lifetimeMS = 100;
particles = "GLWaterExpSparks";
};
datablock ParticleData(GLWaterExpSmoke)
{
textureName = "data/FPSGameplay/art/particles/smoke";
dragCoeffiecient = 0.4;
gravityCoefficient = -0.25;
inheritedVelFactor = 0.025;
constantAcceleration = -1.1;
lifetimeMS = 1250;
lifetimeVarianceMS = 0;
useInvAlpha = false;
spinSpeed = 1;
spinRandomMin = -200.0;
spinRandomMax = 200.0;
colors[0] = "0.1 0.1 1.0 1.0";
colors[1] = "0.4 0.4 1.0 1.0";
colors[2] = "0.4 0.4 1.0 0.0";
sizes[0] = 2.0;
sizes[1] = 6.0;
sizes[2] = 2.0;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpSmokeEmitter)
{
ejectionPeriodMS = 15;
periodVarianceMS = 0;
ejectionVelocity = 6.25;
velocityVariance = 0.25;
thetaMin = 0.0;
thetaMax = 90.0;
lifetimeMS = 250;
particles = "GLWaterExpSmoke";
};
datablock ParticleData(GLWaterExpBubbles)
{
textureName = "data/FPSGameplay/art/particles/millsplash01";
dragCoeffiecient = 0.0;
gravityCoefficient = -0.05;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 1500;
lifetimeVarianceMS = 250;
useInvAlpha = false;
spinRandomMin = -100.0;
spinRandomMax = 100.0;
spinSpeed = 1;
colors[0] = "0.7 0.8 1.0 0.0";
colors[1] = "0.7 0.8 1.0 0.4";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.2;
sizes[1] = 0.4;
sizes[2] = 0.8;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpBubbleEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 1.0;
ejectionOffset = 3.0;
velocityVariance = 0.5;
thetaMin = 0;
thetaMax = 80;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
particles = "GLWaterExpBubbles";
};
datablock ExplosionData(GrenadeLauncherWaterExplosion)
{
//soundProfile = GLWaterExplosionSound;
emitter[0] = GLWaterExpDustEmitter;
emitter[1] = GLWaterExpSparkEmitter;
emitter[2] = GLWaterExpSmokeEmitter;
emitter[3] = GLWaterExpBubbleEmitter;
shakeCamera = true;
camShakeFreq = "10.0 11.0 9.0";
camShakeAmp = "20.0 20.0 20.0";
camShakeDuration = 1.5;
camShakeRadius = 20.0;
lightStartRadius = 20.0;
lightEndRadius = 0.0;
lightStartColor = "0.9 0.9 0.8";
lightEndColor = "0.6 0.6 1.0";
lightStartBrightness = 2.0;
lightEndBrightness = 0.0;
};
// ----------------------------------------------------------------------------
// Dry/Air Explosion Objects
// ----------------------------------------------------------------------------
datablock ExplosionData(GrenadeSubExplosion)
{
offset = 0.25;
emitter[0] = GrenadeExpSparkEmitter;
lightStartRadius = 4.0;
lightEndRadius = 0.0;
lightStartColor = "0.9 0.7 0.7";
lightEndColor = "0.9 0.7 0.7";
lightStartBrightness = 2.0;
lightEndBrightness = 0.0;
};
datablock ExplosionData(GrenadeLauncherExplosion)
{
soundProfile = GrenadeLauncherExplosionSound;
lifeTimeMS = 400; // Quick flash, short burn, and moderate dispersal
// Volume particles
particleEmitter = GrenadeExpFireEmitter;
particleDensity = 75;
particleRadius = 2.25;
// Point emission
emitter[0] = GrenadeExpDustEmitter;
emitter[1] = GrenadeExpSparksEmitter;
emitter[2] = GrenadeExpSmokeEmitter;
// Sub explosion objects
subExplosion[0] = GrenadeSubExplosion;
// Camera Shaking
shakeCamera = true;
camShakeFreq = "10.0 11.0 9.0";
camShakeAmp = "15.0 15.0 15.0";
camShakeDuration = 1.5;
camShakeRadius = 20;
// Exploding debris
debris = GrenadeDebris;
debrisThetaMin = 10;
debrisThetaMax = 60;
debrisNum = 4;
debrisNumVariance = 2;
debrisVelocity = 25;
debrisVelocityVariance = 5;
lightStartRadius = 4.0;
lightEndRadius = 0.0;
lightStartColor = "1.0 1.0 1.0";
lightEndColor = "1.0 1.0 1.0";
lightStartBrightness = 4.0;
lightEndBrightness = 0.0;
lightNormalOffset = 2.0;
};
// ----------------------------------------------------------------------------
// Underwater Grenade projectile trail
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeTrailWaterParticle)
{
textureName = "data/FPSGameplay/art/particles/bubble";
dragCoeffiecient = 0.0;
gravityCoefficient = 0.1;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 1500;
lifetimeVarianceMS = 600;
useInvAlpha = false;
spinRandomMin = -100.0;
spinRandomMax = 100.0;
spinSpeed = 1;
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.4";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.05;
sizes[1] = 0.05;
sizes[2] = 0.05;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeTrailWaterEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 1.0;
ejectionOffset = 0.1;
velocityVariance = 0.5;
thetaMin = 0.0;
thetaMax = 80.0;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
particles = GrenadeTrailWaterParticle;
};
// ----------------------------------------------------------------------------
// Normal-fire Projectile Object
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeProjSmokeTrail)
{
textureName = "data/FPSGameplay/art/particles/smoke";
dragCoeffiecient = 0.0;
gravityCoefficient = -0.2;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 750;
lifetimeVarianceMS = 250;
useInvAlpha = true;
spinRandomMin = -60;
spinRandomMax = 60;
spinSpeed = 1;
colors[0] = "0.9 0.8 0.8 0.6";
colors[1] = "0.6 0.6 0.6 0.9";
colors[2] = "0.3 0.3 0.3 0";
sizes[0] = 0.25;
sizes[1] = 0.5;
sizes[2] = 0.75;
times[0] = 0.0;
times[1] = 0.4;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeProjSmokeTrailEmitter)
{
ejectionPeriodMS = 10;
periodVarianceMS = 0;
ejectionVelocity = 0.75;
velocityVariance = 0;
thetaMin = 0.0;
thetaMax = 0.0;
phiReferenceVel = 90;
phiVariance = 0;
particles = "GrenadeProjSmokeTrail";
};
datablock ProjectileData(GrenadeLauncherProjectile)
{
projectileShapeName = "data/FPSGameplay/art/shapes/weapons/shared/rocket.dts";
directDamage = 30;
radiusDamage = 30;
damageRadius = 5;
areaImpulse = 2000;
explosion = GrenadeLauncherExplosion;
waterExplosion = GrenadeLauncherWaterExplosion;
decal = ScorchRXDecal;
splash = GrenadeSplash;
particleEmitter = GrenadeProjSmokeTrailEmitter;
particleWaterEmitter = GrenadeTrailWaterEmitter;
muzzleVelocity = 30;
velInheritFactor = 0.3;
armingDelay = 2000;
lifetime = 10000;
fadeDelay = 4500;
bounceElasticity = 0.4;
bounceFriction = 0.3;
isBallistic = true;
gravityMod = 0.9;
lightDesc = GrenadeLauncherLightDesc;
damageType = "GrenadeDamage";
};
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests;
using ObjectFormatterFixtures;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests
{
public class ObjectFormatterTests : ObjectFormatterTestBase
{
private static readonly ObjectFormatter Formatter = new TestCSharpObjectFormatter();
[Fact]
public void Objects()
{
string str;
object nested = new Outer.Nested<int>();
str = Formatter.FormatObject(nested, SingleLineOptions);
Assert.Equal(@"Outer.Nested<int> { A=1, B=2 }", str);
str = Formatter.FormatObject(nested, HiddenOptions);
Assert.Equal(@"Outer.Nested<int>", str);
str = Formatter.FormatObject(A<int>.X, HiddenOptions);
Assert.Equal(@"A<int>.B<int>", str);
object obj = new A<int>.B<bool>.C.D<string, double>.E();
str = Formatter.FormatObject(obj, HiddenOptions);
Assert.Equal(@"A<int>.B<bool>.C.D<string, double>.E", str);
var sort = new Sort();
str = new TestCSharpObjectFormatter(maximumLineLength: 51).FormatObject(sort, SingleLineOptions);
Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, aF=-1...", str);
Assert.Equal(51 + 3, str.Length);
str = new TestCSharpObjectFormatter(maximumLineLength: 5).FormatObject(sort, SingleLineOptions);
Assert.Equal(@"Sort ...", str);
Assert.Equal(5 + 3, str.Length);
str = new TestCSharpObjectFormatter(maximumLineLength: 4).FormatObject(sort, SingleLineOptions);
Assert.Equal(@"Sort...", str);
str = new TestCSharpObjectFormatter(maximumLineLength: 3).FormatObject(sort, SingleLineOptions);
Assert.Equal(@"Sor...", str);
str = new TestCSharpObjectFormatter(maximumLineLength: 2).FormatObject(sort, SingleLineOptions);
Assert.Equal(@"So...", str);
str = new TestCSharpObjectFormatter(maximumLineLength: 1).FormatObject(sort, SingleLineOptions);
Assert.Equal(@"S...", str);
str = new TestCSharpObjectFormatter(maximumLineLength: 80).FormatObject(sort, SingleLineOptions);
Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, aF=-1, AG=1 }", str);
}
[Fact]
public void ArrayOfInt32_NoMembers()
{
object o = new int[4] { 3, 4, 5, 6 };
var str = Formatter.FormatObject(o, HiddenOptions);
Assert.Equal("int[4] { 3, 4, 5, 6 }", str);
}
#region DANGER: Debugging this method under VS2010 might freeze your machine.
[Fact]
public void RecursiveRootHidden()
{
var DO_NOT_ADD_TO_WATCH_WINDOW = new RecursiveRootHidden();
DO_NOT_ADD_TO_WATCH_WINDOW.C = DO_NOT_ADD_TO_WATCH_WINDOW;
string str = Formatter.FormatObject(DO_NOT_ADD_TO_WATCH_WINDOW, SingleLineOptions);
Assert.Equal(@"RecursiveRootHidden { A=0, B=0 }", str);
}
#endregion
[Fact]
public void DebuggerDisplay_ParseSimpleMemberName()
{
Test_ParseSimpleMemberName("foo", name: "foo", callable: false, nq: false);
Test_ParseSimpleMemberName("foo ", name: "foo", callable: false, nq: false);
Test_ParseSimpleMemberName(" foo", name: "foo", callable: false, nq: false);
Test_ParseSimpleMemberName(" foo ", name: "foo", callable: false, nq: false);
Test_ParseSimpleMemberName("foo()", name: "foo", callable: true, nq: false);
Test_ParseSimpleMemberName("\nfoo (\r\n)", name: "foo", callable: true, nq: false);
Test_ParseSimpleMemberName(" foo ( \t) ", name: "foo", callable: true, nq: false);
Test_ParseSimpleMemberName("foo,nq", name: "foo", callable: false, nq: true);
Test_ParseSimpleMemberName("foo ,nq", name: "foo", callable: false, nq: true);
Test_ParseSimpleMemberName("foo(),nq", name: "foo", callable: true, nq: true);
Test_ParseSimpleMemberName(" foo \t( ) ,nq", name: "foo", callable: true, nq: true);
Test_ParseSimpleMemberName(" foo \t( ) , nq", name: "foo", callable: true, nq: true);
Test_ParseSimpleMemberName("foo, nq", name: "foo", callable: false, nq: true);
Test_ParseSimpleMemberName("foo(,nq", name: "foo(", callable: false, nq: true);
Test_ParseSimpleMemberName("foo),nq", name: "foo)", callable: false, nq: true);
Test_ParseSimpleMemberName("foo ( ,nq", name: "foo (", callable: false, nq: true);
Test_ParseSimpleMemberName("foo ) ,nq", name: "foo )", callable: false, nq: true);
Test_ParseSimpleMemberName(",nq", name: "", callable: false, nq: true);
Test_ParseSimpleMemberName(" ,nq", name: "", callable: false, nq: true);
}
private void Test_ParseSimpleMemberName(string value, string name, bool callable, bool nq)
{
bool actualNoQuotes, actualIsCallable;
string actualName = ObjectFormatterHelpers.ParseSimpleMemberName(value, 0, value.Length, out actualNoQuotes, out actualIsCallable);
Assert.Equal(name, actualName);
Assert.Equal(nq, actualNoQuotes);
Assert.Equal(callable, actualIsCallable);
actualName = ObjectFormatterHelpers.ParseSimpleMemberName("---" + value + "-", 3, 3 + value.Length, out actualNoQuotes, out actualIsCallable);
Assert.Equal(name, actualName);
Assert.Equal(nq, actualNoQuotes);
Assert.Equal(callable, actualIsCallable);
}
[Fact]
public void DebuggerDisplay()
{
string str;
var a = new ComplexProxy();
str = Formatter.FormatObject(a, SeparateLinesOptions);
AssertMembers(str, @"[AStr]",
@"_02_public_property_dd: *1",
@"_03_private_property_dd: *2",
@"_04_protected_property_dd: *3",
@"_05_internal_property_dd: *4",
@"_07_private_field_dd: +2",
@"_08_protected_field_dd: +3",
@"_09_internal_field_dd: +4",
@"_10_private_collapsed: 0",
@"_12_public: 0",
@"_13_private: 0",
@"_14_protected: 0",
@"_15_internal: 0",
"_16_eolns: ==\r\n=\r\n=",
@"_17_braces_0: =={==",
@"_17_braces_1: =={{==",
@"_17_braces_2: ==!<Member ''{'' not found>==",
@"_17_braces_3: ==!<Member ''\{'' not found>==",
@"_17_braces_4: ==!<Member '1/*{*/' not found>==",
@"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==",
@"_17_braces_6: ==!<Member ''{'/*' not found>*/}==",
@"_19_escapes: ==\{\x\t==",
@"_21: !<Member '1+1' not found>",
@"_22: !<Member '""xxx""' not found>",
@"_23: !<Member '""xxx""' not found>",
@"_24: !<Member ''x'' not found>",
@"_25: !<Member ''x'' not found>",
@"_26_0: !<Method 'new B' not found>",
@"_26_1: !<Method 'new D' not found>",
@"_26_2: !<Method 'new E' not found>",
@"_26_3: ",
@"_26_4: !<Member 'F1(1)' not found>",
@"_26_5: 1",
@"_26_6: 2",
@"A: 1",
@"B: 2",
@"_28: [CStr]",
@"_29_collapsed: [CStr]",
@"_31: 0",
@"_32: 0",
@"_33: 0",
@"_34_Exception: !<Exception>",
@"_35_Exception: -!-",
@"_36: !<MyException>",
@"_38_private_get_public_set: 1",
@"_39_public_get_private_set: 1",
@"_40_private_get_private_set: 1"
);
var b = new TypeWithComplexProxy();
str = Formatter.FormatObject(b, SeparateLinesOptions);
AssertMembers(str, @"[BStr]",
@"_02_public_property_dd: *1",
@"_04_protected_property_dd: *3",
@"_08_protected_field_dd: +3",
@"_10_private_collapsed: 0",
@"_12_public: 0",
@"_14_protected: 0",
"_16_eolns: ==\r\n=\r\n=",
@"_17_braces_0: =={==",
@"_17_braces_1: =={{==",
@"_17_braces_2: ==!<Member ''{'' not found>==",
@"_17_braces_3: ==!<Member ''\{'' not found>==",
@"_17_braces_4: ==!<Member '1/*{*/' not found>==",
@"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==",
@"_17_braces_6: ==!<Member ''{'/*' not found>*/}==",
@"_19_escapes: ==\{\x\t==",
@"_21: !<Member '1+1' not found>",
@"_22: !<Member '""xxx""' not found>",
@"_23: !<Member '""xxx""' not found>",
@"_24: !<Member ''x'' not found>",
@"_25: !<Member ''x'' not found>",
@"_26_0: !<Method 'new B' not found>",
@"_26_1: !<Method 'new D' not found>",
@"_26_2: !<Method 'new E' not found>",
@"_26_3: ",
@"_26_4: !<Member 'F1(1)' not found>",
@"_26_5: 1",
@"_26_6: 2",
@"A: 1",
@"B: 2",
@"_28: [CStr]",
@"_29_collapsed: [CStr]",
@"_31: 0",
@"_32: 0",
@"_34_Exception: !<Exception>",
@"_35_Exception: -!-",
@"_36: !<MyException>",
@"_38_private_get_public_set: 1",
@"_39_public_get_private_set: 1"
);
}
[Fact]
public void DebuggerDisplay_Inherited()
{
var obj = new InheritedDebuggerDisplay();
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("InheritedDebuggerDisplay(DebuggerDisplayValue)", str);
}
[Fact]
public void DebuggerProxy_DebuggerDisplayAndProxy()
{
var obj = new TypeWithDebuggerDisplayAndProxy();
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("TypeWithDebuggerDisplayAndProxy(DD) { A=0, B=0 }", str);
str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "TypeWithDebuggerDisplayAndProxy(DD)",
"A: 0",
"B: 0"
);
}
[Fact]
public void DebuggerProxy_Recursive()
{
string str;
object obj = new RecursiveProxy.Node(0);
str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "RecursiveProxy.Node",
"x: 0",
"y: RecursiveProxy.Node { x=1, y=RecursiveProxy.Node { x=2, y=RecursiveProxy.Node { x=3, y=RecursiveProxy.Node { x=4, y=RecursiveProxy.Node { x=5, y=null } } } } }"
);
obj = new InvalidRecursiveProxy.Node();
str = Formatter.FormatObject(obj, SeparateLinesOptions);
// TODO: better overflow handling
Assert.Equal("!<Stack overflow while evaluating object>", str);
}
[Fact]
public void Array_Recursive()
{
string str;
ListNode n2;
ListNode n1 = new ListNode();
object[] obj = new object[5];
obj[0] = 1;
obj[1] = obj;
obj[2] = n2 = new ListNode() { data = obj, next = n1 };
obj[3] = new object[] { 4, 5, obj, 6, new ListNode() };
obj[4] = 3;
n1.next = n2;
n1.data = new object[] { 7, n2, 8, obj };
str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "object[5]",
"1",
"{ ... }",
"ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }",
"object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }",
"3"
);
str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal(str, "object[5] { 1, { ... }, ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }, object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }, 3 }");
}
[Fact]
public void LargeGraph()
{
var list = new LinkedList<object>();
object obj = list;
for (int i = 0; i < 10000; i++)
{
var node = list.AddFirst(i);
var newList = new LinkedList<object>();
list.AddAfter(node, newList);
list = newList;
}
string output = "LinkedList<object>(2) { 0, LinkedList<object>(2) { 1, LinkedList<object>(2) { 2, LinkedList<object>(2) {";
for (int i = 100; i > 4; i--)
{
var printOptions = new PrintOptions
{
MaximumOutputLength = i,
MemberDisplayFormat = MemberDisplayFormat.SingleLine,
};
var actual = Formatter.FormatObject(obj, printOptions);
var expected = output.Substring(0, i) + "...";
Assert.Equal(expected, actual);
}
}
[Fact]
public void LongMembers()
{
object obj = new LongMembers();
var str = new TestCSharpObjectFormatter(maximumLineLength: 20).FormatObject(obj, SingleLineOptions);
Assert.Equal("LongMembers { LongNa...", str);
str = new TestCSharpObjectFormatter(maximumLineLength: 20).FormatObject(obj, SeparateLinesOptions);
Assert.Equal("LongMembers {\r\n LongName0123456789...\r\n LongValue: \"012345...\r\n}\r\n", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_Array()
{
var obj = new Object[] { new C(), 1, "str", 'c', true, null, new bool[] { true, false, true, false } };
var str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "object[7]",
"[CStr]",
"1",
"\"str\"",
"'c'",
"true",
"null",
"bool[4] { true, false, true, false }"
);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_MdArray()
{
string str;
int[,,] a = new int[2, 3, 4]
{
{
{ 000, 001, 002, 003 },
{ 010, 011, 012, 013 },
{ 020, 021, 022, 023 },
},
{
{ 100, 101, 102, 103 },
{ 110, 111, 112, 113 },
{ 120, 121, 122, 123 },
}
};
str = Formatter.FormatObject(a, SingleLineOptions);
Assert.Equal("int[2, 3, 4] { { { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } } }", str);
str = Formatter.FormatObject(a, SeparateLinesOptions);
AssertMembers(str, "int[2, 3, 4]",
"{ { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }",
"{ { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } }"
);
int[][,][,,,] obj = new int[2][,][,,,];
obj[0] = new int[1, 2][,,,];
obj[0][0, 0] = new int[1, 2, 3, 4];
str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("int[2][,][,,,] { int[1, 2][,,,] { { int[1, 2, 3, 4] { { { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } } } }, null } }, null }", str);
Array x = Array.CreateInstance(typeof(Object), lengths: new int[] { 2, 3 }, lowerBounds: new int[] { 2, 9 });
str = Formatter.FormatObject(x, SingleLineOptions);
Assert.Equal("object[2..4, 9..12] { { null, null, null }, { null, null, null } }", str);
Array y = Array.CreateInstance(typeof(Object), lengths: new int[] { 1, 1 }, lowerBounds: new int[] { 0, 0 });
str = Formatter.FormatObject(y, SingleLineOptions);
Assert.Equal("object[1, 1] { { null } }", str);
Array z = Array.CreateInstance(typeof(Object), lengths: new int[] { 0, 0 }, lowerBounds: new int[] { 0, 0 });
str = Formatter.FormatObject(z, SingleLineOptions);
Assert.Equal("object[0, 0] { }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_IEnumerable()
{
string str;
object obj;
obj = Enumerable.Range(0, 10);
str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("RangeIterator { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_IEnumerable_Exception()
{
string str;
object obj;
obj = Enumerable.Range(0, 10).Where(i => { if (i == 5) throw new Exception("xxx"); return i < 7; });
str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("Enumerable.WhereEnumerableIterator<int> { 0, 1, 2, 3, 4, !<Exception> ... }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_IDictionary()
{
string str;
object obj;
obj = new ThrowingDictionary(throwAt: -1);
str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 } }", str);
str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "ThrowingDictionary(10)",
"{ 1, 1 }",
"{ 2, 2 }",
"{ 3, 3 }",
"{ 4, 4 }"
);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_IDictionary_Exception()
{
string str;
object obj;
obj = new ThrowingDictionary(throwAt: 3);
str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, !<Exception> ... }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_BitArray()
{
// BitArray doesn't have debugger proxy/display
var obj = new System.Collections.BitArray(new int[] { 1 });
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("BitArray(32) { true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_Queue()
{
var obj = new Queue<int>();
obj.Enqueue(1);
obj.Enqueue(2);
obj.Enqueue(3);
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("Queue<int>(3) { 1, 2, 3 }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_Stack()
{
var obj = new Stack<int>();
obj.Push(1);
obj.Push(2);
obj.Push(3);
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("Stack<int>(3) { 3, 2, 1 }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_Dictionary()
{
var obj = new Dictionary<string, int>
{
{ "x", 1 },
};
var str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "Dictionary<string, int>(1)",
"{ \"x\", 1 }"
);
str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("Dictionary<string, int>(1) { { \"x\", 1 } }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_KeyValuePair()
{
var obj = new KeyValuePair<int, string>(1, "x");
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("KeyValuePair<int, string> { 1, \"x\" }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_List()
{
var obj = new List<object> { 1, 2, 'c' };
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("List<object>(3) { 1, 2, 'c' }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_LinkedList()
{
var obj = new LinkedList<int>();
obj.AddLast(1);
obj.AddLast(2);
obj.AddLast(3);
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("LinkedList<int>(3) { 1, 2, 3 }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_SortedList()
{
var obj = new SortedList<int, int>();
obj.Add(3, 4);
obj.Add(1, 5);
obj.Add(2, 6);
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("SortedList<int, int>(3) { { 1, 5 }, { 2, 6 }, { 3, 4 } }", str);
var obj2 = new SortedList<int[], int[]>();
obj2.Add(new[] { 3 }, new int[] { 4 });
str = Formatter.FormatObject(obj2, SingleLineOptions);
Assert.Equal("SortedList<int[], int[]>(1) { { int[1] { 3 }, int[1] { 4 } } }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_SortedDictionary()
{
var obj = new SortedDictionary<int, int>();
obj.Add(1, 0x1a);
obj.Add(3, 0x3c);
obj.Add(2, 0x2b);
var str = Formatter.
FormatObject(obj, new PrintOptions { NumberRadix = ObjectFormatterHelpers.NumberRadixHexadecimal });
Assert.Equal("SortedDictionary<int, int>(3) { { 0x00000001, 0x0000001a }, { 0x00000002, 0x0000002b }, { 0x00000003, 0x0000003c } }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_HashSet()
{
var obj = new HashSet<int>();
obj.Add(1);
obj.Add(2);
// HashSet doesn't implement ICollection (it only implements ICollection<T>) so we don't call Count,
// instead a DebuggerDisplay.Value is used.
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("HashSet<int>(Count = 2) { 1, 2 }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_SortedSet()
{
var obj = new SortedSet<int>();
obj.Add(1);
obj.Add(2);
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("SortedSet<int>(2) { 1, 2 }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_ConcurrentDictionary()
{
var obj = new ConcurrentDictionary<string, int>();
obj.AddOrUpdate("x", 1, (k, v) => v);
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("ConcurrentDictionary<string, int>(1) { { \"x\", 1 } }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_ConcurrentQueue()
{
var obj = new ConcurrentQueue<object>();
obj.Enqueue(1);
obj.Enqueue(2);
obj.Enqueue(3);
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("ConcurrentQueue<object>(3) { 1, 2, 3 }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_ConcurrentStack()
{
var obj = new ConcurrentStack<object>();
obj.Push(1);
obj.Push(2);
obj.Push(3);
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("ConcurrentStack<object>(3) { 3, 2, 1 }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_BlockingCollection()
{
var obj = new BlockingCollection<int>();
obj.Add(1);
obj.Add(2, new CancellationToken());
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("BlockingCollection<int>(2) { 1, 2 }", str);
}
// TODO(tomat): this only works with System.dll file version 30319.16644 (Win8 build)
//[Fact]
//public void DebuggerProxy_FrameworkTypes_ConcurrentBag()
//{
// var obj = new ConcurrentBag<int>();
// obj.Add(1);
// var str = ObjectFormatter.Instance.FormatObject(obj, quoteStrings: true, memberFormat: MemberDisplayFormat.Inline);
// Assert.Equal("ConcurrentBag<int>(1) { 1 }", str);
//}
[Fact]
public void DebuggerProxy_FrameworkTypes_ReadOnlyCollection()
{
var obj = new System.Collections.ObjectModel.ReadOnlyCollection<int>(new[] { 1, 2, 3 });
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("ReadOnlyCollection<int>(3) { 1, 2, 3 }", str);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_Lazy()
{
var obj = new Lazy<int[]>(() => new int[] { 1, 2 }, LazyThreadSafetyMode.None);
// Lazy<T> has both DebuggerDisplay and DebuggerProxy attributes and both display the same information.
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null) { IsValueCreated=false, IsValueFaulted=false, Mode=None, Value=null }", str);
str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null)",
"IsValueCreated: false",
"IsValueFaulted: false",
"Mode: None",
"Value: null"
);
Assert.NotNull(obj.Value);
str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 }) { IsValueCreated=true, IsValueFaulted=false, Mode=None, Value=int[2] { 1, 2 } }", str);
str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 })",
"IsValueCreated: true",
"IsValueFaulted: false",
"Mode: None",
"Value: int[2] { 1, 2 }"
);
}
public void TaskMethod()
{
}
[Fact]
public void DebuggerProxy_FrameworkTypes_Task()
{
var obj = new System.Threading.Tasks.Task(TaskMethod);
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal(
@"Task(Id = *, Status = Created, Method = ""Void TaskMethod()"") { AsyncState=null, CancellationPending=false, CreationOptions=None, Exception=null, Id=*, Status=Created }",
FilterDisplayString(str));
str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(FilterDisplayString(str), @"Task(Id = *, Status = Created, Method = ""Void TaskMethod()"")",
"AsyncState: null",
"CancellationPending: false",
"CreationOptions: None",
"Exception: null",
"Id: *",
"Status: Created"
);
}
[Fact]
public void DebuggerProxy_FrameworkTypes_SpinLock()
{
var obj = new SpinLock();
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("SpinLock(IsHeld = false) { IsHeld=false, IsHeldByCurrentThread=false, OwnerThreadID=0 }", str);
str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "SpinLock(IsHeld = false)",
"IsHeld: false",
"IsHeldByCurrentThread: false",
"OwnerThreadID: 0"
);
}
[Fact]
public void DebuggerProxy_DiagnosticBag()
{
var obj = new DiagnosticBag();
obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_AbstractAndExtern, "bar"), NoLocation.Singleton);
obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_BadExternIdentifier, "foo"), NoLocation.Singleton);
using (new EnsureEnglishUICulture())
{
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("DiagnosticBag(Count = 2) { =error CS0180: 'bar' cannot be both extern and abstract, =error CS1679: Invalid extern alias for '/reference'; 'foo' is not a valid identifier }", str);
str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "DiagnosticBag(Count = 2)",
": error CS0180: 'bar' cannot be both extern and abstract",
": error CS1679: Invalid extern alias for '/reference'; 'foo' is not a valid identifier"
);
}
}
[Fact]
public void DebuggerProxy_ArrayBuilder()
{
var obj = new ArrayBuilder<int>();
obj.AddRange(new[] { 1, 2, 3, 4, 5 });
var str = Formatter.FormatObject(obj, SingleLineOptions);
Assert.Equal("ArrayBuilder<int>(Count = 5) { 1, 2, 3, 4, 5 }", str);
str = Formatter.FormatObject(obj, SeparateLinesOptions);
AssertMembers(str, "ArrayBuilder<int>(Count = 5)",
"1",
"2",
"3",
"4",
"5"
);
}
// The stack trace contains line numbers. We use a #line directive
// so that the baseline doesn't need to be updated every time this
// file changes.
//
// When adding a new test to this region, ADD IT ADD THE END, so you
// don't have to update all the other baselines.
#line 10000 "z:\Fixture.cs"
private static class Fixture
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Method()
{
throw new Exception();
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Method<U>()
{
throw new Exception();
}
}
private static class Fixture<T>
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Method()
{
throw new Exception();
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Method<U>()
{
throw new Exception();
}
}
[Fact]
public void StackTrace_NonGeneric()
{
try
{
Fixture.Method();
}
catch (Exception e)
{
const string filePath = @"z:\Fixture.cs";
var expected =
$@"Exception of type 'System.Exception' was thrown.
+ Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture.Method(){string.Format(ScriptingResources.AtFileLine, filePath, 10006)}
+ Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_NonGeneric(){string.Format(ScriptingResources.AtFileLine, filePath, 10036)}
";
var actual = Formatter.FormatUnhandledException(e);
Assert.Equal(expected, actual);
}
}
[Fact]
public void StackTrace_GenericMethod()
{
try
{
Fixture.Method<char>();
}
catch (Exception e)
{
const string filePath = @"z:\Fixture.cs";
// TODO (DevDiv #173210): Should show Fixture.Method<char>
var expected =
$@"Exception of type 'System.Exception' was thrown.
+ Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture.Method<U>(){string.Format(ScriptingResources.AtFileLine, filePath, 10012)}
+ Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericMethod(){string.Format(ScriptingResources.AtFileLine, filePath, 10057)}
";
var actual = Formatter.FormatUnhandledException(e);
Assert.Equal(expected, actual);
}
}
[Fact]
public void StackTrace_GenericType()
{
try
{
Fixture<int>.Method();
}
catch (Exception e)
{
const string filePath = @"z:\Fixture.cs";
// TODO (DevDiv #173210): Should show Fixture<int>.Method
var expected =
$@"Exception of type 'System.Exception' was thrown.
+ Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture<T>.Method(){string.Format(ScriptingResources.AtFileLine, filePath, 10021)}
+ Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericType(){string.Format(ScriptingResources.AtFileLine, filePath, 10079)}
";
var actual = Formatter.FormatUnhandledException(e);
Assert.Equal(expected, actual);
}
}
[Fact]
public void StackTrace_GenericMethodInGenericType()
{
try
{
Fixture<int>.Method<char>();
}
catch(Exception e)
{
const string filePath = @"z:\Fixture.cs";
// TODO (DevDiv #173210): Should show Fixture<int>.Method<char>
var expected =
$@"Exception of type 'System.Exception' was thrown.
+ Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture<T>.Method<U>(){string.Format(ScriptingResources.AtFileLine, filePath, 10027)}
+ Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericMethodInGenericType(){string.Format(ScriptingResources.AtFileLine, filePath, 10101)}
";
var actual = Formatter.FormatUnhandledException(e);
Assert.Equal(expected, actual);
}
}
}
}
| |
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Topshelf.Logging
{
using System;
using NLog;
/// <summary>
/// A logger that wraps to NLog. See http://stackoverflow.com/questions/7412156/how-to-retain-callsite-information-when-wrapping-nlog
/// </summary>
public class NLogLogWriter :
LogWriter
{
readonly Logger _log;
/// <summary>
/// Create a new NLog logger instance.
/// </summary>
/// <param name="log"> </param>
/// <param name="name"> Name of type to log as. </param>
public NLogLogWriter(Logger log, string name)
{
if (name == null)
throw new ArgumentNullException("name");
_log = log;
}
public bool IsDebugEnabled
{
get { return _log.IsDebugEnabled; }
}
public bool IsInfoEnabled
{
get { return _log.IsInfoEnabled; }
}
public bool IsWarnEnabled
{
get { return _log.IsWarnEnabled; }
}
public bool IsErrorEnabled
{
get { return _log.IsErrorEnabled; }
}
public bool IsFatalEnabled
{
get { return _log.IsFatalEnabled; }
}
public void Log(LoggingLevel level, object obj)
{
_log.Log(GetNLogLevel(level), obj);
}
public void Log(LoggingLevel level, object obj, Exception exception)
{
_log.Log(GetNLogLevel(level), obj == null
? ""
: obj.ToString(), exception);
}
public void Log(LoggingLevel level, LogWriterOutputProvider messageProvider)
{
_log.Log(GetNLogLevel(level), ToGenerator(messageProvider));
}
public void LogFormat(LoggingLevel level, IFormatProvider formatProvider, string format,
params object[] args)
{
_log.Log(GetNLogLevel(level), formatProvider, format, args);
}
public void LogFormat(LoggingLevel level, string format, params object[] args)
{
_log.Log(GetNLogLevel(level), format, args);
}
public void Debug(object obj)
{
_log.Log(LogLevel.Debug, obj);
}
public void Debug(object obj, Exception exception)
{
_log.Log(LogLevel.Debug, obj == null
? ""
: obj.ToString(), exception);
}
public void Debug(LogWriterOutputProvider messageProvider)
{
_log.Debug(ToGenerator(messageProvider));
}
public void Info(object obj)
{
_log.Log(LogLevel.Info, obj);
}
public void Info(object obj, Exception exception)
{
_log.Log(LogLevel.Info, obj == null
? ""
: obj.ToString(), exception);
}
public void Info(LogWriterOutputProvider messageProvider)
{
_log.Info(ToGenerator(messageProvider));
}
public void Warn(object obj)
{
_log.Log(LogLevel.Warn, obj);
}
public void Warn(object obj, Exception exception)
{
_log.Log(LogLevel.Warn, obj == null
? ""
: obj.ToString(), exception);
}
public void Warn(LogWriterOutputProvider messageProvider)
{
_log.Warn(ToGenerator(messageProvider));
}
public void Error(object obj)
{
_log.Log(LogLevel.Error, obj);
}
public void Error(object obj, Exception exception)
{
_log.Log(LogLevel.Error, obj == null
? ""
: obj.ToString(), exception);
}
public void Error(LogWriterOutputProvider messageProvider)
{
_log.Error(ToGenerator(messageProvider));
}
public void Fatal(object obj)
{
_log.Log(LogLevel.Fatal, obj);
}
public void Fatal(object obj, Exception exception)
{
_log.Log(LogLevel.Fatal, obj == null
? ""
: obj.ToString(), exception);
}
public void Fatal(LogWriterOutputProvider messageProvider)
{
_log.Fatal(ToGenerator(messageProvider));
}
public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(LogLevel.Debug, formatProvider, format, args);
}
public void DebugFormat(string format, params object[] args)
{
_log.Log(LogLevel.Debug, format, args);
}
public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(LogLevel.Info, formatProvider, format, args);
}
public void InfoFormat(string format, params object[] args)
{
_log.Log(LogLevel.Info, format, args);
}
public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(LogLevel.Warn, formatProvider, format, args);
}
public void WarnFormat(string format, params object[] args)
{
_log.Log(LogLevel.Warn, format, args);
}
public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(LogLevel.Error, formatProvider, format, args);
}
public void ErrorFormat(string format, params object[] args)
{
_log.Log(LogLevel.Error, format, args);
}
public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
{
_log.Log(LogLevel.Fatal, formatProvider, format, args);
}
public void FatalFormat(string format, params object[] args)
{
_log.Log(LogLevel.Fatal, format, args);
}
LogLevel GetNLogLevel(LoggingLevel level)
{
if (level == LoggingLevel.Fatal)
return LogLevel.Fatal;
if (level == LoggingLevel.Error)
return LogLevel.Error;
if (level == LoggingLevel.Warn)
return LogLevel.Warn;
if (level == LoggingLevel.Info)
return LogLevel.Info;
if (level == LoggingLevel.Debug)
return LogLevel.Debug;
if (level == LoggingLevel.All)
return LogLevel.Trace;
return LogLevel.Off;
}
LogMessageGenerator ToGenerator(LogWriterOutputProvider provider)
{
return () =>
{
object obj = provider();
return obj == null
? ""
: obj.ToString();
};
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
#if EF7
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
#else
using System.Data.Entity;
#endif
namespace Microsoft.Restier.Samples.Northwind.Models
{
public class NorthwindContext : DbContext
{
static NorthwindContext()
{
LoadDataSource();
}
#if EF7
public NorthwindContext()
{
// TODO : remove those as we will initialize the db in static ctor.
try
{
if (!Database.AsRelational().Exists())
{
LoadDataSource();
}
}
catch
{
ResetDataSource();
}
}
protected override void OnConfiguring(EntityOptionsBuilder optionsBuilder)
{
// TODO GitHubIssue#57: Complete EF7 to EDM model mapping
// Seems for now EF7 can't support named connection string like "name=NorthwindConnection",
// find an equivalent approach when it's ready.
optionsBuilder.UseSqlServer(@"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Northwind.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework");
base.OnConfiguring(optionsBuilder);
}
#else
public NorthwindContext()
: base("name=NorthwindConnection")
{
}
#endif
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Contact> Contacts { get; set; }
#if !EF7
// TODO GitHubIssue#57: Complete EF7 to EDM model mapping
// Restore this property after ToTable() is supported by EF7.
public virtual DbSet<CustomerDemographic> CustomerDemographics { get; set; }
#endif
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Order_Detail> Order_Details { get; set; }
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<Region> Regions { get; set; }
public virtual DbSet<Shipper> Shippers { get; set; }
public virtual DbSet<Supplier> Suppliers { get; set; }
public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
public virtual DbSet<Territory> Territories { get; set; }
public virtual DbSet<Alphabetical_list_of_product> Alphabetical_list_of_products { get; set; }
public virtual DbSet<Category_Sales_for_1997> Category_Sales_for_1997 { get; set; }
public virtual DbSet<Current_Product_List> Current_Product_Lists { get; set; }
public virtual DbSet<Customer_and_Suppliers_by_City> Customer_and_Suppliers_by_Cities { get; set; }
public virtual DbSet<Invoice> Invoices { get; set; }
public virtual DbSet<Order_Details_Extended> Order_Details_Extendeds { get; set; }
public virtual DbSet<Order_Subtotal> Order_Subtotals { get; set; }
public virtual DbSet<Orders_Qry> Orders_Qries { get; set; }
public virtual DbSet<Product_Sales_for_1997> Product_Sales_for_1997 { get; set; }
public virtual DbSet<Products_Above_Average_Price> Products_Above_Average_Prices { get; set; }
public virtual DbSet<Products_by_Category> Products_by_Categories { get; set; }
public virtual DbSet<Sales_by_Category> Sales_by_Categories { get; set; }
public virtual DbSet<Sales_Totals_by_Amount> Sales_Totals_by_Amounts { get; set; }
public virtual DbSet<Summary_of_Sales_by_Quarter> Summary_of_Sales_by_Quarters { get; set; }
public virtual DbSet<Summary_of_Sales_by_Year> Summary_of_Sales_by_Years { get; set; }
public void ResetDataSource()
{
#if EF7
Database.EnsureDeleted();
#else
if (Database.Exists())
{
Database.Delete();
}
#endif
LoadDataSource();
}
private static void LoadDataSource()
{
var dbPath = SqlLoader.GetDatabaseDirectory(null);
var loader = new SqlLoader();
loader.SetDatabaseEngine("(localdb)\\MSSQLLocalDB");
loader.AddScript("instnwdb.sql");
loader.AddScriptArgument("SqlSamplesDatabasePath", dbPath);
loader.Execute(dbPath);
}
#if EF7
protected override void OnModelCreating(Data.Entity.ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ForSqlServer().UseIdentity();
// TODO GitHubIssue#57: Complete EF7 to EDM model mapping
// After EF7 adds support for DataAnnotation, some of following configuration could be deprecated.
modelBuilder.Entity<Alphabetical_list_of_product>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Alphabetical list of products");
entityBuilder.Property(e => e.UnitPrice).ForSqlServer().ColumnType("money");
entityBuilder.Property(e => e.ProductName).MaxLength(40);
entityBuilder.Property(e => e.QuantityPerUnit).MaxLength(40);
entityBuilder.Property(e => e.CategoryName).MaxLength(15);
entityBuilder.Key(e => new
{
K1 = e.ProductID,
K2 = e.ProductName,
K3 = e.Discontinued,
K4 = e.CategoryName,
});
});
modelBuilder.Entity<Category>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Categories");
entityBuilder.Property(e => e.CategoryName).Required().MaxLength(15);
entityBuilder.Property(e => e.Description).ForSqlServer().ColumnType("ntext");
entityBuilder.Property(e => e.Picture).ForSqlServer().ColumnType("image");
entityBuilder.Property(e => e.CategoryName).MaxLength(15);
entityBuilder.Key(e => e.CategoryID);
});
modelBuilder.Entity<Category_Sales_for_1997>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Category Sales for 1997");
entityBuilder.Property(e => e.CategoryName).MaxLength(15);
entityBuilder.Property(e => e.CategorySales).ForSqlServer().ColumnType("money");
entityBuilder.Key(e => e.CategoryName);
});
modelBuilder.Entity<Contact>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Contacts");
entityBuilder.Property(e => e.HomePage).ForSqlServer().ColumnType("ntext");
entityBuilder.Property(e => e.Photo).ForSqlServer().ColumnType("image");
//entityBuilder.Key(e => e.ContactID);
});
modelBuilder.Entity<Current_Product_List>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Current Product List");
entityBuilder.Key(e => new
{
K1 = e.ProductID,
K2 = e.ProductName,
});
});
modelBuilder.Entity<Customer>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Customers");
entityBuilder.Property(e => e.CompanyName).Required().MaxLength(40);
entityBuilder.Key(e => e.CustomerID);
});
modelBuilder.Entity<Customer_and_Suppliers_by_City>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Customer and Suppliers by City");
//entityBuilder.Property(e => e.CompanyName).Required().MaxLength(40);
entityBuilder.Key(e => new
{
K1 = e.CompanyName,
K2 = e.Relationship,
});
});
modelBuilder.Entity<Employee>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Employees");
entityBuilder.Property(e => e.LastName).Required().MaxLength(20);
entityBuilder.Property(e => e.FirstName).Required().MaxLength(10);
entityBuilder.Collection(e => e.Employees1).InverseReference(e => e.Employee1).Required(false).ForeignKey(e => e.ReportsTo);
});
modelBuilder.Entity<Invoice>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Invoices");
entityBuilder.Property(e => e.UnitPrice).ForSqlServer().ColumnType("money");
entityBuilder.Property(e => e.ExtendedPrice).ForSqlServer().ColumnType("money");
entityBuilder.Property(e => e.Freight).ForSqlServer().ColumnType("money");
entityBuilder.Key(e => new
{
K1 = e.CustomerName,
K2 = e.Salesperson,
K3 = e.OrderID,
K4 = e.ShipperName,
K5 = e.ProductID,
K6 = e.ProductName,
K7 = e.UnitPrice,
K8 = e.Quantity,
K9 = e.Discount,
});
});
modelBuilder.Entity<Order>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Orders");
entityBuilder.Collection(e => e.Order_Details).InverseReference(e => e.Order).Required().ForeignKey(e => e.OrderID);
});
modelBuilder.Entity<Order_Detail>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Order Details");
entityBuilder.Property(e => e.UnitPrice).ForSqlServer().ColumnType("money");
entityBuilder.Key(e => new
{
K1 = e.OrderID,
K2 = e.ProductID,
});
});
modelBuilder.Entity<Order_Details_Extended>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Order Details Extended");
entityBuilder.Property(e => e.UnitPrice).ForSqlServer().ColumnType("money");
entityBuilder.Property(e => e.ExtendedPrice).ForSqlServer().ColumnType("money");
entityBuilder.Key(e => new
{
K0 = e.OrderID,
K1 = e.ProductID,
K2 = e.ProductName,
K3 = e.UnitPrice,
K4 = e.Quantity,
K5 = e.Discount,
});
});
modelBuilder.Entity<Order_Subtotal>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Order Subtotals");
entityBuilder.Property(e => e.Subtotal).ForSqlServer().ColumnType("money");
entityBuilder.Key(e => e.OrderID);
});
modelBuilder.Entity<Orders_Qry>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Order Qry");
entityBuilder.Property(e => e.Freight).ForSqlServer().ColumnType("money");
entityBuilder.Key(e => new
{
K0 = e.OrderID,
K1 = e.CompanyName,
});
});
modelBuilder.Entity<Product>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Products");
entityBuilder.Property(e => e.UnitPrice).ForSqlServer().ColumnType("money");
entityBuilder.Collection(e => e.Order_Details).InverseReference(e => e.Product).Required();
});
modelBuilder.Entity<Product_Sales_for_1997>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Product Sales for 1997");
entityBuilder.Property(e => e.ProductSales).ForSqlServer().ColumnType("money");
entityBuilder.Key(e => new
{
K0 = e.CategoryName,
K1 = e.ProductName,
});
});
modelBuilder.Entity<Products_Above_Average_Price>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Products Above Average Price");
entityBuilder.Property(e => e.UnitPrice).ForSqlServer().ColumnType("money");
entityBuilder.Key(e => e.ProductName);
});
modelBuilder.Entity<Products_by_Category>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Products by Category");
entityBuilder.Key(e => new
{
K0 = e.CategoryName,
K1 = e.ProductName,
K2 = e.Discontinued,
});
});
modelBuilder.Entity<Region>(entityBuilder =>
{
entityBuilder.Property(e => e.RegionDescription).Required();
entityBuilder.Key(e => e.RegionID);
});
modelBuilder.Entity<Sales_by_Category>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Sales by Category");
entityBuilder.Property(e => e.ProductSales).ForSqlServer().ColumnType("money");
entityBuilder.Key(e => new
{
K0 = e.CategoryID,
K1 = e.CategoryName,
K2 = e.ProductName,
});
});
modelBuilder.Entity<Sales_Totals_by_Amount>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Sales Totals by Amount");
entityBuilder.Property(e => e.SaleAmount).ForSqlServer().ColumnType("money");
entityBuilder.Key(e => new
{
K0 = e.OrderID,
K1 = e.CompanyName,
});
});
modelBuilder.Entity<Shipper>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Shippers");
entityBuilder.Collection(e => e.Orders).InverseReference(e => e.Shipper).ForeignKey(e => e.ShipVia).Required(false);
});
modelBuilder.Entity<Summary_of_Sales_by_Quarter>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Summary of Sales by Quarter");
entityBuilder.Property(e => e.Subtotal).ForSqlServer().ColumnType("money");
entityBuilder.Property(e => e.OrderID).StoreGeneratedPattern(StoreGeneratedPattern.None);
entityBuilder.Key(e => e.OrderID);
});
modelBuilder.Entity<Summary_of_Sales_by_Year>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Summary of Sales by Year");
entityBuilder.Property(e => e.Subtotal).ForSqlServer().ColumnType("money");
entityBuilder.Property(e => e.OrderID).StoreGeneratedPattern(StoreGeneratedPattern.None);
entityBuilder.Key(e => e.OrderID);
});
modelBuilder.Entity<Supplier>(entityBuilder =>
{
});
modelBuilder.Entity<sysdiagram>(entityBuilder =>
{
entityBuilder.Property(e => e.name).Required();
entityBuilder.Key(e => e.diagram_id);
});
modelBuilder.Entity<Territory>(entityBuilder =>
{
entityBuilder.ForSqlServer().Table("Territories");
});
// TODO GitHubIssue#57: Complete EF7 to EDM model mapping
// ToTable() is not yet supported in EF7, remove following ignores after it's ready.
modelBuilder.Ignore<CustomerDemographic>();
modelBuilder.Entity<Customer>().Ignore(e => e.CustomerDemographics);
modelBuilder.Entity<Employee>().Ignore(e => e.Territories);
modelBuilder.Entity<Territory>().Ignore(e => e.Employees);
}
#else
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerDemographic>()
.Property(e => e.CustomerTypeID)
.IsFixedLength();
modelBuilder.Entity<CustomerDemographic>()
.HasMany(e => e.Customers)
.WithMany(e => e.CustomerDemographics)
.Map(m => m.ToTable("CustomerCustomerDemo").MapLeftKey("CustomerTypeID").MapRightKey("CustomerID"));
modelBuilder.Entity<Customer>()
.Property(e => e.CustomerID)
.IsFixedLength();
modelBuilder.Entity<Employee>()
.HasMany(e => e.Employees1)
.WithOptional(e => e.Employee1)
.HasForeignKey(e => e.ReportsTo);
modelBuilder.Entity<Employee>()
.HasMany(e => e.Territories)
.WithMany(e => e.Employees)
.Map(m => m.ToTable("EmployeeTerritories").MapLeftKey("EmployeeID").MapRightKey("TerritoryID"));
modelBuilder.Entity<Order_Detail>()
.Property(e => e.UnitPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<Order>()
.Property(e => e.CustomerID)
.IsFixedLength();
modelBuilder.Entity<Order>()
.Property(e => e.Freight)
.HasPrecision(19, 4);
modelBuilder.Entity<Order>()
.HasMany(e => e.Order_Details)
.WithRequired(e => e.Order)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Product>()
.Property(e => e.UnitPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<Product>()
.HasMany(e => e.Order_Details)
.WithRequired(e => e.Product)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Region>()
.Property(e => e.RegionDescription)
.IsFixedLength();
modelBuilder.Entity<Region>()
.HasMany(e => e.Territories)
.WithRequired(e => e.Region)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Shipper>()
.HasMany(e => e.Orders)
.WithOptional(e => e.Shipper)
.HasForeignKey(e => e.ShipVia);
modelBuilder.Entity<Territory>()
.Property(e => e.TerritoryDescription)
.IsFixedLength();
modelBuilder.Entity<Alphabetical_list_of_product>()
.Property(e => e.UnitPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<Category_Sales_for_1997>()
.Property(e => e.CategorySales)
.HasPrecision(19, 4);
modelBuilder.Entity<Customer_and_Suppliers_by_City>()
.Property(e => e.Relationship)
.IsUnicode(false);
modelBuilder.Entity<Invoice>()
.Property(e => e.CustomerID)
.IsFixedLength();
modelBuilder.Entity<Invoice>()
.Property(e => e.UnitPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<Invoice>()
.Property(e => e.ExtendedPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<Invoice>()
.Property(e => e.Freight)
.HasPrecision(19, 4);
modelBuilder.Entity<Order_Details_Extended>()
.Property(e => e.UnitPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<Order_Details_Extended>()
.Property(e => e.ExtendedPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<Order_Subtotal>()
.Property(e => e.Subtotal)
.HasPrecision(19, 4);
modelBuilder.Entity<Orders_Qry>()
.Property(e => e.CustomerID)
.IsFixedLength();
modelBuilder.Entity<Orders_Qry>()
.Property(e => e.Freight)
.HasPrecision(19, 4);
modelBuilder.Entity<Product_Sales_for_1997>()
.Property(e => e.ProductSales)
.HasPrecision(19, 4);
modelBuilder.Entity<Products_Above_Average_Price>()
.Property(e => e.UnitPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<Sales_by_Category>()
.Property(e => e.ProductSales)
.HasPrecision(19, 4);
modelBuilder.Entity<Sales_Totals_by_Amount>()
.Property(e => e.SaleAmount)
.HasPrecision(19, 4);
modelBuilder.Entity<Summary_of_Sales_by_Quarter>()
.Property(e => e.Subtotal)
.HasPrecision(19, 4);
modelBuilder.Entity<Summary_of_Sales_by_Year>()
.Property(e => e.Subtotal)
.HasPrecision(19, 4);
}
#endif
}
}
| |
//
// Copyright (C) 2009-2010 Jordi Mas i Hernandez, jmas@softcatala.org
//
// 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 Gtk;
using Gdk;
using System.Collections.Generic;
using System.ComponentModel;
using Mistelix.Widgets;
using Mistelix.DataModel;
using Mistelix.Core;
namespace Mistelix.Dialogs
{
// Button properties dialog
public class ButtonPropertiesDialog : BuilderDialog
{
Project project;
int button_id;
ThumbnailCollection thumbnails;
ListStore store;
Pixbuf def_image;
Dictionary <ThumbnailCollection.ItemTask, Gtk.TreeIter> mapping;
BackgroundWorker thumbnailing;
[GtkBeans.Builder.Object] Gtk.Entry element_entry;
[GtkBeans.Builder.Object] Gtk.RadioButton image_radio;
[GtkBeans.Builder.Object] Gtk.RadioButton text_radio;
[GtkBeans.Builder.Object] Gtk.Button ok_button;
[GtkBeans.Builder.Object] Gtk.IconView thumbnails_iconview;
const int COL_PIXBUF = 0;
const int COL_INDEX = 1;
public ButtonPropertiesDialog (Project project, int button_id) : base ("ButtonPropertiesDialog.ui", "buttonproperties")
{
this.project = project;
this.button_id = button_id;
if (project.Buttons[button_id].ShowAs == ButtonShowAs.Thumbnail) {
image_radio.Active = true;
element_entry.Sensitive = false;
}
else {
text_radio.Active = true;
element_entry.Sensitive = true;
}
if (project.Buttons[button_id].Text != null)
element_entry.Text = project.Buttons[button_id].Text;
image_radio.Toggled += new EventHandler (OnCheckToggled);
element_entry.Changed += OnChangedText;
CreateDefaultImage ();
thumbnails_iconview.PixbufColumn = 0;
mapping = new Dictionary <ThumbnailCollection.ItemTask, Gtk.TreeIter> ();
thumbnails_iconview.Model = store = CreateStore ();
thumbnailing = new BackgroundWorker ();
thumbnailing.WorkerSupportsCancellation = true;
thumbnailing.DoWork += new DoWorkEventHandler (DoWork);
LoadThumbnails ();
}
void CreateDefaultImage ()
{
const int channels = 4;
Cairo.ImageSurface image;
int thumbnail_width, thumbnail_height;
thumbnail_width = ThumbnailSizeManager.List [project.Details.ButtonThumbnailSize].Width;
thumbnail_height = ThumbnailSizeManager.List [project.Details.ButtonThumbnailSize].Height;
image = Utils.CreateNoPreviewImage (thumbnail_width, thumbnail_height);
byte[] data = DataImageSurface.FromCairo32ToPixBuf (image.Data, thumbnail_width, thumbnail_height, channels);
def_image = new Pixbuf (data, true, 8, thumbnail_width, thumbnail_height, thumbnail_width * channels, null);
image.Destroy ();
}
ListStore CreateStore ()
{
// Pixbuf
return new ListStore (typeof (Pixbuf), typeof (int));
}
void DoWork (object sender, DoWorkEventArgs e)
{
Task task;
while (true) {
if (thumbnailing.CancellationPending)
break;
task = thumbnails.Dispatcher.GetNextTask ();
if (task == null)
break;
task.Do ();
}
}
void LoadThumbnails ()
{
VisibleProjectElement element;
Resolution size;
Gtk.TreeIter selected_iter = Gtk.TreeIter.Zero;
size = ThumbnailSizeManager.List [project.Details.ButtonThumbnailSize];
element = project.ElementFromID (project.Buttons[button_id].LinkedId);
thumbnails = element.GetThumbnailRepresentations (size.Width, size.Height);
foreach (ThumbnailCollection.ItemTask task in thumbnails)
{
Gtk.TreeIter iter;
iter = store.AppendValues (def_image, task.ThumbnailIndex);
mapping.Add (task, iter);
if (task.ThumbnailIndex == project.Buttons[button_id].ThumbnailIndex)
selected_iter = iter;
task.CompletedEventHandler += delegate (object obj, EventArgs args)
{
ThumbnailCollection.ItemTask itemtask = (ThumbnailCollection.ItemTask) obj;
Gtk.TreeIter tree_iter;
try
{
mapping.TryGetValue (itemtask, out tree_iter);
}
catch (KeyNotFoundException)
{
Logger.Error ("ButtonPropertiesDialog.LoadThumbnails. Cannot find key");
return;
}
Application.Invoke (delegate { store.SetValue (tree_iter, COL_PIXBUF, itemtask.Pixbuf); });
};
}
TreePath path = store.GetPath (selected_iter);
thumbnails_iconview.SelectPath (path);
thumbnailing.RunWorkerAsync (store);
}
void OnChangedText (object sender, EventArgs args)
{
EnableOKButton ();
}
void EnableOKButton ()
{
bool enabled;
if (text_radio.Active == true) {
if (element_entry.Text.Length > 0)
enabled = true;
else
enabled = false;
} else
enabled = true;
ok_button.Sensitive = enabled;
}
void OnOK (object sender, EventArgs args)
{
if (image_radio.Active == false) { // Text
project.Buttons[button_id].ShowAs = ButtonShowAs.Text;
project.Buttons[button_id].Text = element_entry.Text;
return;
}
project.Buttons[button_id].ShowAs = ButtonShowAs.Thumbnail;
TreeIter iter;
int idx;
TreePath[] items = thumbnails_iconview.SelectedItems;
store.GetIter (out iter, items [0]);
idx = (int) store.GetValue (iter, COL_INDEX);
project.Buttons[button_id].ThumbnailIndex = idx;
}
void OnCheckToggled (object obj, EventArgs args)
{
element_entry.Sensitive = text_radio.Active;
EnableOKButton ();
}
public override void Destroy ()
{
thumbnailing.CancelAsync ();
thumbnailing.Dispose ();
store.Foreach (delegate (TreeModel model, TreePath path, TreeIter iter)
{
Gdk.Pixbuf im = (Gdk.Pixbuf) store.GetValue (iter, COL_PIXBUF);
if (def_image != im)
im.Dispose ();
return false;
});
def_image.Dispose ();
base.Destroy ();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Python.Runtime.Reflection;
using System.Reflection;
namespace Python.Runtime
{
/// <summary>
/// This file defines objects to support binary interop with the Python
/// runtime. Generally, the definitions here need to be kept up to date
/// when moving to new Python versions.
/// </summary>
[Serializable]
[AttributeUsage(AttributeTargets.All)]
public class DocStringAttribute : Attribute
{
public DocStringAttribute(string docStr)
{
DocString = docStr;
}
public string DocString { get; }
}
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Delegate)]
internal class ModuleFunctionAttribute : Attribute
{
public ModuleFunctionAttribute()
{
}
}
[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Delegate)]
internal class ForbidPythonThreadsAttribute : Attribute
{
public ForbidPythonThreadsAttribute()
{
}
}
[Serializable]
[AttributeUsage(AttributeTargets.Property)]
internal class ModulePropertyAttribute : Attribute
{
public ModulePropertyAttribute()
{
}
}
/// <summary>
/// TypeFlags(): The actual bit values for the Type Flags stored
/// in a class.
/// Note that the two values reserved for stackless have been put
/// to good use as PythonNet specific flags (Managed and Subclass)
/// </summary>
// Py_TPFLAGS_*
[Flags]
public enum TypeFlags: long
{
HeapType = (1 << 9),
BaseType = (1 << 10),
Ready = (1 << 12),
Readying = (1 << 13),
HaveGC = (1 << 14),
// 15 and 16 are reserved for stackless
HaveStacklessExtension = 0,
/* XXX Reusing reserved constants */
/// <remarks>PythonNet specific</remarks>
HasClrInstance = (1 << 15),
/// <remarks>PythonNet specific</remarks>
Subclass = (1 << 16),
/* Objects support nb_index in PyNumberMethods */
HaveVersionTag = (1 << 18),
ValidVersionTag = (1 << 19),
IsAbstract = (1 << 20),
HaveNewBuffer = (1 << 21),
// TODO: Implement FastSubclass functions
IntSubclass = (1 << 23),
LongSubclass = (1 << 24),
ListSubclass = (1 << 25),
TupleSubclass = (1 << 26),
StringSubclass = (1 << 27),
UnicodeSubclass = (1 << 28),
DictSubclass = (1 << 29),
BaseExceptionSubclass = (1 << 30),
TypeSubclass = (1 << 31),
Default = (
HaveStacklessExtension |
HaveVersionTag),
}
// This class defines the function prototypes (delegates) used for low
// level integration with the CPython runtime. It also provides name
// based lookup of the correct prototype for a particular Python type
// slot and utilities for generating method thunks for managed methods.
internal class Interop
{
static readonly Dictionary<MethodInfo, Type> delegateTypes = new();
internal static Type GetPrototype(MethodInfo method)
{
if (delegateTypes.TryGetValue(method, out var delegateType))
return delegateType;
var parameters = method.GetParameters().Select(p => new ParameterHelper(p)).ToArray();
foreach (var candidate in typeof(Interop).GetNestedTypes())
{
if (!typeof(Delegate).IsAssignableFrom(candidate))
continue;
MethodInfo invoke = candidate.GetMethod("Invoke");
var candiateParameters = invoke.GetParameters();
if (candiateParameters.Length != parameters.Length)
continue;
var parametersMatch = parameters.Zip(candiateParameters,
(expected, actual) => expected.Matches(actual))
.All(matches => matches);
if (!parametersMatch) continue;
if (invoke.ReturnType != method.ReturnType) continue;
delegateTypes.Add(method, candidate);
return candidate;
}
throw new NotImplementedException(method.ToString());
}
internal static Dictionary<IntPtr, Delegate> allocatedThunks = new Dictionary<IntPtr, Delegate>();
internal static ThunkInfo GetThunk(MethodInfo method)
{
Type dt = GetPrototype(method);
Delegate d = Delegate.CreateDelegate(dt, method);
return GetThunk(d);
}
internal static ThunkInfo GetThunk(Delegate @delegate)
{
var info = new ThunkInfo(@delegate);
allocatedThunks[info.Address] = @delegate;
return info;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate NewReference B_N(BorrowedReference ob);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate NewReference BB_N(BorrowedReference ob, BorrowedReference a);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate NewReference BBB_N(BorrowedReference ob, BorrowedReference a1, BorrowedReference a2);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int B_I32(BorrowedReference ob);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int BB_I32(BorrowedReference ob, BorrowedReference a);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int BBB_I32(BorrowedReference ob, BorrowedReference a1, BorrowedReference a2);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int BP_I32(BorrowedReference ob, IntPtr arg);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate IntPtr B_P(BorrowedReference ob);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate NewReference BBI32_N(BorrowedReference ob, BorrowedReference a1, int a2);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate NewReference BP_N(BorrowedReference ob, IntPtr arg);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void N_V(NewReference ob);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int BPP_I32(BorrowedReference ob, IntPtr a1, IntPtr a2);
}
internal class ThunkInfo
{
public readonly Delegate Target;
public readonly IntPtr Address;
public ThunkInfo(Delegate target)
{
Debug.Assert(target is not null);
Target = target!;
Address = Marshal.GetFunctionPointerForDelegate(target);
}
}
[StructLayout(LayoutKind.Sequential)]
struct PyMethodDef
{
public IntPtr ml_name;
public IntPtr ml_meth;
public int ml_flags;
public IntPtr ml_doc;
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: BufferedStream2
**
**
===========================================================*/
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Versioning;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Runtime.CompilerServices;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Security.Permissions;
namespace System.IO {
// This abstract implementation adds thread safe buffering on top
// of the underlying stream. For most streams, having this intermediate
// buffer translates to better performance due to the costly nature of
// underlying IO, P/Invoke (such as disk IO). This also improves the locking
// efficiency when operating under heavy concurrency. The synchronization
// technique used in this implementation is specifically optimized for IO
// The main differences between this implementation and the existing System.IO.BufferedStream
// - the design allows for inheritance as opposed to wrapping streams
// - it is thread safe, though currently only synchronous Write is optimized
[HostProtection(Synchronization=true)]
internal abstract class BufferedStream2 : Stream
{
protected internal const int DefaultBufferSize = 32*1024; //32KB or 64KB seems to give the best throughput
protected int bufferSize; // Length of internal buffer, if it's allocated.
private byte[] _buffer; // Internal buffer. Alloc on first use.
// At present only concurrent buffer writing is optimized implicitly
// while reading relies on explicit locking.
// Ideally we want these fields to be volatile
private /*volatile*/ int _pendingBufferCopy; // How many buffer writes are pending.
private /*volatile*/ int _writePos; // Write pointer within shared buffer.
// Should we use a separate buffer for reading Vs writing?
private /*volatile*/ int _readPos; // Read pointer within shared buffer.
private /*volatile*/ int _readLen; // Number of bytes read in buffer from file.
// Ideally we want this field to be volatile but Interlocked operations
// on 64bit int is not guaranteed to be atomic especially on 32bit platforms
protected long pos; // Cache current location in the underlying stream.
// Derived streams should override CanRead/CanWrite/CanSeek to enable/disable functionality as desired
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.AppDomain, ResourceScope.AppDomain)]
public override void Write(byte[] array, int offset, int count)
{
if (array==null)
throw new ArgumentNullException("array", SR.GetString(SR.ArgumentNull_Buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
if (array.Length - offset < count)
throw new ArgumentException(SR.GetString(SR.Argument_InvalidOffLen));
Debug.Assert((_readPos==0 && _readLen==0 && _writePos >= 0) || (_writePos==0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
if (_writePos==0) {
// Ensure we can write to the stream, and ready buffer for writing.
if (!CanWrite) __Error.WriteNotSupported();
if (_readPos < _readLen) FlushRead();
_readPos = 0;
_readLen = 0;
}
// Optimization:
// Don't allocate a buffer then call memcpy for 0 bytes.
if (count == 0)
return;
do {
// Avoid contention around spilling over the buffer, the locking mechanism here is bit unconventional.
// Let's call this a YieldLock. It is closer to a spin lock than a semaphore but not quite a spin lock.
// Forced thread context switching is better than a tight spin lock here for several reasons.
// We utilize less CPU, yield to other threads (potentially the one doing the write, this is
// especially important under heavy thread/processor contention environment) and also yield to
// runtime thread aborts (important when run from a high pri thread like finalizer).
if (_writePos > bufferSize) {
Thread.Sleep(1);
continue;
}
// Optimization:
// For input chunk larger than internal buffer size, write directly
// It is okay to have a ---- here with the _writePos check, which means
// we have a loose order between flushing the intenal cache Vs writing
// this larger chunk but that is fine. This step will nicely optimize
// repeated writing of larger chunks by skipping the interlocked operation
if ((_writePos == 0) && (count >= bufferSize)) {
WriteCore(array, offset, count, true);
return;
}
// We should review whether we need critical region markers for hosts.
Thread.BeginCriticalRegion();
Interlocked.Increment(ref _pendingBufferCopy);
int newPos = Interlocked.Add(ref _writePos, count);
int oldPos = (newPos - count);
// Clear the buffer
if (newPos > bufferSize) {
Interlocked.Decrement(ref _pendingBufferCopy);
Thread.EndCriticalRegion();
// Though the lock below is not necessary for correctness, when operating in a heavy
// thread contention environment, augmenting the YieldLock techinique with a critical
// section around write seems to be giving slightly better performance while
// not having noticable impact in the less contended situations.
// Perhaps we can build a technique that keeps track of the contention?
//lock (this)
{
// Make sure we didn't get pre-empted by another thread
if (_writePos > bufferSize) {
if ((oldPos <= bufferSize) && (oldPos > 0)) {
while (_pendingBufferCopy != 0) {
Thread.SpinWait(1);
}
WriteCore(_buffer, 0, oldPos, true);
_writePos = 0;
}
}
}
}
else {
if (_buffer == null)
Interlocked.CompareExchange(ref _buffer, new byte[bufferSize], null);
// Copy user data into buffer, to write at a later date.
Buffer.BlockCopy(array, offset, _buffer, oldPos, count);
Interlocked.Decrement(ref _pendingBufferCopy);
Thread.EndCriticalRegion();
return;
}
} while (true);
}
#if _ENABLE_STREAM_FACTORING
public override long Position
{
// Making the getter thread safe is not very useful anyways
get {
if (!CanSeek) __Error.SeekNotSupported();
Debug.Assert((_readPos==0 && _readLen==0 && _writePos >= 0) || (_writePos==0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
// Compensate for buffer that we read from the handle (_readLen) Vs what the user
// read so far from the internel buffer (_readPos). Of course add any unwrittern
// buffered data
return pos + (_readPos - _readLen + _writePos);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
set {
if (value < 0) throw new ArgumentOutOfRangeException("value", Helper.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (_writePos > 0) FlushWrite(false);
_readPos = 0;
_readLen = 0;
Seek(value, SeekOrigin.Begin);
}
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Read(/*[In, Out]*/ byte[] array, int offset, int count)
{
if (array == null)
throw new ArgumentNullException("array", Helper.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Helper.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Helper.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - offset < count)
throw new ArgumentException(Helper.GetResourceString("Argument_InvalidOffLen"));
Debug.Assert((_readPos==0 && _readLen==0 && _writePos >= 0) || (_writePos==0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
bool isBlocked = false;
int n = _readLen - _readPos;
// If the read buffer is empty, read into either user's array or our
// buffer, depending on number of bytes user asked for and buffer size.
if (n == 0) {
if (!CanRead) __Error.ReadNotSupported();
if (_writePos > 0) FlushWrite(false);
if (!CanSeek || (count >= bufferSize)) {
n = ReadCore(array, offset, count);
// Throw away read buffer.
_readPos = 0;
_readLen = 0;
return n;
}
if (_buffer == null) _buffer = new byte[bufferSize];
n = ReadCore(_buffer, 0, bufferSize);
if (n == 0) return 0;
isBlocked = n < bufferSize;
_readPos = 0;
_readLen = n;
}
// Now copy min of count or numBytesAvailable (ie, near EOF) to array.
if (n > count) n = count;
Buffer.BlockCopy(_buffer, _readPos, array, offset, n);
_readPos += n;
// We may have read less than the number of bytes the user asked
// for, but that is part of the Stream contract. Reading again for
// more data may cause us to block if we're using a device with
// no clear end of file, such as a serial port or pipe. If we
// blocked here & this code was used with redirected pipes for a
// process's standard output, this can lead to deadlocks involving
// two processes. But leave this here for files to avoid what would
// probably be a breaking change. --
return n;
}
[HostProtection(ExternalThreading=true)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, Object stateObject)
{
if (array==null)
throw new ArgumentNullException("array");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Helper.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (numBytes < 0)
throw new ArgumentOutOfRangeException("numBytes", Helper.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - offset < numBytes)
throw new ArgumentException(Helper.GetResourceString("Argument_InvalidOffLen"));
if (!CanRead) __Error.ReadNotSupported();
Debug.Assert((_readPos==0 && _readLen==0 && _writePos >= 0) || (_writePos==0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
if (_writePos > 0) FlushWrite(false);
if (_readPos == _readLen) {
// I can't see how to handle buffering of async requests when
// filling the buffer asynchronously, without a lot of complexity.
// The problems I see are issuing an async read, we do an async
// read to fill the buffer, then someone issues another read
// (either synchronously or asynchronously) before the first one
// returns. This would involve some sort of complex buffer locking
// that we probably don't want to get into, at least not in V1.
// If we did a [....] read to fill the buffer, we could avoid the
// problem, and any async read less than 64K gets turned into a
// synchronous read by NT anyways... --
if (numBytes < bufferSize) {
if (_buffer == null) _buffer = new byte[bufferSize];
IAsyncResult bufferRead = BeginReadCore(_buffer, 0, bufferSize, null, null, 0);
_readLen = EndRead(bufferRead);
int n = _readLen;
if (n > numBytes) n = numBytes;
Buffer.BlockCopy(_buffer, 0, array, offset, n);
_readPos = n;
// Fake async
return BufferedStreamAsyncResult.Complete(n, userCallback, stateObject, false);
}
// Here we're making our position pointer inconsistent
// with our read buffer. Throw away the read buffer's contents.
_readPos = 0;
_readLen = 0;
return BeginReadCore(array, offset, numBytes, userCallback, stateObject, 0);
}
else {
int n = _readLen - _readPos;
if (n > numBytes) n = numBytes;
Buffer.BlockCopy(_buffer, _readPos, array, offset, n);
_readPos += n;
if (n >= numBytes)
return BufferedStreamAsyncResult.Complete(n, userCallback, stateObject, false);
// For streams with no clear EOF like serial ports or pipes
// we cannot read more data without causing an app to block
// incorrectly. Pipes don't go down this path
// though. This code needs to be fixed.
// Throw away read buffer.
_readPos = 0;
_readLen = 0;
// WARNING: all state on asyncResult objects must be set before
// we call ReadFile in BeginReadCore, since the OS can run our
// callback & the user's callback before ReadFile returns.
return BeginReadCore(array, offset + n, numBytes - n, userCallback, stateObject, n);
}
}
public unsafe override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
BufferedStreamAsyncResult bsar = asyncResult as BufferedStreamAsyncResult;
if (bsar != null) {
if (bsar._isWrite)
__Error.WrongAsyncResult();
return bsar._numBytes;
}
else {
return EndReadCore(asyncResult);
}
}
[HostProtection(ExternalThreading=true)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, Object stateObject)
{
if (array==null)
throw new ArgumentNullException("array");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Helper.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (numBytes < 0)
throw new ArgumentOutOfRangeException("numBytes", Helper.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - offset < numBytes)
throw new ArgumentException(Helper.GetResourceString("Argument_InvalidOffLen"));
if (!CanWrite) __Error.WriteNotSupported();
Debug.Assert((_readPos==0 && _readLen==0 && _writePos >= 0) || (_writePos==0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
if (_writePos==0) {
if (_readPos < _readLen) FlushRead();
_readPos = 0;
_readLen = 0;
}
int n = bufferSize - _writePos;
if (numBytes <= n) {
if (_buffer == null) _buffer = new byte[bufferSize];
Buffer.BlockCopy(array, offset, _buffer, _writePos, numBytes);
_writePos += numBytes;
return BufferedStreamAsyncResult.Complete(numBytes, userCallback, stateObject, true);
}
if (_writePos > 0) FlushWrite(false);
return BeginWriteCore(array, offset, numBytes, userCallback, stateObject);
}
public unsafe override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
BufferedStreamAsyncResult bsar = asyncResult as BufferedStreamAsyncResult;
if (bsar == null)
EndWriteCore(asyncResult);
}
// Reads a byte from the file stream. Returns the byte cast to an int
// or -1 if reading from the end of the stream.
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int ReadByte()
{
if (_readLen == 0 && !CanRead)
__Error.ReadNotSupported();
Debug.Assert((_readPos==0 && _readLen==0 && _writePos >= 0) || (_writePos==0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
if (_readPos == _readLen) {
if (_writePos > 0) FlushWrite(false);
Debug.Assert(bufferSize > 0, "bufferSize > 0");
if (_buffer == null) _buffer = new byte[bufferSize];
_readLen = ReadCore(_buffer, 0, bufferSize);
_readPos = 0;
}
if (_readPos == _readLen)
return -1;
int result = _buffer[_readPos];
_readPos++;
return result;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteByte(byte value)
{
if (_writePos == 0) {
if (!CanWrite)
__Error.WriteNotSupported();
if (_readPos < _readLen)
FlushRead();
_readPos = 0;
_readLen = 0;
Debug.Assert(bufferSize > 0, "bufferSize > 0");
if (_buffer==null)
_buffer = new byte[bufferSize];
}
if (_writePos == bufferSize)
FlushWrite(false);
_buffer[_writePos] = value;
_writePos++;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override long Seek(long offset, SeekOrigin origin)
{
if (origin<SeekOrigin.Begin || origin>SeekOrigin.End)
throw new ArgumentException(Helper.GetResourceString("Argument_InvalidSeekOrigin"));
if (!CanSeek) __Error.SeekNotSupported();
Debug.Assert((_readPos==0 && _readLen==0 && _writePos >= 0) || (_writePos==0 && _readPos <= _readLen), "We're either reading or writing, but not both.");
// If we've got bytes in our buffer to write, write them out.
// If we've read in and consumed some bytes, we'll have to adjust
// our seek positions ONLY IF we're seeking relative to the current
// position in the stream. This simulates doing a seek to the new
// position, then a read for the number of bytes we have in our buffer.
if (_writePos > 0) {
FlushWrite(false);
}
else if (origin == SeekOrigin.Current) {
// Don't call FlushRead here, which would have caused an infinite
// loop. Simply adjust the seek origin. This isn't necessary
// if we're seeking relative to the beginning or end of the stream.
offset -= (_readLen - _readPos);
}
long oldPos = pos + (_readPos - _readLen);
long curPos = SeekCore(offset, origin);
// We now must update the read buffer. We can in some cases simply
// update _readPos within the buffer, copy around the buffer so our
// Position property is still correct, and avoid having to do more
// reads from the disk. Otherwise, discard the buffer's contents.
if (_readLen > 0) {
// We can optimize the following condition:
// oldPos - _readPos <= curPos < oldPos + _readLen - _readPos
if (oldPos == curPos) {
if (_readPos > 0) {
Buffer.BlockCopy(_buffer, _readPos, _buffer, 0, _readLen - _readPos);
_readLen -= _readPos;
_readPos = 0;
}
// If we still have buffered data, we must update the stream's
// position so our Position property is correct.
if (_readLen > 0)
SeekCore(_readLen, SeekOrigin.Current);
}
else if (oldPos - _readPos < curPos && curPos < oldPos + _readLen - _readPos) {
int diff = (int)(curPos - oldPos);
Buffer.BlockCopy(_buffer, _readPos+diff, _buffer, 0, _readLen - (_readPos + diff));
_readLen -= (_readPos + diff);
_readPos = 0;
if (_readLen > 0)
SeekCore(_readLen, SeekOrigin.Current);
}
else {
// Lose the read buffer.
_readPos = 0;
_readLen = 0;
}
Debug.Assert(_readLen >= 0 && _readPos <= _readLen, "_readLen should be nonnegative, and _readPos should be less than or equal _readLen");
Debug.Assert(curPos == Position, "Seek optimization: curPos != Position! Buffer math was mangled.");
}
return curPos;
}
#endif //_ENABLE_STREAM_FACTORING
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Flush()
{
try {
if (_writePos > 0)
FlushWrite(false);
else if (_readPos < _readLen)
FlushRead();
}
finally {
_writePos = 0;
_readPos = 0;
_readLen = 0;
}
}
// Reading is done by blocks from the file, but someone could read
// 1 byte from the buffer then write. At that point, the OS's file
// pointer is out of [....] with the stream's position. All write
// functions should call this function to preserve the position in the file.
[MethodImplAttribute(MethodImplOptions.Synchronized)]
protected void FlushRead() {
#if _ENABLE_STREAM_FACTORING
Debug.Assert(_writePos == 0, "BufferedStream: Write buffer must be empty in FlushRead!");
if (_readPos - _readLen != 0) {
Debug.Assert(CanSeek, "BufferedStream will lose buffered read data now.");
if (CanSeek)
SeekCore(_readPos - _readLen, SeekOrigin.Current);
}
_readPos = 0;
_readLen = 0;
#endif //_ENABLE_STREAM_FACTORING
}
// Writes are buffered. Anytime the buffer fills up
// (_writePos + delta > bufferSize) or the buffer switches to reading
// and there is left over data (_writePos > 0), this function must be called.
[MethodImplAttribute(MethodImplOptions.Synchronized)]
protected void FlushWrite(bool blockForWrite) {
Debug.Assert(_readPos == 0 && _readLen == 0, "BufferedStream: Read buffer must be empty in FlushWrite!");
if (_writePos > 0)
WriteCore(_buffer, 0, _writePos, blockForWrite);
_writePos = 0;
}
protected override void Dispose(bool disposing)
{
try {
// Flush data to disk iff we were writing.
if (_writePos > 0) {
// With our Whidbey async IO & overlapped support for AD unloads,
// we don't strictly need to block here to release resources
// if the underlying IO is overlapped since that support
// takes care of the pinning & freeing the
// overlapped struct. We need to do this when called from
// Close so that the handle is closed when Close returns, but
// we do't need to call EndWrite from the finalizer.
// Additionally, if we do call EndWrite, we block forever
// because AD unloads prevent us from running the managed
// callback from the IO completion port. Blocking here when
// called from the finalizer during AD unload is clearly wrong,
// but we can't use any sort of test for whether the AD is
// unloading because if we weren't unloading, an AD unload
// could happen on a separate thread before we call EndWrite.
FlushWrite(disposing);
}
}
finally {
// Don't set the buffer to null, to avoid a NullReferenceException
// when users have a race condition in their code (ie, they call
// Close when calling another method on Stream like Read).
//_buffer = null;
_readPos = 0;
_readLen = 0;
_writePos = 0;
base.Dispose(disposing);
}
}
//
// Helper methods
//
#if _ENABLE_STREAM_FACTORING
protected int BufferedWritePosition
{
// Making the getter thread safe is not very useful anyways
get {
return _writePos;
}
//set {
// Interlocked.Exchange(ref _writePos, value);
//}
}
protected int BufferedReadPosition
{
// Making the getter thread safe is not very useful anyways
get {
return _readPos;
}
//set {
// Interlocked.Exchange(ref _readPos, value);
//}
}
#endif //_ENABLE_STREAM_FACTORING
protected long UnderlyingStreamPosition
{
// Making the getter thread safe is not very useful anyways
get {
return pos;
}
set {
Interlocked.Exchange(ref pos, value);
}
}
protected long AddUnderlyingStreamPosition(long posDelta)
{
return Interlocked.Add(ref pos, posDelta);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
protected internal void DiscardBuffer()
{
_readPos = 0;
_readLen = 0;
_writePos = 0;
}
private void WriteCore(byte[] buffer, int offset, int count, bool blockForWrite)
{
long streamPos;
WriteCore(buffer, offset, count, blockForWrite, out streamPos);
}
protected abstract void WriteCore(byte[] buffer, int offset, int count, bool blockForWrite, out long streamPos);
#if _ENABLE_STREAM_FACTORING
private int ReadCore(byte[] buffer, int offset, int count)
{
long streamPos;
return ReadCore(buffer, offset, count, out streamPos);
}
private int EndReadCore(IAsyncResult asyncResult)
{
long streamPos;
return EndReadCore(asyncResult, out streamPos);
}
private void EndWriteCore(IAsyncResult asyncResult)
{
long streamPos;
EndWriteCore(asyncResult, out streamPos);
}
// Derived streams should implement the following core methods
protected abstract int ReadCore(byte[] buffer, int offset, int count, out long streamPos);
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.AppDomain, ResourceScope.AppDomain)]
protected abstract IAsyncResult BeginReadCore(byte[] bytes, int offset, int numBytes, AsyncCallback userCallback, Object stateObject, int numBufferedBytesRead);
protected abstract int EndReadCore(IAsyncResult asyncResult, out long streamPos);
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.AppDomain, ResourceScope.AppDomain)]
protected abstract IAsyncResult BeginWriteCore(byte[] bytes, int offset, int numBytes, AsyncCallback userCallback, Object stateObject);
protected abstract void EndWriteCore(IAsyncResult asyncResult, out long streamPos);
protected abstract long SeekCore(long offset, SeekOrigin origin);
#endif //_ENABLE_STREAM_FACTORING
}
#if _ENABLE_STREAM_FACTORING
// Fake async result
unsafe internal sealed class BufferedStreamAsyncResult : IAsyncResult
{
// User code callback
internal AsyncCallback _userCallback;
internal Object _userStateObject;
internal int _numBytes; // number of bytes read OR written
//internal int _errorCode;
internal bool _isWrite; // Whether this is a read or a write
public Object AsyncState
{
get { return _userStateObject; }
}
public bool IsCompleted
{
get { return true; }
}
public WaitHandle AsyncWaitHandle
{
get { return null; }
}
public bool CompletedSynchronously
{
get { return true; }
}
internal static IAsyncResult Complete(int numBufferedBytes, AsyncCallback userCallback, Object userStateObject, bool isWrite)
{
// Fake async
BufferedStreamAsyncResult asyncResult = new BufferedStreamAsyncResult();
asyncResult._numBytes = numBufferedBytes;
asyncResult._userCallback = userCallback;
asyncResult._userStateObject = userStateObject;
asyncResult._isWrite = isWrite;
if (userCallback != null) {
userCallback(asyncResult);
}
return asyncResult;
}
}
#endif //_ENABLE_STREAM_FACTORING
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: client/conf_hero.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace UF.Config {
/// <summary>Holder for reflection information generated from client/conf_hero.proto</summary>
public static partial class ConfHeroReflection {
#region Descriptor
/// <summary>File descriptor for client/conf_hero.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ConfHeroReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChZjbGllbnQvY29uZl9oZXJvLnByb3RvEgZjbGllbnQiuAEKCENvbmZIZXJv",
"EhcKD2F0dGFja19zZWN0aW9ucxgBIAMoBRIcChRhdHRhY2tfd2FpdF90aW1l",
"X21pbhgCIAMoAhIcChRhdHRhY2tfd2FpdF90aW1lX21heBgDIAMoAhIYChBh",
"dHRhY2tfd2FpdF90aW1lGAQgAygCEhUKDWF0dGFja193ZWlnaHQYBSABKAIS",
"FAoMc2tpbGxfd2VpZ2h0GAYgAygCEhAKCHRlc3RfYWRkGAcgASgFQgyqAglV",
"Ri5Db25maWdiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::UF.Config.ConfHero), global::UF.Config.ConfHero.Parser, new[]{ "AttackSections", "AttackWaitTimeMin", "AttackWaitTimeMax", "AttackWaitTime", "AttackWeight", "SkillWeight", "TestAdd" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ConfHero : pb::IMessage<ConfHero> {
private static readonly pb::MessageParser<ConfHero> _parser = new pb::MessageParser<ConfHero>(() => new ConfHero());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ConfHero> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::UF.Config.ConfHeroReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConfHero() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConfHero(ConfHero other) : this() {
attackSections_ = other.attackSections_.Clone();
attackWaitTimeMin_ = other.attackWaitTimeMin_.Clone();
attackWaitTimeMax_ = other.attackWaitTimeMax_.Clone();
attackWaitTime_ = other.attackWaitTime_.Clone();
attackWeight_ = other.attackWeight_;
skillWeight_ = other.skillWeight_.Clone();
testAdd_ = other.testAdd_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConfHero Clone() {
return new ConfHero(this);
}
/// <summary>Field number for the "attack_sections" field.</summary>
public const int AttackSectionsFieldNumber = 1;
private static readonly pb::FieldCodec<int> _repeated_attackSections_codec
= pb::FieldCodec.ForInt32(10);
private readonly pbc::RepeatedField<int> attackSections_ = new pbc::RepeatedField<int>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<int> AttackSections {
get { return attackSections_; }
}
/// <summary>Field number for the "attack_wait_time_min" field.</summary>
public const int AttackWaitTimeMinFieldNumber = 2;
private static readonly pb::FieldCodec<float> _repeated_attackWaitTimeMin_codec
= pb::FieldCodec.ForFloat(18);
private readonly pbc::RepeatedField<float> attackWaitTimeMin_ = new pbc::RepeatedField<float>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<float> AttackWaitTimeMin {
get { return attackWaitTimeMin_; }
}
/// <summary>Field number for the "attack_wait_time_max" field.</summary>
public const int AttackWaitTimeMaxFieldNumber = 3;
private static readonly pb::FieldCodec<float> _repeated_attackWaitTimeMax_codec
= pb::FieldCodec.ForFloat(26);
private readonly pbc::RepeatedField<float> attackWaitTimeMax_ = new pbc::RepeatedField<float>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<float> AttackWaitTimeMax {
get { return attackWaitTimeMax_; }
}
/// <summary>Field number for the "attack_wait_time" field.</summary>
public const int AttackWaitTimeFieldNumber = 4;
private static readonly pb::FieldCodec<float> _repeated_attackWaitTime_codec
= pb::FieldCodec.ForFloat(34);
private readonly pbc::RepeatedField<float> attackWaitTime_ = new pbc::RepeatedField<float>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<float> AttackWaitTime {
get { return attackWaitTime_; }
}
/// <summary>Field number for the "attack_weight" field.</summary>
public const int AttackWeightFieldNumber = 5;
private float attackWeight_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float AttackWeight {
get { return attackWeight_; }
set {
attackWeight_ = value;
}
}
/// <summary>Field number for the "skill_weight" field.</summary>
public const int SkillWeightFieldNumber = 6;
private static readonly pb::FieldCodec<float> _repeated_skillWeight_codec
= pb::FieldCodec.ForFloat(50);
private readonly pbc::RepeatedField<float> skillWeight_ = new pbc::RepeatedField<float>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<float> SkillWeight {
get { return skillWeight_; }
}
/// <summary>Field number for the "test_add" field.</summary>
public const int TestAddFieldNumber = 7;
private int testAdd_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int TestAdd {
get { return testAdd_; }
set {
testAdd_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ConfHero);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ConfHero other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!attackSections_.Equals(other.attackSections_)) return false;
if(!attackWaitTimeMin_.Equals(other.attackWaitTimeMin_)) return false;
if(!attackWaitTimeMax_.Equals(other.attackWaitTimeMax_)) return false;
if(!attackWaitTime_.Equals(other.attackWaitTime_)) return false;
if (AttackWeight != other.AttackWeight) return false;
if(!skillWeight_.Equals(other.skillWeight_)) return false;
if (TestAdd != other.TestAdd) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= attackSections_.GetHashCode();
hash ^= attackWaitTimeMin_.GetHashCode();
hash ^= attackWaitTimeMax_.GetHashCode();
hash ^= attackWaitTime_.GetHashCode();
if (AttackWeight != 0F) hash ^= AttackWeight.GetHashCode();
hash ^= skillWeight_.GetHashCode();
if (TestAdd != 0) hash ^= TestAdd.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
attackSections_.WriteTo(output, _repeated_attackSections_codec);
attackWaitTimeMin_.WriteTo(output, _repeated_attackWaitTimeMin_codec);
attackWaitTimeMax_.WriteTo(output, _repeated_attackWaitTimeMax_codec);
attackWaitTime_.WriteTo(output, _repeated_attackWaitTime_codec);
if (AttackWeight != 0F) {
output.WriteRawTag(45);
output.WriteFloat(AttackWeight);
}
skillWeight_.WriteTo(output, _repeated_skillWeight_codec);
if (TestAdd != 0) {
output.WriteRawTag(56);
output.WriteInt32(TestAdd);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += attackSections_.CalculateSize(_repeated_attackSections_codec);
size += attackWaitTimeMin_.CalculateSize(_repeated_attackWaitTimeMin_codec);
size += attackWaitTimeMax_.CalculateSize(_repeated_attackWaitTimeMax_codec);
size += attackWaitTime_.CalculateSize(_repeated_attackWaitTime_codec);
if (AttackWeight != 0F) {
size += 1 + 4;
}
size += skillWeight_.CalculateSize(_repeated_skillWeight_codec);
if (TestAdd != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(TestAdd);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ConfHero other) {
if (other == null) {
return;
}
attackSections_.Add(other.attackSections_);
attackWaitTimeMin_.Add(other.attackWaitTimeMin_);
attackWaitTimeMax_.Add(other.attackWaitTimeMax_);
attackWaitTime_.Add(other.attackWaitTime_);
if (other.AttackWeight != 0F) {
AttackWeight = other.AttackWeight;
}
skillWeight_.Add(other.skillWeight_);
if (other.TestAdd != 0) {
TestAdd = other.TestAdd;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10:
case 8: {
attackSections_.AddEntriesFrom(input, _repeated_attackSections_codec);
break;
}
case 18:
case 21: {
attackWaitTimeMin_.AddEntriesFrom(input, _repeated_attackWaitTimeMin_codec);
break;
}
case 26:
case 29: {
attackWaitTimeMax_.AddEntriesFrom(input, _repeated_attackWaitTimeMax_codec);
break;
}
case 34:
case 37: {
attackWaitTime_.AddEntriesFrom(input, _repeated_attackWaitTime_codec);
break;
}
case 45: {
AttackWeight = input.ReadFloat();
break;
}
case 50:
case 53: {
skillWeight_.AddEntriesFrom(input, _repeated_skillWeight_codec);
break;
}
case 56: {
TestAdd = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.IO;
using log4net;
using FluorineFx.Messaging.Api;
using FluorineFx.Messaging.Api.Messaging;
using FluorineFx.Messaging.Api.Stream;
using FluorineFx.Messaging.Rtmp.Event;
using FluorineFx.Messaging.Rtmp.Stream.Messages;
namespace FluorineFx.Messaging.Rtmp.Stream
{
/// <summary>
/// State machine for video frame dropping in live streams.
/// <p>
/// We start sending all frame types. Disposable interframes can be dropped any
/// time without affecting the current state. If a regular interframe is dropped,
/// all future frames up to the next keyframes are dropped as well. Dropped
/// keyframes result in only keyframes being sent. If two consecutive keyframes
/// have been successfully sent, regular interframes will be sent in the next
/// iteration as well. If these frames all went through, disposable interframes
/// are sent again.
/// </p>
/// So from highest to lowest bandwidth and back, the states go as follows:
/// <ul>
/// <li>all frames</li>
/// <li>keyframes and interframes</li>
/// <li>keyframes</li>
/// <li>keyframes and interframes</li>
/// <li>all frames</li>
/// </ul>
/// </summary>
class VideoFrameDropper : IFrameDropper
{
private static ILog log = LogManager.GetLogger(typeof(VideoFrameDropper));
/// <summary>
/// Current state.
/// </summary>
private FrameDropperState _state;
public VideoFrameDropper()
{
Reset();
}
#region IFrameDropper Members
public bool CanSendPacket(RtmpMessage message, long pending)
{
IRtmpEvent packet = message.body;
if (!(packet is VideoData))
{
// We currently only drop video packets.
return true;
}
VideoData video = packet as VideoData;
FrameType type = video.FrameType;
bool result = false;
switch (_state)
{
case FrameDropperState.SEND_ALL:
// All packets will be sent.
result = true;
break;
case FrameDropperState.SEND_INTERFRAMES:
// Only keyframes and interframes will be sent.
if (type == FrameType.Keyframe)
{
if (pending == 0)
{
// Send all frames from now on.
_state = FrameDropperState.SEND_ALL;
}
result = true;
}
else if (type == FrameType.Interframe)
{
result = true;
}
break;
case FrameDropperState.SEND_KEYFRAMES:
// Only keyframes will be sent.
result = (type == FrameType.Keyframe);
if (result && pending == 0)
{
// Maybe switch back to SEND_INTERFRAMES after the next keyframe
_state = FrameDropperState.SEND_KEYFRAMES_CHECK;
}
break;
case FrameDropperState.SEND_KEYFRAMES_CHECK:
// Only keyframes will be sent.
result = (type == FrameType.Keyframe);
if (result && pending == 0)
{
// Continue with sending interframes as well
_state = FrameDropperState.SEND_INTERFRAMES;
}
break;
default:
break;
}
return result;
}
public void DropPacket(RtmpMessage message)
{
IRtmpEvent packet = message.body;
if (!(packet is VideoData))
{
// Only check video packets.
return;
}
VideoData video = packet as VideoData;
FrameType type = video.FrameType;
switch (_state)
{
case FrameDropperState.SEND_ALL:
if (type == FrameType.DisposableInterframe)
{
// Remain in state, packet is safe to drop.
return;
}
else if (type == FrameType.Interframe)
{
// Drop all frames until the next keyframe.
_state = FrameDropperState.SEND_KEYFRAMES;
return;
}
else if (type == FrameType.Keyframe)
{
// Drop all frames until the next keyframe.
_state = FrameDropperState.SEND_KEYFRAMES;
return;
}
break;
case FrameDropperState.SEND_INTERFRAMES:
if (type == FrameType.Interframe)
{
// Drop all frames until the next keyframe.
_state = FrameDropperState.SEND_KEYFRAMES_CHECK;
return;
}
else if (type == FrameType.Keyframe)
{
// Drop all frames until the next keyframe.
_state = FrameDropperState.SEND_KEYFRAMES;
return;
}
break;
case FrameDropperState.SEND_KEYFRAMES:
// Remain in state.
break;
case FrameDropperState.SEND_KEYFRAMES_CHECK:
if (type == FrameType.Keyframe)
{
// Switch back to sending keyframes, but don't move to SEND_INTERFRAMES afterwards.
_state = FrameDropperState.SEND_KEYFRAMES;
return;
}
break;
default:
break;
}
}
public void SendPacket(RtmpMessage message)
{
}
public void Reset()
{
Reset(FrameDropperState.SEND_ALL);
}
public void Reset(FrameDropperState state)
{
_state = state;
}
#endregion
}
}
| |
using System;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Visuals.Media.Imaging;
using SkiaSharp;
namespace Avalonia.Skia
{
public static class SkiaSharpExtensions
{
public static SKFilterQuality ToSKFilterQuality(this BitmapInterpolationMode interpolationMode)
{
switch (interpolationMode)
{
case BitmapInterpolationMode.LowQuality:
return SKFilterQuality.Low;
case BitmapInterpolationMode.MediumQuality:
return SKFilterQuality.Medium;
case BitmapInterpolationMode.HighQuality:
return SKFilterQuality.High;
case BitmapInterpolationMode.Default:
return SKFilterQuality.None;
default:
throw new ArgumentOutOfRangeException(nameof(interpolationMode), interpolationMode, null);
}
}
public static SKBlendMode ToSKBlendMode(this BitmapBlendingMode blendingMode)
{
switch (blendingMode)
{
case BitmapBlendingMode.SourceOver:
return SKBlendMode.SrcOver;
case BitmapBlendingMode.Source:
return SKBlendMode.Src;
case BitmapBlendingMode.SourceIn:
return SKBlendMode.SrcIn;
case BitmapBlendingMode.SourceOut:
return SKBlendMode.SrcOut;
case BitmapBlendingMode.SourceAtop:
return SKBlendMode.SrcATop;
case BitmapBlendingMode.Destination:
return SKBlendMode.Dst;
case BitmapBlendingMode.DestinationIn:
return SKBlendMode.DstIn;
case BitmapBlendingMode.DestinationOut:
return SKBlendMode.DstOut;
case BitmapBlendingMode.DestinationOver:
return SKBlendMode.DstOver;
case BitmapBlendingMode.DestinationAtop:
return SKBlendMode.DstATop;
case BitmapBlendingMode.Xor:
return SKBlendMode.Xor;
case BitmapBlendingMode.Plus:
return SKBlendMode.Plus;
default:
throw new ArgumentOutOfRangeException(nameof(blendingMode), blendingMode, null);
}
}
public static SKPoint ToSKPoint(this Point p)
{
return new SKPoint((float)p.X, (float)p.Y);
}
public static SKPoint ToSKPoint(this Vector p)
{
return new SKPoint((float)p.X, (float)p.Y);
}
public static SKRect ToSKRect(this Rect r)
{
return new SKRect((float)r.X, (float)r.Y, (float)r.Right, (float)r.Bottom);
}
public static SKRoundRect ToSKRoundRect(this RoundedRect r)
{
var rc = r.Rect.ToSKRect();
var result = new SKRoundRect();
result.SetRectRadii(rc,
new[]
{
r.RadiiTopLeft.ToSKPoint(), r.RadiiTopRight.ToSKPoint(),
r.RadiiBottomRight.ToSKPoint(), r.RadiiBottomLeft.ToSKPoint(),
});
return result;
}
public static Rect ToAvaloniaRect(this SKRect r)
{
return new Rect(r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top);
}
public static SKMatrix ToSKMatrix(this Matrix m)
{
var sm = new SKMatrix
{
ScaleX = (float)m.M11,
SkewX = (float)m.M21,
TransX = (float)m.M31,
SkewY = (float)m.M12,
ScaleY = (float)m.M22,
TransY = (float)m.M32,
Persp0 = 0,
Persp1 = 0,
Persp2 = 1
};
return sm;
}
public static SKColor ToSKColor(this Media.Color c)
{
return new SKColor(c.R, c.G, c.B, c.A);
}
public static SKColorType ToSkColorType(this PixelFormat fmt)
{
if (fmt == PixelFormat.Rgb565)
return SKColorType.Rgb565;
if (fmt == PixelFormat.Bgra8888)
return SKColorType.Bgra8888;
if (fmt == PixelFormat.Rgba8888)
return SKColorType.Rgba8888;
throw new ArgumentException("Unknown pixel format: " + fmt);
}
public static PixelFormat ToPixelFormat(this SKColorType fmt)
{
if (fmt == SKColorType.Rgb565)
return PixelFormat.Rgb565;
if (fmt == SKColorType.Bgra8888)
return PixelFormat.Bgra8888;
if (fmt == SKColorType.Rgba8888)
return PixelFormat.Rgba8888;
throw new ArgumentException("Unknown pixel format: " + fmt);
}
public static SKAlphaType ToSkAlphaType(this AlphaFormat fmt)
{
return fmt switch
{
AlphaFormat.Premul => SKAlphaType.Premul,
AlphaFormat.Unpremul => SKAlphaType.Unpremul,
AlphaFormat.Opaque => SKAlphaType.Opaque,
_ => throw new ArgumentException($"Unknown alpha format: {fmt}")
};
}
public static AlphaFormat ToAlphaFormat(this SKAlphaType fmt)
{
return fmt switch
{
SKAlphaType.Premul => AlphaFormat.Premul,
SKAlphaType.Unpremul => AlphaFormat.Unpremul,
SKAlphaType.Opaque => AlphaFormat.Opaque,
_ => throw new ArgumentException($"Unknown alpha format: {fmt}")
};
}
public static SKShaderTileMode ToSKShaderTileMode(this Media.GradientSpreadMethod m)
{
switch (m)
{
default:
case Media.GradientSpreadMethod.Pad: return SKShaderTileMode.Clamp;
case Media.GradientSpreadMethod.Reflect: return SKShaderTileMode.Mirror;
case Media.GradientSpreadMethod.Repeat: return SKShaderTileMode.Repeat;
}
}
public static SKTextAlign ToSKTextAlign(this TextAlignment a)
{
switch (a)
{
default:
case TextAlignment.Left: return SKTextAlign.Left;
case TextAlignment.Center: return SKTextAlign.Center;
case TextAlignment.Right: return SKTextAlign.Right;
}
}
public static TextAlignment ToAvalonia(this SKTextAlign a)
{
switch (a)
{
default:
case SKTextAlign.Left: return TextAlignment.Left;
case SKTextAlign.Center: return TextAlignment.Center;
case SKTextAlign.Right: return TextAlignment.Right;
}
}
public static FontStyle ToAvalonia(this SKFontStyleSlant slant)
{
return slant switch
{
SKFontStyleSlant.Upright => FontStyle.Normal,
SKFontStyleSlant.Italic => FontStyle.Italic,
SKFontStyleSlant.Oblique => FontStyle.Oblique,
_ => throw new ArgumentOutOfRangeException(nameof (slant), slant, null)
};
}
public static SKPath Clone(this SKPath src)
{
return src != null ? new SKPath(src) : null;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Storage.Internal;
namespace Orleans.Storage
{
/// <summary>
/// This is a simple in-memory grain implementation of a storage provider.
/// </summary>
/// <remarks>
/// This storage provider is ONLY intended for simple in-memory Development / Unit Test scenarios.
/// This class should NOT be used in Production environment,
/// because [by-design] it does not provide any resilience
/// or long-term persistence capabilities.
/// </remarks>
/// <example>
/// Example configuration for this storage provider in OrleansConfiguration.xml file:
/// <code>
/// <OrleansConfiguration xmlns="urn:orleans">
/// <Globals>
/// <StorageProviders>
/// <Provider Type="Orleans.Storage.MemoryStorage" Name="MemoryStore" />
/// </StorageProviders>
/// </code>
/// </example>
[DebuggerDisplay("MemoryStore:{Name}")]
public class MemoryGrainStorage : IGrainStorage, IDisposable
{
private MemoryGrainStorageOptions options;
private const string STATE_STORE_NAME = "MemoryStorage";
private Lazy<IMemoryStorageGrain>[] storageGrains;
private ILogger logger;
private IGrainFactory grainFactory;
/// <summary> Name of this storage provider instance. </summary>
private readonly string name;
/// <summary> Default constructor. </summary>
public MemoryGrainStorage(string name, MemoryGrainStorageOptions options, ILoggerFactory loggerFactory, IGrainFactory grainFactory)
{
this.options = options;
this.name = name;
this.logger = loggerFactory.CreateLogger($"{this.GetType().FullName}.{name}");
this.grainFactory = grainFactory;
//Init
logger.Info("Init: Name={0} NumStorageGrains={1}", name, this.options.NumStorageGrains);
storageGrains = new Lazy<IMemoryStorageGrain>[this.options.NumStorageGrains];
for (int i = 0; i < this.options.NumStorageGrains; i++)
{
int idx = i; // Capture variable to avoid modified closure error
storageGrains[idx] = new Lazy<IMemoryStorageGrain>(() => this.grainFactory.GetGrain<IMemoryStorageGrain>(idx));
}
}
/// <summary> Read state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ReadStateAsync"/>
public virtual async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Read Keys={0}", StorageProviderUtils.PrintKeys(keys));
string id = HierarchicalKeyStore.MakeStoreKey(keys);
IMemoryStorageGrain storageGrain = GetStorageGrain(id);
var state = await storageGrain.ReadStateAsync(STATE_STORE_NAME, id);
if (state != null)
{
grainState.ETag = state.ETag;
grainState.State = state.State;
}
}
/// <summary> Write state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.WriteStateAsync"/>
public virtual async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
string key = HierarchicalKeyStore.MakeStoreKey(keys);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Write {0} ", StorageProviderUtils.PrintOneWrite(keys, grainState.State, grainState.ETag));
IMemoryStorageGrain storageGrain = GetStorageGrain(key);
try
{
grainState.ETag = await storageGrain.WriteStateAsync(STATE_STORE_NAME, key, grainState);
}
catch (MemoryStorageEtagMismatchException e)
{
throw e.AsInconsistentStateException();
}
}
/// <summary> Delete / Clear state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ClearStateAsync"/>
public virtual async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Delete Keys={0} Etag={1}", StorageProviderUtils.PrintKeys(keys), grainState.ETag);
string key = HierarchicalKeyStore.MakeStoreKey(keys);
IMemoryStorageGrain storageGrain = GetStorageGrain(key);
try
{
await storageGrain.DeleteStateAsync(STATE_STORE_NAME, key, grainState.ETag);
grainState.ETag = null;
}
catch (MemoryStorageEtagMismatchException e)
{
throw e.AsInconsistentStateException();
}
}
private static IEnumerable<Tuple<string, string>> MakeKeys(string grainType, GrainReference grain)
{
return new[]
{
Tuple.Create("GrainType", grainType),
Tuple.Create("GrainId", grain.ToKeyString())
};
}
private IMemoryStorageGrain GetStorageGrain(string id)
{
int idx = StorageProviderUtils.PositiveHash(id.GetHashCode(), this.options.NumStorageGrains);
IMemoryStorageGrain storageGrain = storageGrains[idx].Value;
return storageGrain;
}
internal static Func<IDictionary<string, object>, bool> GetComparer<T>(string rangeParamName, T fromValue, T toValue) where T : IComparable
{
Comparer comparer = Comparer.DefaultInvariant;
bool sameRange = comparer.Compare(fromValue, toValue) == 0; // FromValue == ToValue
bool insideRange = comparer.Compare(fromValue, toValue) < 0; // FromValue < ToValue
Func<IDictionary<string, object>, bool> compareClause;
if (sameRange)
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) == 0;
};
}
else if (insideRange)
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) >= 0 && comparer.Compare(obj, toValue) <= 0;
};
}
else
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) >= 0 || comparer.Compare(obj, toValue) <= 0;
};
}
return compareClause;
}
public void Dispose()
{
for (int i = 0; i < this.options.NumStorageGrains; i++)
storageGrains[i] = null;
}
}
/// <summary>
/// Factory for creating MemoryGrainStorage
/// </summary>
public class MemoryGrainStorageFactory
{
public static IGrainStorage Create(IServiceProvider services, string name)
{
return ActivatorUtilities.CreateInstance<MemoryGrainStorage>(services,
services.GetRequiredService<IOptionsSnapshot<MemoryGrainStorageOptions>>().Get(name), name);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Collections.Generic;
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class ObjectWriter
{
private Queue<object> _objectQueue;
private ObjectIDGenerator _idGenerator;
private int _currentId;
private ISurrogateSelector _surrogates;
private StreamingContext _context;
private BinaryFormatterWriter _serWriter;
private SerializationObjectManager _objectManager;
private long _topId;
private string _topName = null;
private InternalFE _formatterEnums;
private SerializationBinder _binder;
private SerObjectInfoInit _serObjectInfoInit;
private IFormatterConverter _formatterConverter;
internal object[] _crossAppDomainArray = null;
internal List<object> _internalCrossAppDomainArray = null;
private object _previousObj = null;
private long _previousId = 0;
private Type _previousType = null;
private InternalPrimitiveTypeE _previousCode = InternalPrimitiveTypeE.Invalid;
internal ObjectWriter(ISurrogateSelector selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder binder)
{
_currentId = 1;
_surrogates = selector;
_context = context;
_binder = binder;
_formatterEnums = formatterEnums;
_objectManager = new SerializationObjectManager(context);
}
internal void Serialize(object graph, BinaryFormatterWriter serWriter, bool fCheck)
{
if (graph == null)
{
throw new ArgumentNullException(nameof(graph));
}
if (serWriter == null)
{
throw new ArgumentNullException(nameof(serWriter));
}
_serWriter = serWriter;
serWriter.WriteBegin();
long headerId = 0;
object obj;
long objectId;
bool isNew;
// allocations if methodCall or methodResponse and no graph
_idGenerator = new ObjectIDGenerator();
_objectQueue = new Queue<object>();
_formatterConverter = new FormatterConverter();
_serObjectInfoInit = new SerObjectInfoInit();
_topId = InternalGetId(graph, false, null, out isNew);
headerId = -1;
WriteSerializedStreamHeader(_topId, headerId);
_objectQueue.Enqueue(graph);
while ((obj = GetNext(out objectId)) != null)
{
WriteObjectInfo objectInfo = null;
// GetNext will return either an object or a WriteObjectInfo.
// A WriteObjectInfo is returned if this object was member of another object
if (obj is WriteObjectInfo)
{
objectInfo = (WriteObjectInfo)obj;
}
else
{
objectInfo = WriteObjectInfo.Serialize(obj, _surrogates, _context, _serObjectInfoInit, _formatterConverter, this, _binder);
objectInfo._assemId = GetAssemblyId(objectInfo);
}
objectInfo._objectId = objectId;
NameInfo typeNameInfo = TypeToNameInfo(objectInfo);
Write(objectInfo, typeNameInfo, typeNameInfo);
PutNameInfo(typeNameInfo);
objectInfo.ObjectEnd();
}
serWriter.WriteSerializationHeaderEnd();
serWriter.WriteEnd();
// Invoke OnSerialized Event
_objectManager.RaiseOnSerializedEvent();
}
internal SerializationObjectManager ObjectManager => _objectManager;
// Writes a given object to the stream.
private void Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)
{
object obj = objectInfo._obj;
if (obj == null)
{
throw new ArgumentNullException(nameof(objectInfo) + "." + nameof(objectInfo._obj));
}
Type objType = objectInfo._objectType;
long objectId = objectInfo._objectId;
if (ReferenceEquals(objType, Converter.s_typeofString))
{
// Top level String
memberNameInfo._objectId = objectId;
_serWriter.WriteObjectString((int)objectId, obj.ToString());
}
else
{
if (objectInfo._isArray)
{
WriteArray(objectInfo, memberNameInfo, null);
}
else
{
string[] memberNames;
Type[] memberTypes;
object[] memberData;
objectInfo.GetMemberInfo(out memberNames, out memberTypes, out memberData);
// Only Binary needs to transmit types for ISerializable because the binary formatter transmits the types in URT format.
// Soap transmits all types as strings, so it is up to the ISerializable object to convert the string back to its URT type
if (objectInfo._isSi || CheckTypeFormat(_formatterEnums._typeFormat, FormatterTypeStyle.TypesAlways))
{
memberNameInfo._transmitTypeOnObject = true;
memberNameInfo._isParentTypeOnObject = true;
typeNameInfo._transmitTypeOnObject = true;
typeNameInfo._isParentTypeOnObject = true;
}
var memberObjectInfos = new WriteObjectInfo[memberNames.Length];
// Get assembly information
// Binary Serializer, assembly names need to be
// written before objects are referenced.
// GetAssemId here will write out the
// assemblyStrings at the right Binary
// Serialization object boundary.
for (int i = 0; i < memberTypes.Length; i++)
{
Type type =
memberTypes[i] != null ? memberTypes[i] :
memberData[i] != null ? GetType(memberData[i]) :
Converter.s_typeofObject;
InternalPrimitiveTypeE code = ToCode(type);
if ((code == InternalPrimitiveTypeE.Invalid) &&
(!ReferenceEquals(type, Converter.s_typeofString)))
{
if (memberData[i] != null)
{
memberObjectInfos[i] = WriteObjectInfo.Serialize(
memberData[i],
_surrogates,
_context,
_serObjectInfoInit,
_formatterConverter,
this,
_binder);
memberObjectInfos[i]._assemId = GetAssemblyId(memberObjectInfos[i]);
}
else
{
memberObjectInfos[i] = WriteObjectInfo.Serialize(
memberTypes[i],
_surrogates,
_context,
_serObjectInfoInit,
_formatterConverter,
_binder);
memberObjectInfos[i]._assemId = GetAssemblyId(memberObjectInfos[i]);
}
}
}
Write(objectInfo, memberNameInfo, typeNameInfo, memberNames, memberTypes, memberData, memberObjectInfos);
}
}
}
// Writes a given object to the stream.
private void Write(WriteObjectInfo objectInfo,
NameInfo memberNameInfo,
NameInfo typeNameInfo,
string[] memberNames,
Type[] memberTypes,
object[] memberData,
WriteObjectInfo[] memberObjectInfos)
{
int numItems = memberNames.Length;
NameInfo topNameInfo = null;
if (memberNameInfo != null)
{
memberNameInfo._objectId = objectInfo._objectId;
_serWriter.WriteObject(memberNameInfo, typeNameInfo, numItems, memberNames, memberTypes, memberObjectInfos);
}
else if ((objectInfo._objectId == _topId) && (_topName != null))
{
topNameInfo = MemberToNameInfo(_topName);
topNameInfo._objectId = objectInfo._objectId;
_serWriter.WriteObject(topNameInfo, typeNameInfo, numItems, memberNames, memberTypes, memberObjectInfos);
}
else
{
if (!ReferenceEquals(objectInfo._objectType, Converter.s_typeofString))
{
typeNameInfo._objectId = objectInfo._objectId;
_serWriter.WriteObject(typeNameInfo, null, numItems, memberNames, memberTypes, memberObjectInfos);
}
}
if (memberNameInfo._isParentTypeOnObject)
{
memberNameInfo._transmitTypeOnObject = true;
memberNameInfo._isParentTypeOnObject = false;
}
else
{
memberNameInfo._transmitTypeOnObject = false;
}
// Write members
for (int i = 0; i < numItems; i++)
{
WriteMemberSetup(objectInfo, memberNameInfo, typeNameInfo, memberNames[i], memberTypes[i], memberData[i], memberObjectInfos[i]);
}
if (memberNameInfo != null)
{
memberNameInfo._objectId = objectInfo._objectId;
_serWriter.WriteObjectEnd(memberNameInfo, typeNameInfo);
}
else if ((objectInfo._objectId == _topId) && (_topName != null))
{
_serWriter.WriteObjectEnd(topNameInfo, typeNameInfo);
PutNameInfo(topNameInfo);
}
else if (!ReferenceEquals(objectInfo._objectType, Converter.s_typeofString))
{
_serWriter.WriteObjectEnd(typeNameInfo, typeNameInfo);
}
}
private void WriteMemberSetup(WriteObjectInfo objectInfo,
NameInfo memberNameInfo,
NameInfo typeNameInfo,
string memberName,
Type memberType,
object memberData,
WriteObjectInfo memberObjectInfo)
{
NameInfo newMemberNameInfo = MemberToNameInfo(memberName); // newMemberNameInfo contains the member type
if (memberObjectInfo != null)
{
newMemberNameInfo._assemId = memberObjectInfo._assemId;
}
newMemberNameInfo._type = memberType;
// newTypeNameInfo contains the data type
NameInfo newTypeNameInfo = null;
if (memberObjectInfo == null)
{
newTypeNameInfo = TypeToNameInfo(memberType);
}
else
{
newTypeNameInfo = TypeToNameInfo(memberObjectInfo);
}
newMemberNameInfo._transmitTypeOnObject = memberNameInfo._transmitTypeOnObject;
newMemberNameInfo._isParentTypeOnObject = memberNameInfo._isParentTypeOnObject;
WriteMembers(newMemberNameInfo, newTypeNameInfo, memberData, objectInfo, typeNameInfo, memberObjectInfo);
PutNameInfo(newMemberNameInfo);
PutNameInfo(newTypeNameInfo);
}
// Writes the members of an object
private void WriteMembers(NameInfo memberNameInfo,
NameInfo memberTypeNameInfo,
object memberData,
WriteObjectInfo objectInfo,
NameInfo typeNameInfo,
WriteObjectInfo memberObjectInfo)
{
Type memberType = memberNameInfo._type;
bool assignUniqueIdToValueType = false;
// Types are transmitted for a member as follows:
// The member is of type object
// The member object of type is ISerializable and
// Binary - Types always transmitted.
if (ReferenceEquals(memberType, Converter.s_typeofObject) || Nullable.GetUnderlyingType(memberType) != null)
{
memberTypeNameInfo._transmitTypeOnMember = true;
memberNameInfo._transmitTypeOnMember = true;
}
if (CheckTypeFormat(_formatterEnums._typeFormat, FormatterTypeStyle.TypesAlways) || (objectInfo._isSi))
{
memberTypeNameInfo._transmitTypeOnObject = true;
memberNameInfo._transmitTypeOnObject = true;
memberNameInfo._isParentTypeOnObject = true;
}
if (CheckForNull(objectInfo, memberNameInfo, memberTypeNameInfo, memberData))
{
return;
}
object outObj = memberData;
Type outType = null;
// If member type does not equal data type, transmit type on object.
if (memberTypeNameInfo._primitiveTypeEnum == InternalPrimitiveTypeE.Invalid)
{
outType = GetType(outObj);
if (!ReferenceEquals(memberType, outType))
{
memberTypeNameInfo._transmitTypeOnMember = true;
memberNameInfo._transmitTypeOnMember = true;
}
}
if (ReferenceEquals(memberType, Converter.s_typeofObject))
{
assignUniqueIdToValueType = true;
memberType = GetType(memberData);
if (memberObjectInfo == null)
{
TypeToNameInfo(memberType, memberTypeNameInfo);
}
else
{
TypeToNameInfo(memberObjectInfo, memberTypeNameInfo);
}
}
if (memberObjectInfo != null && memberObjectInfo._isArray)
{
// Array
long arrayId = 0;
if (outType == null)
{
outType = GetType(outObj);
}
// outObj is an array. It can never be a value type..
arrayId = Schedule(outObj, false, null, memberObjectInfo);
if (arrayId > 0)
{
// Array as object
memberNameInfo._objectId = arrayId;
WriteObjectRef(memberNameInfo, arrayId);
}
else
{
// Nested Array
_serWriter.WriteMemberNested(memberNameInfo);
memberObjectInfo._objectId = arrayId;
memberNameInfo._objectId = arrayId;
WriteArray(memberObjectInfo, memberNameInfo, memberObjectInfo);
objectInfo.ObjectEnd();
}
return;
}
if (!WriteKnownValueClass(memberNameInfo, memberTypeNameInfo, memberData))
{
if (outType == null)
{
outType = GetType(outObj);
}
long memberObjectId = Schedule(outObj, assignUniqueIdToValueType, outType, memberObjectInfo);
if (memberObjectId < 0)
{
// Nested object
memberObjectInfo._objectId = memberObjectId;
NameInfo newTypeNameInfo = TypeToNameInfo(memberObjectInfo);
newTypeNameInfo._objectId = memberObjectId;
Write(memberObjectInfo, memberNameInfo, newTypeNameInfo);
PutNameInfo(newTypeNameInfo);
memberObjectInfo.ObjectEnd();
}
else
{
// Object reference
memberNameInfo._objectId = memberObjectId;
WriteObjectRef(memberNameInfo, memberObjectId);
}
}
}
// Writes out an array
private void WriteArray(WriteObjectInfo objectInfo, NameInfo memberNameInfo, WriteObjectInfo memberObjectInfo)
{
bool isAllocatedMemberNameInfo = false;
if (memberNameInfo == null)
{
memberNameInfo = TypeToNameInfo(objectInfo);
isAllocatedMemberNameInfo = true;
}
memberNameInfo._isArray = true;
long objectId = objectInfo._objectId;
memberNameInfo._objectId = objectInfo._objectId;
// Get array type
Array array = (Array)objectInfo._obj;
//Type arrayType = array.GetType();
Type arrayType = objectInfo._objectType;
// Get type of array element
Type arrayElemType = arrayType.GetElementType();
WriteObjectInfo arrayElemObjectInfo = null;
if (!arrayElemType.IsPrimitive)
{
arrayElemObjectInfo = WriteObjectInfo.Serialize(arrayElemType, _surrogates, _context, _serObjectInfoInit, _formatterConverter, _binder);
arrayElemObjectInfo._assemId = GetAssemblyId(arrayElemObjectInfo);
}
NameInfo arrayElemTypeNameInfo = arrayElemObjectInfo == null ?
TypeToNameInfo(arrayElemType) :
TypeToNameInfo(arrayElemObjectInfo);
arrayElemTypeNameInfo._isArray = arrayElemTypeNameInfo._type.IsArray;
NameInfo arrayNameInfo = memberNameInfo;
arrayNameInfo._objectId = objectId;
arrayNameInfo._isArray = true;
arrayElemTypeNameInfo._objectId = objectId;
arrayElemTypeNameInfo._transmitTypeOnMember = memberNameInfo._transmitTypeOnMember;
arrayElemTypeNameInfo._transmitTypeOnObject = memberNameInfo._transmitTypeOnObject;
arrayElemTypeNameInfo._isParentTypeOnObject = memberNameInfo._isParentTypeOnObject;
// Get rank and length information
int rank = array.Rank;
int[] lengthA = new int[rank];
int[] lowerBoundA = new int[rank];
int[] upperBoundA = new int[rank];
for (int i = 0; i < rank; i++)
{
lengthA[i] = array.GetLength(i);
lowerBoundA[i] = array.GetLowerBound(i);
upperBoundA[i] = array.GetUpperBound(i);
}
InternalArrayTypeE arrayEnum;
if (arrayElemTypeNameInfo._isArray)
{
arrayEnum = rank == 1 ? InternalArrayTypeE.Jagged : InternalArrayTypeE.Rectangular;
}
else if (rank == 1)
{
arrayEnum = InternalArrayTypeE.Single;
}
else
{
arrayEnum = InternalArrayTypeE.Rectangular;
}
arrayElemTypeNameInfo._arrayEnum = arrayEnum;
// Byte array
if ((ReferenceEquals(arrayElemType, Converter.s_typeofByte)) && (rank == 1) && (lowerBoundA[0] == 0))
{
_serWriter.WriteObjectByteArray(memberNameInfo, arrayNameInfo, arrayElemObjectInfo, arrayElemTypeNameInfo, lengthA[0], lowerBoundA[0], (byte[])array);
return;
}
if (ReferenceEquals(arrayElemType, Converter.s_typeofObject) || Nullable.GetUnderlyingType(arrayElemType) != null)
{
memberNameInfo._transmitTypeOnMember = true;
arrayElemTypeNameInfo._transmitTypeOnMember = true;
}
if (CheckTypeFormat(_formatterEnums._typeFormat, FormatterTypeStyle.TypesAlways))
{
memberNameInfo._transmitTypeOnObject = true;
arrayElemTypeNameInfo._transmitTypeOnObject = true;
}
if (arrayEnum == InternalArrayTypeE.Single)
{
// Single Dimensional array
// BinaryFormatter array of primitive types is written out in the WriteSingleArray statement
// as a byte buffer
_serWriter.WriteSingleArray(memberNameInfo, arrayNameInfo, arrayElemObjectInfo, arrayElemTypeNameInfo, lengthA[0], lowerBoundA[0], array);
if (!(Converter.IsWriteAsByteArray(arrayElemTypeNameInfo._primitiveTypeEnum) && (lowerBoundA[0] == 0)))
{
object[] objectA = null;
if (!arrayElemType.IsValueType)
{
// Non-primitive type array
objectA = (object[])array;
}
int upperBound = upperBoundA[0] + 1;
for (int i = lowerBoundA[0]; i < upperBound; i++)
{
if (objectA == null)
{
WriteArrayMember(objectInfo, arrayElemTypeNameInfo, array.GetValue(i));
}
else
{
WriteArrayMember(objectInfo, arrayElemTypeNameInfo, objectA[i]);
}
}
_serWriter.WriteItemEnd();
}
}
else if (arrayEnum == InternalArrayTypeE.Jagged)
{
// Jagged Array
arrayNameInfo._objectId = objectId;
_serWriter.WriteJaggedArray(memberNameInfo, arrayNameInfo, arrayElemObjectInfo, arrayElemTypeNameInfo, lengthA[0], lowerBoundA[0]);
var objectA = (Array)array;
for (int i = lowerBoundA[0]; i < upperBoundA[0] + 1; i++)
{
WriteArrayMember(objectInfo, arrayElemTypeNameInfo, objectA.GetValue(i));
}
_serWriter.WriteItemEnd();
}
else
{
// Rectangle Array
// Get the length for all the ranks
arrayNameInfo._objectId = objectId;
_serWriter.WriteRectangleArray(memberNameInfo, arrayNameInfo, arrayElemObjectInfo, arrayElemTypeNameInfo, rank, lengthA, lowerBoundA);
// Check for a length of zero
bool bzero = false;
for (int i = 0; i < rank; i++)
{
if (lengthA[i] == 0)
{
bzero = true;
break;
}
}
if (!bzero)
{
WriteRectangle(objectInfo, rank, lengthA, array, arrayElemTypeNameInfo, lowerBoundA);
}
_serWriter.WriteItemEnd();
}
_serWriter.WriteObjectEnd(memberNameInfo, arrayNameInfo);
PutNameInfo(arrayElemTypeNameInfo);
if (isAllocatedMemberNameInfo)
{
PutNameInfo(memberNameInfo);
}
}
// Writes out an array element
private void WriteArrayMember(WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, object data)
{
arrayElemTypeNameInfo._isArrayItem = true;
if (CheckForNull(objectInfo, arrayElemTypeNameInfo, arrayElemTypeNameInfo, data))
{
return;
}
NameInfo actualTypeInfo = null;
Type dataType = null;
bool isObjectOnMember = false;
if (arrayElemTypeNameInfo._transmitTypeOnMember)
{
isObjectOnMember = true;
}
if (!isObjectOnMember && !arrayElemTypeNameInfo.IsSealed)
{
dataType = GetType(data);
if (!ReferenceEquals(arrayElemTypeNameInfo._type, dataType))
{
isObjectOnMember = true;
}
}
if (isObjectOnMember)
{
// Object array, need type of member
if (dataType == null)
{
dataType = GetType(data);
}
actualTypeInfo = TypeToNameInfo(dataType);
actualTypeInfo._transmitTypeOnMember = true;
actualTypeInfo._objectId = arrayElemTypeNameInfo._objectId;
actualTypeInfo._assemId = arrayElemTypeNameInfo._assemId;
actualTypeInfo._isArrayItem = true;
}
else
{
actualTypeInfo = arrayElemTypeNameInfo;
actualTypeInfo._isArrayItem = true;
}
if (!WriteKnownValueClass(arrayElemTypeNameInfo, actualTypeInfo, data))
{
object obj = data;
bool assignUniqueIdForValueTypes = false;
if (ReferenceEquals(arrayElemTypeNameInfo._type, Converter.s_typeofObject))
{
assignUniqueIdForValueTypes = true;
}
long arrayId = Schedule(obj, assignUniqueIdForValueTypes, actualTypeInfo._type);
arrayElemTypeNameInfo._objectId = arrayId;
actualTypeInfo._objectId = arrayId;
if (arrayId < 1)
{
WriteObjectInfo newObjectInfo = WriteObjectInfo.Serialize(obj, _surrogates, _context, _serObjectInfoInit, _formatterConverter, this, _binder);
newObjectInfo._objectId = arrayId;
newObjectInfo._assemId = !ReferenceEquals(arrayElemTypeNameInfo._type, Converter.s_typeofObject) && Nullable.GetUnderlyingType(arrayElemTypeNameInfo._type) == null ?
actualTypeInfo._assemId :
GetAssemblyId(newObjectInfo);
NameInfo typeNameInfo = TypeToNameInfo(newObjectInfo);
typeNameInfo._objectId = arrayId;
newObjectInfo._objectId = arrayId;
Write(newObjectInfo, actualTypeInfo, typeNameInfo);
newObjectInfo.ObjectEnd();
}
else
{
_serWriter.WriteItemObjectRef(arrayElemTypeNameInfo, (int)arrayId);
}
}
if (arrayElemTypeNameInfo._transmitTypeOnMember)
{
PutNameInfo(actualTypeInfo);
}
}
// Iterates over a Rectangle array, for each element of the array invokes WriteArrayMember
private void WriteRectangle(WriteObjectInfo objectInfo, int rank, int[] maxA, Array array, NameInfo arrayElemNameTypeInfo, int[] lowerBoundA)
{
int[] currentA = new int[rank];
int[] indexMap = null;
bool isLowerBound = false;
if (lowerBoundA != null)
{
for (int i = 0; i < rank; i++)
{
if (lowerBoundA[i] != 0)
{
isLowerBound = true;
}
}
}
if (isLowerBound)
{
indexMap = new int[rank];
}
bool isLoop = true;
while (isLoop)
{
isLoop = false;
if (isLowerBound)
{
for (int i = 0; i < rank; i++)
{
indexMap[i] = currentA[i] + lowerBoundA[i];
}
WriteArrayMember(objectInfo, arrayElemNameTypeInfo, array.GetValue(indexMap));
}
else
{
WriteArrayMember(objectInfo, arrayElemNameTypeInfo, array.GetValue(currentA));
}
for (int irank = rank - 1; irank > -1; irank--)
{
// Find the current or lower dimension which can be incremented.
if (currentA[irank] < maxA[irank] - 1)
{
// The current dimension is at maximum. Increase the next lower dimension by 1
currentA[irank]++;
if (irank < rank - 1)
{
// The current dimension and higher dimensions are zeroed.
for (int i = irank + 1; i < rank; i++)
{
currentA[i] = 0;
}
}
isLoop = true;
break;
}
}
}
}
// This gives back the next object to be serialized. Objects
// are returned in a FIFO order based on how they were passed
// to Schedule. The id of the object is put into the objID parameter
// and the Object itself is returned from the function.
private object GetNext(out long objID)
{
bool isNew;
//The Queue is empty here. We'll throw if we try to dequeue the empty queue.
if (_objectQueue.Count == 0)
{
objID = 0;
return null;
}
object obj = _objectQueue.Dequeue();
// A WriteObjectInfo is queued if this object was a member of another object
object realObj = obj is WriteObjectInfo ? ((WriteObjectInfo)obj)._obj : obj;
objID = _idGenerator.HasId(realObj, out isNew);
if (isNew)
{
throw new SerializationException(SR.Format(SR.Serialization_ObjNoID, realObj));
}
return obj;
}
// If the type is a value type, we dont attempt to generate a unique id, unless its a boxed entity
// (in which case, there might be 2 references to the same boxed obj. in a graph.)
// "assignUniqueIdToValueType" is true, if the field type holding reference to "obj" is Object.
private long InternalGetId(object obj, bool assignUniqueIdToValueType, Type type, out bool isNew)
{
if (obj == _previousObj)
{
// good for benchmarks
isNew = false;
return _previousId;
}
_idGenerator._currentCount = _currentId;
if (type != null && type.IsValueType)
{
if (!assignUniqueIdToValueType)
{
isNew = false;
return -1 * _currentId++;
}
}
_currentId++;
long retId = _idGenerator.GetId(obj, out isNew);
_previousObj = obj;
_previousId = retId;
return retId;
}
// Schedules an object for later serialization if it hasn't already been scheduled.
// We get an ID for obj and put it on the queue for later serialization
// if this is a new object id.
private long Schedule(object obj, bool assignUniqueIdToValueType, Type type) =>
Schedule(obj, assignUniqueIdToValueType, type, null);
private long Schedule(object obj, bool assignUniqueIdToValueType, Type type, WriteObjectInfo objectInfo)
{
long id = 0;
if (obj != null)
{
bool isNew;
id = InternalGetId(obj, assignUniqueIdToValueType, type, out isNew);
if (isNew && id > 0)
{
_objectQueue.Enqueue(objectInfo ?? obj);
}
}
return id;
}
// Determines if a type is a primitive type, if it is it is written
private bool WriteKnownValueClass(NameInfo memberNameInfo, NameInfo typeNameInfo, object data)
{
if (ReferenceEquals(typeNameInfo._type, Converter.s_typeofString))
{
WriteString(memberNameInfo, typeNameInfo, data);
}
else
{
if (typeNameInfo._primitiveTypeEnum == InternalPrimitiveTypeE.Invalid)
{
return false;
}
else
{
if (typeNameInfo._isArray) // null if an array
{
_serWriter.WriteItem(memberNameInfo, typeNameInfo, data);
}
else
{
_serWriter.WriteMember(memberNameInfo, typeNameInfo, data);
}
}
}
return true;
}
// Writes an object reference to the stream.
private void WriteObjectRef(NameInfo nameInfo, long objectId) =>
_serWriter.WriteMemberObjectRef(nameInfo, (int)objectId);
// Writes a string into the XML stream
private void WriteString(NameInfo memberNameInfo, NameInfo typeNameInfo, object stringObject)
{
bool isFirstTime = true;
long stringId = -1;
if (!CheckTypeFormat(_formatterEnums._typeFormat, FormatterTypeStyle.XsdString))
{
stringId = InternalGetId(stringObject, false, null, out isFirstTime);
}
typeNameInfo._objectId = stringId;
if ((isFirstTime) || (stringId < 0))
{
_serWriter.WriteMemberString(memberNameInfo, typeNameInfo, (string)stringObject);
}
else
{
WriteObjectRef(memberNameInfo, stringId);
}
}
// Writes a null member into the stream
private bool CheckForNull(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo, object data)
{
bool isNull = data == null;
// Optimization, Null members are only written for Binary
if ((isNull) && (((_formatterEnums._serializerTypeEnum == InternalSerializerTypeE.Binary)) ||
memberNameInfo._isArrayItem ||
memberNameInfo._transmitTypeOnObject ||
memberNameInfo._transmitTypeOnMember ||
objectInfo._isSi ||
(CheckTypeFormat(_formatterEnums._typeFormat, FormatterTypeStyle.TypesAlways))))
{
if (typeNameInfo._isArrayItem)
{
if (typeNameInfo._arrayEnum == InternalArrayTypeE.Single)
{
_serWriter.WriteDelayedNullItem();
}
else
{
_serWriter.WriteNullItem(memberNameInfo, typeNameInfo);
}
}
else
{
_serWriter.WriteNullMember(memberNameInfo, typeNameInfo);
}
}
return isNull;
}
// Writes the SerializedStreamHeader
private void WriteSerializedStreamHeader(long topId, long headerId) =>
_serWriter.WriteSerializationHeader((int)topId, (int)headerId, 1, 0);
// Transforms a type to the serialized string form. URT Primitive types are converted to XMLData Types
private NameInfo TypeToNameInfo(Type type, WriteObjectInfo objectInfo, InternalPrimitiveTypeE code, NameInfo nameInfo)
{
if (nameInfo == null)
{
nameInfo = GetNameInfo();
}
else
{
nameInfo.Init();
}
if (code == InternalPrimitiveTypeE.Invalid)
{
if (objectInfo != null)
{
nameInfo.NIname = objectInfo.GetTypeFullName();
nameInfo._assemId = objectInfo._assemId;
}
}
nameInfo._primitiveTypeEnum = code;
nameInfo._type = type;
return nameInfo;
}
private NameInfo TypeToNameInfo(Type type) =>
TypeToNameInfo(type, null, ToCode(type), null);
private NameInfo TypeToNameInfo(WriteObjectInfo objectInfo) =>
TypeToNameInfo(objectInfo._objectType, objectInfo, ToCode(objectInfo._objectType), null);
private NameInfo TypeToNameInfo(WriteObjectInfo objectInfo, NameInfo nameInfo) =>
TypeToNameInfo(objectInfo._objectType, objectInfo, ToCode(objectInfo._objectType), nameInfo);
private void TypeToNameInfo(Type type, NameInfo nameInfo) =>
TypeToNameInfo(type, null, ToCode(type), nameInfo);
private NameInfo MemberToNameInfo(string name)
{
NameInfo memberNameInfo = GetNameInfo();
memberNameInfo.NIname = name;
return memberNameInfo;
}
internal InternalPrimitiveTypeE ToCode(Type type)
{
if (ReferenceEquals(_previousType, type))
{
return _previousCode;
}
else
{
InternalPrimitiveTypeE code = Converter.ToCode(type);
if (code != InternalPrimitiveTypeE.Invalid)
{
_previousType = type;
_previousCode = code;
}
return code;
}
}
private Dictionary<string, long> _assemblyToIdTable = null;
private long GetAssemblyId(WriteObjectInfo objectInfo)
{
//use objectInfo to get assembly string with new criteria
if (_assemblyToIdTable == null)
{
_assemblyToIdTable = new Dictionary<string, long>();
}
long assemId = 0;
string assemblyString = objectInfo.GetAssemblyString();
string serializedAssemblyString = assemblyString;
if (assemblyString.Length == 0)
{
assemId = 0;
}
else if (assemblyString.Equals(Converter.s_urtAssemblyString) || assemblyString.Equals(Converter.s_urtAlternativeAssemblyString))
{
// Urt type is an assemId of 0. No assemblyString needs
// to be sent
assemId = 0;
}
else
{
// Assembly needs to be sent
// Need to prefix assembly string to separate the string names from the
// assemblyName string names. That is a string can have the same value
// as an assemblyNameString, but it is serialized differently
bool isNew = false;
if (_assemblyToIdTable.TryGetValue(assemblyString, out assemId))
{
isNew = false;
}
else
{
assemId = InternalGetId("___AssemblyString___" + assemblyString, false, null, out isNew);
_assemblyToIdTable[assemblyString] = assemId;
}
_serWriter.WriteAssembly(objectInfo._objectType, serializedAssemblyString, (int)assemId, isNew);
}
return assemId;
}
private Type GetType(object obj) => obj.GetType();
private SerStack _niPool = new SerStack("NameInfo Pool");
private NameInfo GetNameInfo()
{
NameInfo nameInfo = null;
if (!_niPool.IsEmpty())
{
nameInfo = (NameInfo)_niPool.Pop();
nameInfo.Init();
}
else
{
nameInfo = new NameInfo();
}
return nameInfo;
}
private bool CheckTypeFormat(FormatterTypeStyle test, FormatterTypeStyle want) => (test & want) == want;
private void PutNameInfo(NameInfo nameInfo) => _niPool.Push(nameInfo);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
namespace System.ServiceModel.Channels
{
// code that pools items and closes/aborts them as necessary.
// shared by IConnection and IChannel users
public abstract class CommunicationPool<TKey, TItem>
where TKey : class
where TItem : class
{
private Dictionary<TKey, EndpointConnectionPool> _endpointPools;
private int _maxCount;
private int _openCount;
// need to make sure we prune over a certain number of endpoint pools
private int _pruneAccrual;
private const int pruneThreshold = 30;
protected CommunicationPool(int maxCount)
{
_maxCount = maxCount;
_endpointPools = new Dictionary<TKey, EndpointConnectionPool>();
_openCount = 1;
}
public int MaxIdleConnectionPoolCount
{
get { return _maxCount; }
}
protected object ThisLock
{
get { return this; }
}
protected abstract void AbortItem(TItem item);
protected abstract void CloseItem(TItem item, TimeSpan timeout);
protected abstract void CloseItemAsync(TItem item, TimeSpan timeout);
protected abstract TKey GetPoolKey(EndpointAddress address, Uri via);
protected virtual EndpointConnectionPool CreateEndpointConnectionPool(TKey key)
{
return new EndpointConnectionPool(this, key);
}
public bool Close(TimeSpan timeout)
{
lock (ThisLock)
{
if (_openCount <= 0)
{
return true;
}
_openCount--;
if (_openCount == 0)
{
this.OnClose(timeout);
return true;
}
return false;
}
}
private List<TItem> PruneIfNecessary()
{
List<TItem> itemsToClose = null;
_pruneAccrual++;
if (_pruneAccrual > pruneThreshold)
{
_pruneAccrual = 0;
itemsToClose = new List<TItem>();
// first prune the connection pool contents
foreach (EndpointConnectionPool pool in _endpointPools.Values)
{
pool.Prune(itemsToClose);
}
// figure out which connection pools are now empty
List<TKey> endpointKeysToRemove = null;
foreach (KeyValuePair<TKey, EndpointConnectionPool> poolEntry in _endpointPools)
{
if (poolEntry.Value.CloseIfEmpty())
{
if (endpointKeysToRemove == null)
{
endpointKeysToRemove = new List<TKey>();
}
endpointKeysToRemove.Add(poolEntry.Key);
}
}
// and then prune the connection pools themselves
if (endpointKeysToRemove != null)
{
for (int i = 0; i < endpointKeysToRemove.Count; i++)
{
_endpointPools.Remove(endpointKeysToRemove[i]);
}
}
}
return itemsToClose;
}
private EndpointConnectionPool GetEndpointPool(TKey key, TimeSpan timeout)
{
EndpointConnectionPool result = null;
List<TItem> itemsToClose = null;
lock (ThisLock)
{
if (!_endpointPools.TryGetValue(key, out result))
{
itemsToClose = PruneIfNecessary();
result = CreateEndpointConnectionPool(key);
_endpointPools.Add(key, result);
}
}
Contract.Assert(result != null, "EndpointPool must be non-null at this point");
if (itemsToClose != null && itemsToClose.Count > 0)
{
// allocate half the remaining timeout for our graceful shutdowns
TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(timeout, 2));
for (int i = 0; i < itemsToClose.Count; i++)
{
result.CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime());
}
}
return result;
}
public bool TryOpen()
{
lock (ThisLock)
{
if (_openCount <= 0)
{
// can't reopen connection pools since the registry purges them on close
return false;
}
else
{
_openCount++;
return true;
}
}
}
protected virtual void OnClosed()
{
}
private void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
foreach (EndpointConnectionPool pool in _endpointPools.Values)
{
try
{
pool.Close(timeoutHelper.RemainingTime());
}
catch (CommunicationException)
{
}
catch (TimeoutException exception)
{
if (WcfEventSource.Instance.CloseTimeoutIsEnabled())
{
WcfEventSource.Instance.CloseTimeout(exception.Message);
}
}
}
_endpointPools.Clear();
}
public void AddConnection(TKey key, TItem connection, TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime());
endpointPool.AddConnection(connection, timeoutHelper.RemainingTime());
}
public TItem TakeConnection(EndpointAddress address, Uri via, TimeSpan timeout, out TKey key)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
key = this.GetPoolKey(address, via);
EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime());
return endpointPool.TakeConnection(timeoutHelper.RemainingTime());
}
public void ReturnConnection(TKey key, TItem connection, bool connectionIsStillGood, TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
EndpointConnectionPool endpointPool = GetEndpointPool(key, timeoutHelper.RemainingTime());
endpointPool.ReturnConnection(connection, connectionIsStillGood, timeoutHelper.RemainingTime());
}
// base class for our collection of Idle connections
protected abstract class IdleConnectionPool
{
public abstract int Count { get; }
public abstract bool Add(TItem item);
public abstract bool Return(TItem item);
public abstract TItem Take(out bool closeItem);
}
protected class EndpointConnectionPool
{
private TKey _key;
private List<TItem> _busyConnections;
private bool _closed;
private IdleConnectionPool _idleConnections;
private CommunicationPool<TKey, TItem> _parent;
public EndpointConnectionPool(CommunicationPool<TKey, TItem> parent, TKey key)
{
_key = key;
_parent = parent;
_busyConnections = new List<TItem>();
}
protected TKey Key
{
get { return _key; }
}
private IdleConnectionPool IdleConnections
{
get
{
if (_idleConnections == null)
{
_idleConnections = GetIdleConnectionPool();
}
return _idleConnections;
}
}
protected CommunicationPool<TKey, TItem> Parent
{
get { return _parent; }
}
protected object ThisLock
{
get { return this; }
}
// close down the pool if empty
public bool CloseIfEmpty()
{
lock (ThisLock)
{
if (!_closed)
{
if (_busyConnections.Count > 0)
{
return false;
}
if (_idleConnections != null && _idleConnections.Count > 0)
{
return false;
}
_closed = true;
}
}
return true;
}
protected virtual void AbortItem(TItem item)
{
_parent.AbortItem(item);
}
protected virtual void CloseItem(TItem item, TimeSpan timeout)
{
_parent.CloseItem(item, timeout);
}
protected virtual void CloseItemAsync(TItem item, TimeSpan timeout)
{
_parent.CloseItemAsync(item, timeout);
}
public void Abort()
{
if (_closed)
{
return;
}
List<TItem> idleItemsToClose = null;
lock (ThisLock)
{
if (_closed)
return;
_closed = true;
idleItemsToClose = SnapshotIdleConnections();
}
AbortConnections(idleItemsToClose);
}
public void Close(TimeSpan timeout)
{
List<TItem> itemsToClose = null;
lock (ThisLock)
{
if (_closed)
return;
_closed = true;
itemsToClose = SnapshotIdleConnections();
}
try
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
for (int i = 0; i < itemsToClose.Count; i++)
{
this.CloseItem(itemsToClose[i], timeoutHelper.RemainingTime());
}
itemsToClose.Clear();
}
finally
{
AbortConnections(itemsToClose);
}
}
private void AbortConnections(List<TItem> idleItemsToClose)
{
for (int i = 0; i < idleItemsToClose.Count; i++)
{
this.AbortItem(idleItemsToClose[i]);
}
for (int i = 0; i < _busyConnections.Count; i++)
{
this.AbortItem(_busyConnections[i]);
}
_busyConnections.Clear();
}
// must call under lock (ThisLock) since we are calling IdleConnections.Take()
private List<TItem> SnapshotIdleConnections()
{
List<TItem> itemsToClose = new List<TItem>();
bool dummy;
for (; ; )
{
TItem item = IdleConnections.Take(out dummy);
if (item == null)
break;
itemsToClose.Add(item);
}
return itemsToClose;
}
public void AddConnection(TItem connection, TimeSpan timeout)
{
bool closeConnection = false;
lock (ThisLock)
{
if (!_closed)
{
if (!IdleConnections.Add(connection))
{
closeConnection = true;
}
}
else
{
closeConnection = true;
}
}
if (closeConnection)
{
CloseIdleConnection(connection, timeout);
}
}
protected virtual IdleConnectionPool GetIdleConnectionPool()
{
return new PoolIdleConnectionPool(_parent.MaxIdleConnectionPoolCount);
}
public virtual void Prune(List<TItem> itemsToClose)
{
}
public TItem TakeConnection(TimeSpan timeout)
{
TItem item = null;
List<TItem> itemsToClose = null;
lock (ThisLock)
{
if (_closed)
return null;
bool closeItem;
while (true)
{
item = IdleConnections.Take(out closeItem);
if (item == null)
{
break;
}
if (!closeItem)
{
_busyConnections.Add(item);
break;
}
if (itemsToClose == null)
{
itemsToClose = new List<TItem>();
}
itemsToClose.Add(item);
}
}
// cleanup any stale items accrued from IdleConnections
if (itemsToClose != null)
{
// and only allocate half the timeout passed in for our graceful shutdowns
TimeoutHelper timeoutHelper = new TimeoutHelper(TimeoutHelper.Divide(timeout, 2));
for (int i = 0; i < itemsToClose.Count; i++)
{
CloseIdleConnection(itemsToClose[i], timeoutHelper.RemainingTime());
}
}
if (WcfEventSource.Instance.ConnectionPoolMissIsEnabled())
{
if (item == null && _busyConnections != null)
{
WcfEventSource.Instance.ConnectionPoolMiss(_key != null ? _key.ToString() : string.Empty, _busyConnections.Count);
}
}
return item;
}
public void ReturnConnection(TItem connection, bool connectionIsStillGood, TimeSpan timeout)
{
bool closeConnection = false;
bool abortConnection = false;
lock (ThisLock)
{
if (!_closed)
{
if (_busyConnections.Remove(connection) && connectionIsStillGood)
{
if (!IdleConnections.Return(connection))
{
closeConnection = true;
}
}
else
{
abortConnection = true;
}
}
else
{
abortConnection = true;
}
}
if (closeConnection)
{
CloseIdleConnection(connection, timeout);
}
else if (abortConnection)
{
this.AbortItem(connection);
OnConnectionAborted();
}
}
public void CloseIdleConnection(TItem connection, TimeSpan timeout)
{
bool throwing = true;
try
{
this.CloseItemAsync(connection, timeout);
throwing = false;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
finally
{
if (throwing)
{
this.AbortItem(connection);
}
}
}
protected virtual void OnConnectionAborted()
{
}
protected class PoolIdleConnectionPool
: IdleConnectionPool
{
private Pool<TItem> _idleConnections;
private int _maxCount;
public PoolIdleConnectionPool(int maxCount)
{
_idleConnections = new Pool<TItem>(maxCount);
_maxCount = maxCount;
}
public override int Count
{
get { return _idleConnections.Count; }
}
public override bool Add(TItem connection)
{
return ReturnToPool(connection);
}
public override bool Return(TItem connection)
{
return ReturnToPool(connection);
}
private bool ReturnToPool(TItem connection)
{
bool result = _idleConnections.Return(connection);
if (!result)
{
if (WcfEventSource.Instance.MaxOutboundConnectionsPerEndpointExceededIsEnabled())
{
WcfEventSource.Instance.MaxOutboundConnectionsPerEndpointExceeded(string.Format(SRServiceModel.TraceCodeConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached, _maxCount));
}
}
else if (WcfEventSource.Instance.OutboundConnectionsPerEndpointRatioIsEnabled())
{
WcfEventSource.Instance.OutboundConnectionsPerEndpointRatio(_idleConnections.Count, _maxCount);
}
return result;
}
public override TItem Take(out bool closeItem)
{
closeItem = false;
TItem ret = _idleConnections.Take();
if (WcfEventSource.Instance.OutboundConnectionsPerEndpointRatioIsEnabled())
{
WcfEventSource.Instance.OutboundConnectionsPerEndpointRatio(_idleConnections.Count, _maxCount);
}
return ret;
}
}
}
}
// all our connection pools support Idling out of connections and lease timeout
// (though Named Pipes doesn't leverage the lease timeout)
public abstract class ConnectionPool : IdlingCommunicationPool<string, IConnection>
{
private int _connectionBufferSize;
private TimeSpan _maxOutputDelay;
private string _name;
protected ConnectionPool(IConnectionOrientedTransportChannelFactorySettings settings, TimeSpan leaseTimeout)
: base(settings.MaxOutboundConnectionsPerEndpoint, settings.IdleTimeout, leaseTimeout)
{
_connectionBufferSize = settings.ConnectionBufferSize;
_maxOutputDelay = settings.MaxOutputDelay;
_name = settings.ConnectionPoolGroupName;
}
public string Name
{
get { return _name; }
}
protected override void AbortItem(IConnection item)
{
item.Abort();
}
protected override void CloseItem(IConnection item, TimeSpan timeout)
{
item.Close(timeout, false);
}
protected override void CloseItemAsync(IConnection item, TimeSpan timeout)
{
item.Close(timeout, true);
}
public virtual bool IsCompatible(IConnectionOrientedTransportChannelFactorySettings settings)
{
return (
(_name == settings.ConnectionPoolGroupName) &&
(_connectionBufferSize == settings.ConnectionBufferSize) &&
(this.MaxIdleConnectionPoolCount == settings.MaxOutboundConnectionsPerEndpoint) &&
(this.IdleTimeout == settings.IdleTimeout) &&
(_maxOutputDelay == settings.MaxOutputDelay)
);
}
}
}
| |
using UnityEngine;
using System.Collections;
using FiniteStateMachine.Unity;
namespace ModelLoaderFileExplorer {
[RequireComponent (typeof(ViewModelInputsHelper))]
public class ViewModelState : MonoBehaviour {
public UIButton submitButton;
public Camera modelCamera;
public GameObject dragAreaGo;
public float zoomSpeed;
public float rotateSpeed;
public float moveSpeed;
public string modelName;
public float viewSizeMax;
public float viewSizeMin;
private ViewModelInputsHelper _helper;
private float _originFOV;
private Vector2 _previousMousePosition;
private ModelData _modelData;
private Transform _modelTrans;
private bool _preserveModelData;
public ModelData modelData {
get {return _modelData;}
set {
_preserveModelData = true;
_modelData = value;
_helper = GetComponent<ViewModelInputsHelper>();
_helper.UpdateInputsData(value);
}
}
void OnEnable () {
_originFOV = modelCamera.fieldOfView;
GameObject modelGo = (GameObject) GameObject.Find(modelName);
if (modelGo == null) {
Debug.LogError("Cannot find GameObject named after '" + modelName + "'");
}
else {
_modelTrans = modelGo.transform;
}
if (_modelTrans.renderer != null) {
float width = _modelTrans.renderer.bounds.size.x;
float height = _modelTrans.renderer.bounds.size.y;
Debug.Log(width);
while (width > viewSizeMax || height > viewSizeMax) {
Vector3 scale = _modelTrans.localScale;
scale *= 0.5f;
_modelTrans.localScale = scale;
width *= 0.5f;
height *= 0.5f;
}
while (width < viewSizeMin || height < viewSizeMin) {
Vector3 scale = _modelTrans.localScale;
scale *= 2;
_modelTrans.localScale = scale;
width *= 2f;
height *= 2f;
}
}
if (!_preserveModelData) {
_modelData = new ModelData();
_helper = GetComponent<ViewModelInputsHelper>();
_helper.UpdateInputsData(_modelData);
}
}
void Update () {
if (Check()) {
// UpdateFieldOfView();
UpdateRotation();
// UpdatePosition();
}
}
void OnDisable () {
if (modelCamera != null) {
modelCamera.fieldOfView = _originFOV;
}
submitButton.onClick.Clear();
_preserveModelData = false;
// if (_modelTrans != null) {
// GameObject.Destroy(_modelTrans.gameObject);
// }
}
private void UpdateFieldOfView () {
modelCamera.fieldOfView += Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
}
private void UpdateRotation () {
if (Input.GetMouseButtonDown(0)) {
_previousMousePosition = GetMousePoisition();
}
else if (Input.GetMouseButton(0)) {
Vector2 mousePosition = GetMousePoisition();
Vector2 delta = mousePosition - _previousMousePosition;
Vector3 angles = _modelTrans.eulerAngles;
angles.x += delta.y * rotateSpeed;
angles.y += delta.x * rotateSpeed;
_modelTrans.eulerAngles = angles;
_previousMousePosition = mousePosition;
}
}
private void UpdatePosition () {
if (Input.GetMouseButtonDown(1)) {
_previousMousePosition = GetMousePoisition();
}
else if (Input.GetMouseButton(1)) {
Vector2 mousePosition = GetMousePoisition();
Vector2 delta = mousePosition - _previousMousePosition;
Vector3 position = _modelTrans.position;
position.x += delta.x * moveSpeed;
position.y += delta.y * moveSpeed;
_modelTrans.position = position;
_previousMousePosition = mousePosition;
}
}
private Vector2 GetMousePoisition () {
Vector3 mousePositionInScreenUnit = Input.mousePosition;
mousePositionInScreenUnit.z = Mathf.Abs(modelCamera.transform.position.z);
return modelCamera.ScreenToWorldPoint(mousePositionInScreenUnit);
}
private bool Check () {
return UICamera.hoveredObject == dragAreaGo;
}
public void OnSubmitButtonClicked () {
_helper.SubmitFields();
if (_modelData.username == null || _modelData.username.Equals("")) { // New server, upload model
_modelData.modelPath = UploadModelController.previousLoadedModelPath;
}
//_modelData.Serialize();
_modelData.MakeCloud();
}
public void OnAddToMineButtonClicked () {
_modelData.AddToUser();
}
public void OnToggle () {
if (UIToggle.current.name.Contains("Input - Is Private")) {
_modelData.isPrivate = UIToggle.current.value;
}
}
public void OnInputFieldSubmit () {
if (!enabled) return;
UIInput input = UIInput.current;
if (input.value == null || input.value.Equals("") || _modelData == null) return;
if (input.name.Contains("Input - Model")) {
_modelData.name = input.value;
}
else if (input.name.Contains("Input - Unit Size")) {
_modelData.unitSize = float.Parse(input.value);
}
else if (input.name.Contains("Input - CPU Core")) {
_modelData.cpuCoresCount = int.Parse(input.value);
}
else if (input.name.Contains("Input - CPU Hz")) {
_modelData.cpuHz = float.Parse(input.value);
}
else if (input.name.Contains("Input - HDD Bays")) {
_modelData.hddBaysCount = int.Parse(input.value);
}
else if (input.name.Contains("Input - Memory Speed")) {
_modelData.memorySpeed = int.Parse(input.value);
}
else if (input.name.Contains("Input - Memory Capacity Count")) {
string parentName = input.transform.parent.name;
bool is0 = true;
int i=0;
for (; i<100; i++) {
if (parentName.Contains(i.ToString())) {
is0 = false;
break;
}
}
if (is0) {
i = 0;
}
if (i >= _modelData.memoryCapacity.Count) {
_modelData.memoryCapacity.Add(new PairData(0, 0));
}
PairData pairData = _modelData.memoryCapacity[i];
pairData.count = int.Parse(input.value);
_modelData.memoryCapacity[i] = pairData;
}
else if (input.name.Contains("Input - Memory Capacity Data")) {
string parentName = input.transform.parent.name;
bool is0 = true;
int i=0;
for (; i<100; i++) {
if (parentName.Contains(i.ToString())) {
is0 = false;
break;
}
}
if (is0) {
i = 0;
}
if (i >= _modelData.memoryCapacity.Count) {
_modelData.memoryCapacity.Add(new PairData(0, 0));
}
PairData pairData = _modelData.memoryCapacity[i];
pairData.data = int.Parse(input.value);
_modelData.memoryCapacity[i] = pairData;
}
else if (input.name.Contains("Input - RAID")) {
_modelData.raid = input.value;
}
else if (input.name.Contains("Input - HDD Count")) {
string parentName = input.transform.parent.name;
bool is0 = true;
int i=0;
for (; i<100; i++) {
if (parentName.Contains(i.ToString())) {
is0 = false;
break;
}
}
if (is0) {
i = 0;
}
if (i >= _modelData.hdd.Count) {
_modelData.hdd.Add(new PairData(0, 0));
}
PairData pairData = _modelData.hdd[i];
pairData.count = int.Parse(input.value);
_modelData.hdd[i] = pairData;
}
else if (input.name.Contains("Input - HDD Data")) {
string parentName = input.transform.parent.name;
bool is0 = true;
int i=0;
for (; i<100; i++) {
if (parentName.Contains(i.ToString())) {
is0 = false;
break;
}
}
if (is0) {
i = 0;
}
if (i >= _modelData.hdd.Count) {
_modelData.hdd.Add(new PairData(0, 0));
}
PairData pairData = _modelData.hdd[i];
pairData.data = int.Parse(input.value);
_modelData.hdd[i] = pairData;
}
else if (input.name.Contains("Input - Network Count")) {
string parentName = input.transform.parent.name;
bool is0 = true;
int i=0;
for (; i<100; i++) {
if (parentName.Contains(i.ToString())) {
is0 = false;
break;
}
}
if (is0) {
i = 0;
}
if (i >= _modelData.network.Count) {
_modelData.network.Add(new PairData(0, 0));
}
PairData pairData = _modelData.network[i];
pairData.count = int.Parse(input.value);
_modelData.network[i] = pairData;
}
else if (input.name.Contains("Input - Network Data")) {
string parentName = input.transform.parent.name;
bool is0 = true;
int i=0;
for (; i<100; i++) {
if (parentName.Contains(i.ToString())) {
is0 = false;
break;
}
}
if (is0) {
i = 0;
}
if (i >= _modelData.network.Count) {
_modelData.network.Add(new PairData(0, 0));
}
PairData pairData = _modelData.network[i];
pairData.data = int.Parse(input.value);
_modelData.network[i] = pairData;
}
else if (input.name.Contains("Input - GPU")) {
string inputName = input.name;
bool is0 = true;
int i=0;
for (; i<100; i++) {
if (inputName.Contains(i.ToString())) {
is0 = false;
break;
}
}
if (is0) {
i = 0;
}
if (i >= _modelData.gpu.Count) {
_modelData.gpu.Add("");
}
_modelData.gpu[i] = input.value;
}
Debug.Log(_modelData.ToString());
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
using System.Text.RegularExpressions;
using Scriban.Runtime;
namespace Scriban.Functions
{
/// <summary>
/// Functions exposed through `regex` builtin object.
/// </summary>
/// <seealso cref="Scriban.Runtime.ScriptObject" />
public class RegexFunctions : ScriptObject
{
/// <summary>
/// Escapes a minimal set of characters (`\`, `*`, `+`, `?`, `|`, `{`, `[`, `(`,`)`, `^`, `$`,`.`, `#`, and white space)
/// by replacing them with their escape codes.
/// This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.
/// </summary>
/// <param name="pattern">The input string that contains the text to convert.</param>
/// <returns>A string of characters with metacharacters converted to their escaped form.</returns>
/// <remarks>
/// ```scriban-html
/// {{ "(abc.*)" | regex.escape }}
/// ```
/// ```html
/// \(abc\.\*\)
/// ```
/// </remarks>
public static string Escape(string pattern)
{
return Regex.Escape(pattern);
}
/// <summary>
/// Searches an input string for a substring that matches a regular expression pattern and returns an array with the match occurences.
/// </summary>
/// <param name="context">The template context (to fetch the timeout configuration)</param>
/// <param name="text">The string to search for a match.</param>
/// <param name="pattern">The regular expression pattern to match.</param>
/// <param name="options">A string with regex options, that can contain the following option characters (default is `null`):
/// - `i`: Specifies case-insensitive matching.
/// - `m`: Multiline mode. Changes the meaning of `^` and `$` so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.
/// - `s`: Specifies single-line mode. Changes the meaning of the dot `.` so it matches every character (instead of every character except `\n`).
/// - `x`: Eliminates unescaped white space from the pattern and enables comments marked with `#`.
/// </param>
/// <returns>An array that contains all the match groups. The first group contains the entire match. The other elements contain regex matched groups `(..)`. An empty array returned means no match.</returns>
/// <remarks>
/// ```scriban-html
/// {{ "this is a text123" | regex.match `(\w+) a ([a-z]+\d+)` }}
/// ```
/// ```html
/// ["is a text123", "is", "text123"]
/// ```
/// Notice that the first element returned in the array is the entire regex match, followed by the regex group matches.
/// </remarks>
public static ScriptArray Match(TemplateContext context, string text, string pattern, string options = null)
{
var match = Regex.Match(text, pattern, GetOptions(options), context.RegexTimeOut);
var matchObject = new ScriptArray();
if (match.Success)
{
foreach (Group group in match.Groups)
{
matchObject.Add(group.Value);
}
}
// otherwise return an empty array
return matchObject;
}
/// <summary>
/// Searches an input string for multiple substrings that matches a regular expression pattern and returns an array with the match occurences.
/// </summary>
/// <param name="context">The template context (to fetch the timeout configuration)</param>
/// <param name="text">The string to search for a match.</param>
/// <param name="pattern">The regular expression pattern to match.</param>
/// <param name="options">A string with regex options, that can contain the following option characters (default is `null`):
/// - `i`: Specifies case-insensitive matching.
/// - `m`: Multiline mode. Changes the meaning of `^` and `$` so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.
/// - `s`: Specifies single-line mode. Changes the meaning of the dot `.` so it matches every character (instead of every character except `\n`).
/// - `x`: Eliminates unescaped white space from the pattern and enables comments marked with `#`.
/// </param>
/// <returns>An array of matches that contains all the match groups. The first group contains the entire match. The other elements contain regex matched groups `(..)`. An empty array returned means no match.</returns>
/// <remarks>
/// ```scriban-html
/// {{ "this is a text123" | regex.matches `(\w+)` }}
/// ```
/// ```html
/// [["this", "this"], ["is", "is"], ["a", "a"], ["text123", "text123"]]
/// ```
/// Notice that the first element returned in the sub array is the entire regex match, followed by the regex group matches.
/// </remarks>
public static ScriptArray Matches(TemplateContext context, string text, string pattern, string options = null)
{
var matches = Regex.Matches(text, pattern, GetOptions(options), context.RegexTimeOut);
var allMatches = new ScriptArray();
foreach (Match match in matches)
{
if (match.Success)
{
var matchObject = new ScriptArray();
for (var i = 0; i < match.Groups.Count; i++)
{
Group @group = match.Groups[i];
matchObject.Add(@group.Value);
}
allMatches.Add(matchObject);
}
}
// otherwise return an empty array
return allMatches;
}
/// <summary>
/// In a specified input string, replaces strings that match a regular expression pattern with a specified replacement string.
/// </summary>
/// <param name="context">The template context (to fetch the timeout configuration)</param>
/// <param name="text">The string to search for a match.</param>
/// <param name="pattern">The regular expression pattern to match.</param>
/// <param name="replace">The replacement string.</param>
/// <param name="options">A string with regex options, that can contain the following option characters (default is `null`):
/// - `i`: Specifies case-insensitive matching.
/// - `m`: Multiline mode. Changes the meaning of `^` and `$` so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.
/// - `s`: Specifies single-line mode. Changes the meaning of the dot `.` so it matches every character (instead of every character except `\n`).
/// - `x`: Eliminates unescaped white space from the pattern and enables comments marked with `#`.
/// </param>
/// <returns>A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.</returns>
/// <remarks>
/// ```scriban-html
/// {{ "abbbbcccd" | regex.replace "b+c+" "-Yo-" }}
/// ```
/// ```html
/// a-Yo-d
/// ```
/// </remarks>
public static string Replace(TemplateContext context, string text, string pattern, string replace, string options = null)
{
return Regex.Replace(text, pattern, replace, GetOptions(options), context.RegexTimeOut);
}
/// <summary>
/// Splits an input string into an array of substrings at the positions defined by a regular expression match.
/// </summary>
/// <param name="context">The template context (to fetch the timeout configuration)</param>
/// <param name="text">The string to split.</param>
/// <param name="pattern">The regular expression pattern to match.</param>
/// <param name="options">A string with regex options, that can contain the following option characters (default is `null`):
/// - `i`: Specifies case-insensitive matching.
/// - `m`: Multiline mode. Changes the meaning of `^` and `$` so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.
/// - `s`: Specifies single-line mode. Changes the meaning of the dot `.` so it matches every character (instead of every character except `\n`).
/// - `x`: Eliminates unescaped white space from the pattern and enables comments marked with `#`.
/// </param>
/// <returns>A string array.</returns>
/// <remarks>
/// ```scriban-html
/// {{ "a, b , c, d" | regex.split `\s*,\s*` }}
/// ```
/// ```html
/// ["a", "b", "c", "d"]
/// ```
/// </remarks>
public static ScriptArray Split(TemplateContext context, string text, string pattern, string options = null)
{
return new ScriptArray(Regex.Split(text, pattern, GetOptions(options), context.RegexTimeOut));
}
/// <summary>
/// Converts any escaped characters in the input string.
/// </summary>
/// <param name="pattern">The input string containing the text to convert.</param>
/// <returns>A string of characters with any escaped characters converted to their unescaped form.</returns>
/// <remarks>
/// ```scriban-html
/// {{ "\\(abc\\.\\*\\)" | regex.unescape }}
/// ```
/// ```html
/// (abc.*)
/// ```
/// </remarks>
public static string Unescape(string pattern)
{
return Regex.Unescape(pattern);
}
private static RegexOptions GetOptions(string options)
{
if (options == null)
{
return RegexOptions.None;
}
var regexOptions = RegexOptions.None;
for (int i = 0; i < options.Length; i++)
{
switch (options[i])
{
case 'i':
regexOptions |= RegexOptions.IgnoreCase;
break;
case 'm':
regexOptions |= RegexOptions.Multiline;
break;
case 's':
regexOptions |= RegexOptions.Singleline;
break;
case 'x':
regexOptions |= RegexOptions.IgnorePatternWhitespace;
break;
}
}
return regexOptions;
}
}
}
| |
//
// Copyright (C) 2010 Novell Inc. http://novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Xaml;
using System.Xaml.Schema;
namespace System.Windows.Markup
{
public abstract class ValueSerializer
{
#if !NET_2_1
public static ValueSerializer GetSerializerFor (PropertyDescriptor descriptor)
{
return GetSerializerFor (descriptor, null);
}
#endif
public static ValueSerializer GetSerializerFor (Type type)
{
return GetSerializerFor (type, null);
}
#if !NET_2_1
// untested
public static ValueSerializer GetSerializerFor (PropertyDescriptor descriptor, IValueSerializerContext context)
{
if (descriptor == null)
throw new ArgumentNullException ("descriptor");
if (context != null)
return context.GetValueSerializerFor (descriptor);
var tc = descriptor.Converter;
if (tc != null && tc.GetType () != typeof (TypeConverter))
return new TypeConverterValueSerializer (tc);
return null;
}
#endif
public static ValueSerializer GetSerializerFor (Type type, IValueSerializerContext context)
{
if (type == null)
throw new ArgumentNullException ("type");
if (context != null)
return context.GetValueSerializerFor (type);
// Standard MarkupExtensions are serialized without ValueSerializer.
if (typeof (MarkupExtension).IsAssignableFrom (type) && XamlLanguage.AllTypes.Any (x => x.UnderlyingType == type))
return null;
// DateTime is documented as special.
if (type == typeof (DateTime))
return new DateTimeValueSerializer ();
// String too.
if (type == typeof (string))
return new StringValueSerializer ();
// FIXME: this is hack. The complete condition is fully documented at http://msdn.microsoft.com/en-us/library/ms590363.aspx
if (type.GetCustomAttribute<TypeConverterAttribute> (true) != null) {
var tc = type.GetTypeConverter ();
if (tc != null && tc.GetType () != typeof (TypeConverter))
return new TypeConverterValueSerializer (tc);
}
// Undocumented, but System.Type seems also special. While other MarkupExtension returned types are not handled specially, this method returns a valid instance for System.Type. Note that it doesn't for TypeExtension.
if (type == typeof (Type))
// Since System.Type does not have a valid TypeConverter, I use TypeExtensionConverter (may sound funny considering the above notes!) for this serializer.
return new TypeValueSerializer ();
// Undocumented, but several primitive types get a valid serializer while it does not have TypeConverter.
switch (Type.GetTypeCode (type)) {
case TypeCode.Object:
case TypeCode.DBNull:
break;
default:
return new TypeConverterValueSerializer (type.GetTypeConverter ());
}
// There is still exceptional type! TimeSpan. Why aren't they documented?
if (type == typeof (TimeSpan))
return new TypeConverterValueSerializer (type.GetTypeConverter ());
return null;
}
// instance members
public virtual bool CanConvertFromString (string value, IValueSerializerContext context)
{
return false;
}
public virtual bool CanConvertToString (object value, IValueSerializerContext context)
{
return false;
}
public virtual object ConvertFromString (string value, IValueSerializerContext context)
{
throw GetConvertFromException (value);
}
public virtual string ConvertToString (object value, IValueSerializerContext context)
{
throw GetConvertToException (value, typeof (string));
}
protected Exception GetConvertFromException (object value)
{
return new NotSupportedException (String.Format ("Conversion from string '{0}' is not supported", value));
}
protected Exception GetConvertToException (object value, Type destinationType)
{
return new NotSupportedException (String.Format ("Conversion from '{0}' to {1} is not supported", value != null ? value.GetType ().Name : "(null)", destinationType));
}
public virtual IEnumerable<Type> TypeReferences (object value, IValueSerializerContext context)
{
yield break;
}
}
#region Internal implementations.
internal class StringValueSerializer : ValueSerializer
{
public override bool CanConvertFromString (string value, IValueSerializerContext context)
{
return true;
}
public override bool CanConvertToString (object value, IValueSerializerContext context)
{
return true;
}
public override object ConvertFromString (string value, IValueSerializerContext context)
{
return value;
}
public override string ConvertToString (object value, IValueSerializerContext context)
{
return (string) value;
}
public override IEnumerable<Type> TypeReferences (object value, IValueSerializerContext context)
{
throw new NotImplementedException ();
}
}
internal class TypeValueSerializer : ValueSerializer
{
TypeExtensionConverter txc = new TypeExtensionConverter ();
public override bool CanConvertFromString (string value, IValueSerializerContext context)
{
return true;
}
public override bool CanConvertToString (object value, IValueSerializerContext context)
{
return true;
}
public override object ConvertFromString (string value, IValueSerializerContext context)
{
if (context == null)
return base.ConvertFromString (value, context);
var nsr = (IXamlNamespaceResolver) context.GetService (typeof (IXamlNamespaceResolver));
var scp = (IXamlSchemaContextProvider) context.GetService (typeof (IXamlSchemaContextProvider));
return scp.SchemaContext.GetXamlType (XamlTypeName.Parse (value, nsr)).UnderlyingType;
}
public override string ConvertToString (object value, IValueSerializerContext context)
{
return (string) txc.ConvertTo (context, CultureInfo.InvariantCulture, value, typeof (string));
}
public override IEnumerable<Type> TypeReferences (object value, IValueSerializerContext context)
{
throw new NotImplementedException ();
}
}
internal class TypeConverterValueSerializer : ValueSerializer
{
public TypeConverterValueSerializer (TypeConverter typeConverter)
{
c = typeConverter;
}
TypeConverter c;
public override bool CanConvertFromString (string value, IValueSerializerContext context)
{
return c.CanConvertFrom (context, typeof (string));
}
public override bool CanConvertToString (object value, IValueSerializerContext context)
{
return c.CanConvertTo (context, typeof (string));
}
public override object ConvertFromString (string value, IValueSerializerContext context)
{
return c.ConvertFrom (context, CultureInfo.InvariantCulture, value);
}
public override string ConvertToString (object value, IValueSerializerContext context)
{
return value == null ? String.Empty : (string) c.ConvertTo (context, CultureInfo.InvariantCulture, value, typeof (string));
}
public override IEnumerable<Type> TypeReferences (object value, IValueSerializerContext context)
{
throw new NotImplementedException ();
}
}
#endregion
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace ModuleUpdater.Dialogs
{
/// <summary>
/// Summary description for ClassificationDialog.
/// </summary>
public class ClassificationDialog : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.ComboBox structureComboBox;
private System.Windows.Forms.Label structureLabel;
private System.Windows.Forms.Label substructureLabel;
private System.Windows.Forms.ComboBox substructureComboBox;
private System.Windows.Forms.Label celltypeLabel;
private System.Windows.Forms.ComboBox celltypeComboBox;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private DataSet versionDataSet;
private DataRow classificationRow;
private bool addMode;
public ClassificationDialog(bool addMode, ref DataRow classificationRow, ref DataSet versionDataSet)
{
// Required for Windows Form Designer support
InitializeComponent();
EnableVisualStyles.Enable(this);
this.addMode = addMode;
this.classificationRow = classificationRow;
this.versionDataSet = versionDataSet;
this.structureComboBox.DataSource = versionDataSet.Tables["tblStructure"];
this.substructureComboBox.DataSource = versionDataSet.Tables["tblSubstructure"];
this.celltypeComboBox.DataSource = versionDataSet.Tables["tblCellType"];
if (addMode)
{
this.okButton.Text = "Add";
this.Text = "Add New Classification";
this.substructureComboBox.SelectedIndex = 0;
}
else
{
this.okButton.Text = "Update";
this.Text = "Update Classification";
this.structureComboBox.SelectedValue = long.Parse(this.classificationRow["fldStructureID"].ToString());
if (this.classificationRow["fldSubstructureID"].ToString() != "")
this.substructureComboBox.SelectedValue = long.Parse(this.classificationRow["fldSubstructureID"].ToString());
else
this.substructureComboBox.SelectedIndex = 0;
if (classificationRow["fldCellTypeID"].ToString() != "")
this.celltypeComboBox.SelectedValue = long.Parse(this.classificationRow["fldCellTypeID"].ToString());
else
this.celltypeComboBox.SelectedIndex = 0;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cancelButton = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.structureComboBox = new System.Windows.Forms.ComboBox();
this.structureLabel = new System.Windows.Forms.Label();
this.substructureLabel = new System.Windows.Forms.Label();
this.substructureComboBox = new System.Windows.Forms.ComboBox();
this.celltypeLabel = new System.Windows.Forms.Label();
this.celltypeComboBox = new System.Windows.Forms.ComboBox();
this.okButton = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(368, 128);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(72, 24);
this.cancelButton.TabIndex = 0;
this.cancelButton.Text = "Cancel";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.celltypeComboBox);
this.groupBox1.Controls.Add(this.celltypeLabel);
this.groupBox1.Controls.Add(this.substructureComboBox);
this.groupBox1.Controls.Add(this.substructureLabel);
this.groupBox1.Controls.Add(this.structureComboBox);
this.groupBox1.Controls.Add(this.structureLabel);
this.groupBox1.Location = new System.Drawing.Point(8, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(432, 112);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Classification Information";
//
// structureComboBox
//
this.structureComboBox.DisplayMember = "fldStructureName";
this.structureComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.structureComboBox.Location = new System.Drawing.Point(88, 24);
this.structureComboBox.Name = "structureComboBox";
this.structureComboBox.Size = new System.Drawing.Size(328, 21);
this.structureComboBox.TabIndex = 0;
this.structureComboBox.ValueMember = "fldStructureID";
this.structureComboBox.SelectedIndexChanged += new System.EventHandler(this.structureComboBox_SelectedIndexChanged);
//
// structureLabel
//
this.structureLabel.Location = new System.Drawing.Point(16, 24);
this.structureLabel.Name = "structureLabel";
this.structureLabel.Size = new System.Drawing.Size(56, 16);
this.structureLabel.TabIndex = 1;
this.structureLabel.Text = "Structure:";
this.structureLabel.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
//
// substructureLabel
//
this.substructureLabel.Location = new System.Drawing.Point(16, 48);
this.substructureLabel.Name = "substructureLabel";
this.substructureLabel.Size = new System.Drawing.Size(72, 16);
this.substructureLabel.TabIndex = 2;
this.substructureLabel.Text = "Substructure:";
//
// substructureComboBox
//
this.substructureComboBox.DisplayMember = "fldSubstructureName";
this.substructureComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.substructureComboBox.Location = new System.Drawing.Point(88, 48);
this.substructureComboBox.Name = "substructureComboBox";
this.substructureComboBox.Size = new System.Drawing.Size(328, 21);
this.substructureComboBox.TabIndex = 3;
this.substructureComboBox.ValueMember = "fldSubstructureID";
this.substructureComboBox.SelectedIndexChanged += new System.EventHandler(this.substructureComboBox_SelectedIndexChanged);
//
// celltypeLabel
//
this.celltypeLabel.Location = new System.Drawing.Point(16, 72);
this.celltypeLabel.Name = "celltypeLabel";
this.celltypeLabel.Size = new System.Drawing.Size(56, 16);
this.celltypeLabel.TabIndex = 4;
this.celltypeLabel.Text = "Cell Type:";
//
// celltypeComboBox
//
this.celltypeComboBox.DisplayMember = "fldCellTypeName";
this.celltypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.celltypeComboBox.Location = new System.Drawing.Point(88, 72);
this.celltypeComboBox.Name = "celltypeComboBox";
this.celltypeComboBox.Size = new System.Drawing.Size(328, 21);
this.celltypeComboBox.TabIndex = 5;
this.celltypeComboBox.ValueMember = "fldCellTypeID";
this.celltypeComboBox.SelectedIndexChanged += new System.EventHandler(this.celltypeComboBox_SelectedIndexChanged);
//
// okButton
//
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.Location = new System.Drawing.Point(280, 128);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 24);
this.okButton.TabIndex = 2;
this.okButton.Text = "OK";
this.okButton.Click += new System.EventHandler(this.okButton_Click);
//
// ClassificationDialog
//
this.AcceptButton = this.okButton;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(450, 160);
this.Controls.Add(this.okButton);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.cancelButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ClassificationDialog";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "ClassificationDialog";
this.TopMost = true;
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void DoCheck()
{
if (this.addMode)
{
if (this.structureComboBox.SelectedIndex != 0)
this.okButton.Enabled = true;
else
this.okButton.Enabled = false;
}
else
{
bool minimumMet = false;
bool structureOn = false;
bool substructureOn = false;
bool celltypeOn = false;
if (this.structureComboBox.SelectedIndex != 0)
minimumMet = true;
if (((DataRowView)this.structureComboBox.SelectedItem).Row["fldStructureID"].ToString() != this.classificationRow["fldStructureID"].ToString())
structureOn = true;
if (this.classificationRow["fldSubstructureID"].ToString() == "")
{
if (this.substructureComboBox.SelectedIndex != 0)
substructureOn = true;
}
else if (((DataRowView)this.substructureComboBox.SelectedItem).Row["fldSubstructureID"].ToString() != this.classificationRow["fldSubstructureID"].ToString())
substructureOn = true;
if (this.classificationRow["fldCellTypeID"].ToString() == "")
{
if (this.celltypeComboBox.SelectedIndex != 0)
celltypeOn = true;
}
else if (((DataRowView)this.celltypeComboBox.SelectedItem).Row["fldCellTypeID"].ToString() != this.classificationRow["fldCellTypeID"].ToString())
celltypeOn = true;
if (minimumMet && (structureOn || substructureOn || celltypeOn))
this.okButton.Enabled = true;
else
this.okButton.Enabled = false;
}
}
private void structureComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.versionDataSet.Tables["tblSubstructure"].DefaultView.RowFilter = "fldSubstructureStructureID = " + this.structureComboBox.SelectedValue + " OR fldSubstructureID = 0";
this.versionDataSet.Tables["tblCellType"].DefaultView.RowFilter = "fldCellTypeSubstructureID = " + this.substructureComboBox.SelectedValue + " OR fldCellTypeID = 0";
this.substructureComboBox.SelectedIndex = 0;
this.DoCheck();
}
private void substructureComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.versionDataSet.Tables["tblCellType"].DefaultView.RowFilter = "fldCellTypeSubstructureID = " + this.substructureComboBox.SelectedValue + " OR fldCellTypeID = 0";
this.celltypeComboBox.SelectedIndex = 0;
this.DoCheck();
}
private void celltypeComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.DoCheck();
}
private void okButton_Click(object sender, System.EventArgs e)
{
this.classificationRow["fldVersionID"] = this.versionDataSet.Tables["tblVersion"].Rows[0]["fldVersionID"];
this.classificationRow["fldStructureID"] = ((DataRowView)this.structureComboBox.SelectedItem).Row["fldStructureID"];
this.classificationRow["fldStructure"] = ((DataRowView)this.structureComboBox.SelectedItem).Row["fldStructureName"].ToString();
if (this.substructureComboBox.SelectedIndex != 0)
{
this.classificationRow["fldSubstructureID"] = ((DataRowView)this.substructureComboBox.SelectedItem).Row["fldSubstructureID"];
this.classificationRow["fldSubstructure"] = ((DataRowView)this.substructureComboBox.SelectedItem).Row["fldSubstructureName"].ToString();
}
else
this.classificationRow["fldSubstructureID"] = this.classificationRow["fldSubstructure"] = DBNull.Value;
if (this.celltypeComboBox.SelectedIndex != 0)
{
this.classificationRow["fldCellTypeID"] = ((DataRowView)this.celltypeComboBox.SelectedItem).Row["fldCellTypeID"];
this.classificationRow["fldCellType"] = ((DataRowView)this.celltypeComboBox.SelectedItem).Row["fldCellTypeName"].ToString();
}
else
this.classificationRow["fldCellTypeID"] = this.classificationRow["fldCellType"] = DBNull.Value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoMac.Foundation;
using MonoMac.AppKit;
using Substrate.Nbt;
namespace NBTExplorer.Mac
{
public partial class CreateNodeWindowController : MonoMac.AppKit.NSWindowController
{
private string _name;
private int _size;
private TagType _type;
private TagNode _tag;
private bool _hasName;
private List<string> _invalidNames = new List<string>();
#region Constructors
// Called when created from unmanaged code
public CreateNodeWindowController (IntPtr handle) : base (handle)
{
Initialize ();
}
// Called when created directly from a XIB file
[Export ("initWithCoder:")]
public CreateNodeWindowController (NSCoder coder) : base (coder)
{
Initialize ();
}
// Call to load from the XIB/NIB file
public CreateNodeWindowController () : base ("CreateNodeWindow")
{
Initialize ();
}
// Shared initialization code
void Initialize ()
{
}
public override void AwakeFromNib ()
{
base.AwakeFromNib ();
SetNameBoxState();
SetSizeBoxState();
}
#endregion
//strongly typed window accessor
public new CreateNodeWindow Window
{
get {
return (CreateNodeWindow)base.Window;
}
}
private void SetNameBoxState ()
{
if (_nameField == null || _nameFieldLabel == null)
return;
if (HasName) {
_nameFieldLabel.Enabled = true;
_nameFieldLabel.TextColor = NSColor.ControlText;
_nameField.Enabled = true;
}
else {
_nameFieldLabel.Enabled = false;
_nameFieldLabel.TextColor = NSColor.DisabledControlText;
_nameField.Enabled = false;
}
}
private void SetSizeBoxState ()
{
if (_sizeField == null || _sizeFieldLabel == null)
return;
if (IsTagSizedType) {
_sizeFieldLabel.Enabled = true;
_sizeFieldLabel.TextColor = NSColor.ControlText;
_sizeField.Enabled = true;
}
else {
_sizeFieldLabel.Enabled = false;
_sizeFieldLabel.TextColor = NSColor.DisabledControlText;
_sizeField.Enabled = false;
}
}
public TagType TagType
{
get { return _type; }
set {
_type = value;
SetSizeBoxState();
}
}
public string TagName
{
get { return _name; }
}
public TagNode TagNode
{
get { return _tag; }
}
public List<string> InvalidNames
{
get { return _invalidNames; }
}
public bool HasName
{
get { return _hasName; }
set
{
_hasName = value;
SetNameBoxState();
}
}
private void Apply ()
{
if (ValidateInput()) {
_tag = CreateTag();
NSApplication.SharedApplication.StopModalWithCode((int)ModalResult.OK);
return;
}
}
private TagNode CreateTag ()
{
switch (_type) {
case TagType.TAG_BYTE:
return new TagNodeByte();
case TagType.TAG_BYTE_ARRAY:
return new TagNodeByteArray(new byte[_size]);
case TagType.TAG_COMPOUND:
return new TagNodeCompound();
case TagType.TAG_DOUBLE:
return new TagNodeDouble();
case TagType.TAG_FLOAT:
return new TagNodeFloat();
case TagType.TAG_INT:
return new TagNodeInt();
case TagType.TAG_INT_ARRAY:
return new TagNodeIntArray(new int[_size]);
case TagType.TAG_LIST:
return new TagNodeList(TagType.TAG_BYTE);
case TagType.TAG_LONG:
return new TagNodeLong();
case TagType.TAG_SHORT:
return new TagNodeShort();
case TagType.TAG_STRING:
return new TagNodeString();
default:
return new TagNodeByte();
}
}
private bool ValidateInput ()
{
return ValidateNameInput()
&& ValidateSizeInput();
}
private bool ValidateNameInput ()
{
if (!HasName)
return true;
string text = _nameField.StringValue.Trim();
if (_invalidNames.Contains(text)) {
NSAlert.WithMessage("Duplicate name.", "OK", null, null, "You cannot specify a name already in use by another tag within the same container.").RunModal();
return false;
}
_name = _nameField.StringValue.Trim();
return true;
}
private bool ValidateSizeInput ()
{
if (!IsTagSizedType)
return true;
if (!Int32.TryParse(_sizeField.StringValue.Trim(), out _size)) {
NSAlert.WithMessage("Invalid size.", "OK", null, null, "The size field must be a valid integer value.").RunModal();
return false;
}
_size = Math.Max(0, _size);
return true;
}
private bool IsTagSizedType
{
get
{
switch (_type) {
case TagType.TAG_BYTE_ARRAY:
case TagType.TAG_INT_ARRAY:
return true;
default:
return false;
}
}
}
partial void ActionOK (NSObject sender)
{
Apply ();
}
partial void ActionCancel (NSObject sender)
{
NSApplication.SharedApplication.StopModalWithCode((int)ModalResult.Cancel);
}
}
}
| |
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using MawMvcApp.ViewModels.Gps;
using MawMvcApp.ViewModels.Navigation;
using MawMvcApp.ViewModels.Tools;
using MawMvcApp.ViewModels.Tools.Dotnet;
using MawMvcApp.ViewModels.Tools.Bandwidth;
using MawMvcApp.ViewModels.Tools.FileSize;
using MawMvcApp.ViewModels.Tools.Time;
namespace MawMvcApp.Controllers
{
[Route("tools")]
public class ToolsController
: MawBaseController<ToolsController>
{
readonly IFileProvider _fileProvider;
public ToolsController(ILogger<ToolsController> log,
IWebHostEnvironment env)
: base(log)
{
_fileProvider = env?.WebRootFileProvider ?? throw new ArgumentNullException(nameof(env));
}
[HttpGet("")]
public IActionResult Index()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View();
}
[HttpGet("roll-the-dice")]
public IActionResult RollTheDice()
{
ViewBag.NavigationZone = NavigationZone.Tools;
var model = new RollTheDiceModel
{
NumberOfThrows = 10,
NumberOfSides = 6
};
return View(model);
}
[HttpPost("roll-the-dice")]
[ValidateAntiForgeryToken]
public IActionResult RollTheDice(RollTheDiceModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.ThrowDice();
}
else
{
model.HasErrors = true;
LogValidationErrors();
}
return View(model);
}
[HttpGet("google-maps")]
public IActionResult GoogleMaps()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View();
}
[HttpGet("binary-clock-about")]
public IActionResult BinaryClockAbout()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View();
}
[HttpGet("binary-clock")]
public IActionResult BinaryClock()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View();
}
[HttpGet("dotnet-formatting-dates")]
public IActionResult DotnetFormattingDates()
{
var mgr = new FormatExampleManager();
var date = new DateTime(1977, 10, 3, 3, 24, 46, 789, DateTimeKind.Local);
ViewBag.NavigationZone = NavigationZone.Tools;
ViewBag.ExampleDate = date;
return View(mgr.GetDateFormatExamples(date));
}
[HttpGet("dotnet-formatting-numbers")]
public IActionResult DotnetFormattingNumbers()
{
var mgr = new FormatExampleManager();
double value = 1234.125678;
ViewBag.NavigationZone = NavigationZone.Tools;
ViewBag.ExampleDate = value;
return View(mgr.GetNumberFormatExamples(value));
}
[HttpGet("dotnet-regex")]
public IActionResult DotnetRegex()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new RegexViewModel());
}
[HttpPost("dotnet-regex")]
[ValidateAntiForgeryToken]
public IActionResult DotnetRegex(RegexViewModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.Execute();
}
else
{
model.HasErrors = true;
LogValidationErrors();
}
return View(model);
}
[HttpGet("networking-bandwidth")]
public IActionResult NetworkingBandwidth()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new BandwidthViewModel());
}
[HttpPost("networking-bandwidth")]
[ValidateAntiForgeryToken]
public IActionResult NetworkingBandwidth(BandwidthViewModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.Calculate();
}
else
{
model.ErrorMessage = "Please enter a number for the file size";
}
return View(model);
}
[HttpGet("networking-file-size")]
public IActionResult NetworkingFileSize()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new FileSizeViewModel());
}
[HttpPost("networking-file-size")]
[ValidateAntiForgeryToken]
public IActionResult NetworkingFileSize(FileSizeViewModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.Calculate();
}
else
{
model.ErrorMessage = "Please enter a valid file size";
}
return View(model);
}
[HttpGet("networking-time")]
public IActionResult NetworkingTime()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new NetworkingTimeViewModel());
}
[HttpPost("networking-time")]
[ValidateAntiForgeryToken]
public IActionResult NetworkingTime(NetworkingTimeViewModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.Calculate();
}
else
{
model.ErrorMessage = "Please enter a valid time";
}
return View(model);
}
[HttpGet("weekend-countdown")]
public IActionResult WeekendCountdown()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View();
}
[HttpGet("weather")]
public IActionResult Weather()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View();
}
[HttpGet("byte-counter")]
public IActionResult ByteCounter()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new ByteCounterViewModel());
}
[HttpPost("byte-counter")]
[ValidateAntiForgeryToken]
public IActionResult ByteCounter(ByteCounterViewModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
model.Calculate();
return View(model);
}
[HttpGet("date-diff")]
public IActionResult DateDiff()
{
ViewBag.NavigationZone = NavigationZone.Tools;
var model = new DateDiff
{
StartDate = DateTime.Now.AddYears(-1),
EndDate = DateTime.Now
};
return View(model);
}
[HttpPost("date-diff")]
[ValidateAntiForgeryToken]
public IActionResult DateDiff(DateDiff model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
model.ShowResults = ModelState.IsValid;
if (!ModelState.IsValid)
{
model.HasErrors = true;
LogValidationErrors();
}
return View(model);
}
[HttpGet("gps-conversion")]
public IActionResult GpsConversion()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new GpsConversionModel());
}
[HttpPost("gps-conversion")]
[ValidateAntiForgeryToken]
public IActionResult GpsConversion(GpsConversionModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.Convert();
}
else
{
LogValidationErrors();
}
return View(model);
}
[HttpGet("guid-gen")]
public IActionResult GuidGen()
{
ViewBag.NavigationZone = NavigationZone.Tools;
ViewBag.Guid = Guid.NewGuid().ToString();
return View();
}
[HttpGet("html-encode")]
public IActionResult HtmlEncode()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new HtmlEncodeDecodeModel());
}
[HttpPost("html-encode")]
[ValidateAntiForgeryToken]
public IActionResult HtmlEncode(HtmlEncodeDecodeModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
if (model.Mode == EncodeMode.Decode)
{
model.Decode();
}
else
{
model.Encode();
}
}
else
{
model.HasErrors = true;
LogValidationErrors();
}
return View(model);
}
[HttpGet("paths")]
public IActionResult Paths()
{
ViewBag.NavigationZone = NavigationZone.Tools;
var model = new PathsModel();
model.PreparePaths();
return View(model);
}
[HttpGet("random-bytes")]
public IActionResult RandomBytes()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new RandomBytesModel());
}
[HttpPost("random-bytes")]
[ValidateAntiForgeryToken]
public IActionResult RandomBytes(RandomBytesModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.GenerateRandomness();
}
else
{
model.HasErrors = true;
LogValidationErrors();
}
return View(model);
}
[HttpGet("color-converter")]
public IActionResult ColorConverter()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new ColorConverterModel());
}
[HttpPost("color-converter")]
[ValidateAntiForgeryToken]
public IActionResult ColorConverter(ColorConverterModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.Convert();
}
else
{
model.HasErrors = true;
LogValidationErrors();
}
return View(model);
}
[HttpGet("url-encode")]
public IActionResult UrlEncode()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new UrlEncodeModel());
}
[HttpPost("url-encode")]
[ValidateAntiForgeryToken]
public IActionResult UrlEncode(UrlEncodeModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.PerformCoding();
}
else
{
model.HasErrors = true;
LogValidationErrors();
}
return View(model);
}
[HttpGet("xml-validate")]
public IActionResult XmlValidate()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new XmlValidateModel());
}
[HttpPost("xml-validate")]
[ValidateAntiForgeryToken]
public IActionResult XmlValidate(XmlValidateModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.ValidateXml();
}
else
{
model.HasErrors = true;
LogValidationErrors();
}
return View(model);
}
[HttpGet("xsd-validate")]
public IActionResult XsdValidate()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new XsdValidateModel());
}
[HttpPost("xsd-validate")]
[ValidateAntiForgeryToken]
public IActionResult XsdValidate(XsdValidateModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.ValidateSchema();
}
else
{
model.HasErrors = true;
LogValidationErrors();
}
return View(model);
}
[HttpGet("xsl-transform")]
public IActionResult XslTransform()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View(new XslTransformModel());
}
[HttpPost("xsl-transform")]
[ValidateAntiForgeryToken]
public IActionResult XslTransform(XslTransformModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
ViewBag.NavigationZone = NavigationZone.Tools;
if (ModelState.IsValid)
{
model.ExecuteTransform();
}
else
{
model.HasErrors = true;
LogValidationErrors();
}
return View(model);
}
[HttpGet("learning")]
public IActionResult Learning()
{
ViewBag.NavigationZone = NavigationZone.Tools;
return View();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Threading;
using AutoMapper;
using Umbraco.Core.Auditing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Events;
using Umbraco.Core.Exceptions;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the ContentType Service, which is an easy access to operations involving <see cref="IContentType"/>
/// </summary>
public class ContentTypeService : ContentTypeServiceBase, IContentTypeService
{
private readonly IContentService _contentService;
private readonly IMediaService _mediaService;
//Support recursive locks because some of the methods that require locking call other methods that require locking.
//for example, the Move method needs to be locked but this calls the Save method which also needs to be locked.
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
public ContentTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory, IContentService contentService, IMediaService mediaService)
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{
if (contentService == null) throw new ArgumentNullException("contentService");
if (mediaService == null) throw new ArgumentNullException("mediaService");
_contentService = contentService;
_mediaService = mediaService;
}
#region Containers
public Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateContentTypeContainer(int parentId, string name, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
try
{
var container = new EntityContainer(Constants.ObjectTypes.DocumentTypeGuid)
{
Name = name,
ParentId = parentId,
CreatorId = userId
};
if (SavingContentTypeContainer.IsRaisedEventCancelled(
new SaveEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.AddOrUpdate(container);
uow.Commit();
SavedContentTypeContainer.RaiseEvent(new SaveEventArgs<EntityContainer>(container, evtMsgs), this);
//TODO: Audit trail ?
return Attempt.Succeed(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.Success, evtMsgs));
}
catch (Exception ex)
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(null, OperationStatusType.FailedExceptionThrown, evtMsgs), ex);
}
}
}
public Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateMediaTypeContainer(int parentId, string name, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
try
{
var container = new EntityContainer(Constants.ObjectTypes.MediaTypeGuid)
{
Name = name,
ParentId = parentId,
CreatorId = userId
};
if (SavingMediaTypeContainer.IsRaisedEventCancelled(
new SaveEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.AddOrUpdate(container);
uow.Commit();
SavedMediaTypeContainer.RaiseEvent(new SaveEventArgs<EntityContainer>(container, evtMsgs), this);
//TODO: Audit trail ?
return Attempt.Succeed(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.Success, evtMsgs));
}
catch (Exception ex)
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(null, OperationStatusType.FailedExceptionThrown, evtMsgs), ex);
}
}
}
public Attempt<OperationStatus> SaveContentTypeContainer(EntityContainer container, int userId = 0)
{
return SaveContainer(
SavingContentTypeContainer, SavedContentTypeContainer,
container, Constants.ObjectTypes.DocumentTypeContainerGuid, "document type", userId);
}
public Attempt<OperationStatus> SaveMediaTypeContainer(EntityContainer container, int userId = 0)
{
return SaveContainer(
SavingMediaTypeContainer, SavedMediaTypeContainer,
container, Constants.ObjectTypes.MediaTypeContainerGuid, "media type", userId);
}
private Attempt<OperationStatus> SaveContainer(
TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> savingEvent,
TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> savedEvent,
EntityContainer container,
Guid containerObjectType,
string objectTypeName, int userId)
{
var evtMsgs = EventMessagesFactory.Get();
if (container.ContainerObjectType != containerObjectType)
{
var ex = new InvalidOperationException("Not a " + objectTypeName + " container.");
return OperationStatus.Exception(evtMsgs, ex);
}
if (container.HasIdentity && container.IsPropertyDirty("ParentId"))
{
var ex = new InvalidOperationException("Cannot save a container with a modified parent, move the container instead.");
return OperationStatus.Exception(evtMsgs, ex);
}
if (savingEvent.IsRaisedEventCancelled(
new SaveEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return OperationStatus.Cancelled(evtMsgs);
}
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType))
{
repo.AddOrUpdate(container);
uow.Commit();
}
savedEvent.RaiseEvent(new SaveEventArgs<EntityContainer>(container, evtMsgs), this);
//TODO: Audit trail ?
return OperationStatus.Success(evtMsgs);
}
public EntityContainer GetContentTypeContainer(int containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.DocumentTypeContainerGuid);
}
public EntityContainer GetMediaTypeContainer(int containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.MediaTypeContainerGuid);
}
private EntityContainer GetContainer(int containerId, Guid containerObjectType)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType))
{
var container = repo.Get(containerId);
return container;
}
}
public IEnumerable<EntityContainer> GetMediaTypeContainers(int[] containerIds)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
return repo.GetAll(containerIds);
}
}
public IEnumerable<EntityContainer> GetMediaTypeContainers(string name, int level)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
return repo.Get(name, level);
}
}
public IEnumerable<EntityContainer> GetMediaTypeContainers(IMediaType mediaType)
{
var ancestorIds = mediaType.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
var asInt = x.TryConvertTo<int>();
if (asInt) return asInt.Result;
return int.MinValue;
})
.Where(x => x != int.MinValue && x != mediaType.Id)
.ToArray();
return GetMediaTypeContainers(ancestorIds);
}
public EntityContainer GetContentTypeContainer(Guid containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.DocumentTypeContainerGuid);
}
public IEnumerable<EntityContainer> GetContentTypeContainers(int[] containerIds)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
return repo.GetAll(containerIds);
}
}
public IEnumerable<EntityContainer> GetContentTypeContainers(IContentType contentType)
{
var ancestorIds = contentType.Path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
var asInt = x.TryConvertTo<int>();
if (asInt) return asInt.Result;
return int.MinValue;
})
.Where(x => x != int.MinValue && x != contentType.Id)
.ToArray();
return GetContentTypeContainers(ancestorIds);
}
public EntityContainer GetMediaTypeContainer(Guid containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.MediaTypeContainerGuid);
}
private EntityContainer GetContainer(Guid containerId, Guid containerObjectType)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType))
{
var container = repo.Get(containerId);
return container;
}
}
public IEnumerable<EntityContainer> GetContentTypeContainers(string name, int level)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
return repo.Get(name, level);
}
}
public Attempt<OperationStatus> DeleteContentTypeContainer(int containerId, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
var container = repo.Get(containerId);
if (container == null) return OperationStatus.NoOperation(evtMsgs);
if (DeletingContentTypeContainer.IsRaisedEventCancelled(
new DeleteEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus(OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.Delete(container);
uow.Commit();
DeletedContentTypeContainer.RaiseEvent(new DeleteEventArgs<EntityContainer>(container, evtMsgs), this);
return OperationStatus.Success(evtMsgs);
//TODO: Audit trail ?
}
}
public Attempt<OperationStatus> DeleteMediaTypeContainer(int containerId, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
var container = repo.Get(containerId);
if (container == null) return OperationStatus.NoOperation(evtMsgs);
if (DeletingMediaTypeContainer.IsRaisedEventCancelled(
new DeleteEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus(OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.Delete(container);
uow.Commit();
DeletedMediaTypeContainer.RaiseEvent(new DeleteEventArgs<EntityContainer>(container, evtMsgs), this);
return OperationStatus.Success(evtMsgs);
//TODO: Audit trail ?
}
}
#endregion
/// <summary>
/// Gets all property type aliases.
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetAllPropertyTypeAliases()
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAllPropertyTypeAliases();
}
}
/// <summary>
/// Gets all content type aliases
/// </summary>
/// <param name="objectTypes">
/// If this list is empty, it will return all content type aliases for media, members and content, otherwise
/// it will only return content type aliases for the object types specified
/// </param>
/// <returns></returns>
public IEnumerable<string> GetAllContentTypeAliases(params Guid[] objectTypes)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAllContentTypeAliases(objectTypes);
}
}
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parentId">
/// The parent to copy the content type to, default is -1 (root)
/// </param>
/// <returns></returns>
public IContentType Copy(IContentType original, string alias, string name, int parentId = -1)
{
IContentType parent = null;
if (parentId > 0)
{
parent = GetContentType(parentId);
if (parent == null)
{
throw new InvalidOperationException("Could not find content type with id " + parentId);
}
}
return Copy(original, alias, name, parent);
}
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parent">
/// The parent to copy the content type to, default is null (root)
/// </param>
/// <returns></returns>
public IContentType Copy(IContentType original, string alias, string name, IContentType parent)
{
Mandate.ParameterNotNull(original, "original");
Mandate.ParameterNotNullOrEmpty(alias, "alias");
if (parent != null)
{
Mandate.That(parent.HasIdentity, () => new InvalidOperationException("The parent content type must have an identity"));
}
var clone = original.DeepCloneWithResetIdentities(alias);
clone.Name = name;
var compositionAliases = clone.CompositionAliases().Except(new[] { alias }).ToList();
//remove all composition that is not it's current alias
foreach (var a in compositionAliases)
{
clone.RemoveContentType(a);
}
//if a parent is specified set it's composition and parent
if (parent != null)
{
//add a new parent composition
clone.AddContentType(parent);
clone.ParentId = parent.Id;
}
else
{
//set to root
clone.ParentId = -1;
}
Save(clone);
return clone;
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(string alias)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(alias);
}
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Key
/// </summary>
/// <param name="id">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(params int[] ids)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(IEnumerable<Guid> ids)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids.ToArray());
}
}
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetContentType(id);
if (found == null) return Enumerable.Empty<IContentType>();
var query = Query<IContentType>.Builder.Where(x => x.ParentId == found.Id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetContentType(id);
if (found == null) return false;
var query = Query<IContentType>.Builder.Where(x => x.ParentId == found.Id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// This is called after an IContentType is saved and is used to update the content xml structures in the database
/// if they are required to be updated.
/// </summary>
/// <param name="contentTypes">A tuple of a content type and a boolean indicating if it is new (HasIdentity was false before committing)</param>
private void UpdateContentXmlStructure(params IContentTypeBase[] contentTypes)
{
var toUpdate = GetContentTypesForXmlUpdates(contentTypes).ToArray();
if (toUpdate.Any())
{
var firstType = toUpdate.First();
//if it is a content type then call the rebuilding methods or content
if (firstType is IContentType)
{
var typedContentService = _contentService as ContentService;
if (typedContentService != null)
{
typedContentService.RePublishAll(toUpdate.Select(x => x.Id).ToArray());
}
else
{
//this should never occur, the content service should always be typed but we'll check anyways.
_contentService.RePublishAll();
}
}
else if (firstType is IMediaType)
{
//if it is a media type then call the rebuilding methods for media
var typedContentService = _mediaService as MediaService;
if (typedContentService != null)
{
typedContentService.RebuildXmlStructures(toUpdate.Select(x => x.Id).ToArray());
}
}
}
}
public int CountContentTypes()
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Count(Query<IContentType>.Builder);
}
}
public int CountMediaTypes()
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Count(Query<IMediaType>.Builder);
}
}
/// <summary>
/// Validates the composition, if its invalid a list of property type aliases that were duplicated is returned
/// </summary>
/// <param name="compo"></param>
/// <returns></returns>
public Attempt<string[]> ValidateComposition(IContentTypeComposition compo)
{
using (new WriteLock(Locker))
{
try
{
ValidateLocked(compo);
return Attempt<string[]>.Succeed();
}
catch (InvalidCompositionException ex)
{
return Attempt.Fail(ex.PropertyTypeAliases, ex);
}
}
}
protected void ValidateLocked(IContentTypeComposition compositionContentType)
{
// performs business-level validation of the composition
// should ensure that it is absolutely safe to save the composition
// eg maybe a property has been added, with an alias that's OK (no conflict with ancestors)
// but that cannot be used (conflict with descendants)
var contentType = compositionContentType as IContentType;
var mediaType = compositionContentType as IMediaType;
var memberType = compositionContentType as IMemberType; // should NOT do it here but... v8!
IContentTypeComposition[] allContentTypes;
if (contentType != null)
allContentTypes = GetAllContentTypes().Cast<IContentTypeComposition>().ToArray();
else if (mediaType != null)
allContentTypes = GetAllMediaTypes().Cast<IContentTypeComposition>().ToArray();
else if (memberType != null)
return; // no compositions on members, always validate
else
throw new Exception("Composition is neither IContentType nor IMediaType nor IMemberType?");
var compositionAliases = compositionContentType.CompositionAliases();
var compositions = allContentTypes.Where(x => compositionAliases.Any(y => x.Alias.Equals(y)));
var propertyTypeAliases = compositionContentType.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).ToArray();
var indirectReferences = allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == compositionContentType.Id));
var comparer = new DelegateEqualityComparer<IContentTypeComposition>((x, y) => x.Id == y.Id, x => x.Id);
var dependencies = new HashSet<IContentTypeComposition>(compositions, comparer);
var stack = new Stack<IContentTypeComposition>();
indirectReferences.ForEach(stack.Push);//Push indirect references to a stack, so we can add recursively
while (stack.Count > 0)
{
var indirectReference = stack.Pop();
dependencies.Add(indirectReference);
//Get all compositions for the current indirect reference
var directReferences = indirectReference.ContentTypeComposition;
foreach (var directReference in directReferences)
{
if (directReference.Id == compositionContentType.Id || directReference.Alias.Equals(compositionContentType.Alias)) continue;
dependencies.Add(directReference);
//A direct reference has compositions of its own - these also need to be taken into account
var directReferenceGraph = directReference.CompositionAliases();
allContentTypes.Where(x => directReferenceGraph.Any(y => x.Alias.Equals(y, StringComparison.InvariantCultureIgnoreCase))).ForEach(c => dependencies.Add(c));
}
//Recursive lookup of indirect references
allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == indirectReference.Id)).ForEach(stack.Push);
}
foreach (var dependency in dependencies)
{
if (dependency.Id == compositionContentType.Id) continue;
var contentTypeDependency = allContentTypes.FirstOrDefault(x => x.Alias.Equals(dependency.Alias, StringComparison.InvariantCultureIgnoreCase));
if (contentTypeDependency == null) continue;
var intersect = contentTypeDependency.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).Intersect(propertyTypeAliases).ToArray();
if (intersect.Length == 0) continue;
throw new InvalidCompositionException(compositionContentType.Alias, intersect.ToArray());
}
}
/// <summary>
/// Saves a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to save</param>
/// <param name="userId">Optional id of the user saving the ContentType</param>
public void Save(IContentType contentType, int userId = 0)
{
if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs<IContentType>(contentType), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
ValidateLocked(contentType); // throws if invalid
contentType.CreatorId = userId;
repository.AddOrUpdate(contentType);
uow.Commit();
}
UpdateContentXmlStructure(contentType);
}
SavedContentType.RaiseEvent(new SaveEventArgs<IContentType>(contentType, false), this);
Audit(AuditType.Save, string.Format("Save ContentType performed by user"), userId, contentType.Id);
}
/// <summary>
/// Saves a collection of <see cref="IContentType"/> objects
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to save</param>
/// <param name="userId">Optional id of the user saving the ContentType</param>
public void Save(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs<IContentType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
// all-or-nothing, validate them all first
foreach (var contentType in asArray)
{
ValidateLocked(contentType); // throws if invalid
}
foreach (var contentType in asArray)
{
contentType.CreatorId = userId;
repository.AddOrUpdate(contentType);
}
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
}
SavedContentType.RaiseEvent(new SaveEventArgs<IContentType>(asArray, false), this);
Audit(AuditType.Save, string.Format("Save ContentTypes performed by user"), userId, -1);
}
/// <summary>
/// Deletes a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to delete</param>
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks>
public void Delete(IContentType contentType, int userId = 0)
{
if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs<IContentType>(contentType), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
//TODO: This needs to change, if we are deleting a content type, we should just delete the data,
// this method will recursively go lookup every content item, check if any of it's descendants are
// of a different type, move them to the recycle bin, then permanently delete the content items.
// The main problem with this is that for every content item being deleted, events are raised...
// which we need for many things like keeping caches in sync, but we can surely do this MUCH better.
var deletedContentTypes = new List<IContentType>() {contentType};
deletedContentTypes.AddRange(contentType.Descendants().OfType<IContentType>());
foreach (var deletedContentType in deletedContentTypes)
{
_contentService.DeleteContentOfType(deletedContentType.Id);
}
repository.Delete(contentType);
uow.Commit();
DeletedContentType.RaiseEvent(new DeleteEventArgs<IContentType>(deletedContentTypes.DistinctBy(x => x.Id), false), this);
}
Audit(AuditType.Delete, string.Format("Delete ContentType performed by user"), userId, contentType.Id);
}
}
/// <summary>
/// Deletes a collection of <see cref="IContentType"/> objects.
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to delete</param>
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>
/// Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/>
/// </remarks>
public void Delete(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs<IContentType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
var deletedContentTypes = new List<IContentType>();
deletedContentTypes.AddRange(asArray);
foreach (var contentType in asArray)
{
deletedContentTypes.AddRange(contentType.Descendants().OfType<IContentType>());
}
foreach (var deletedContentType in deletedContentTypes)
{
_contentService.DeleteContentOfType(deletedContentType.Id);
}
foreach (var contentType in asArray)
{
repository.Delete(contentType);
}
uow.Commit();
DeletedContentType.RaiseEvent(new DeleteEventArgs<IContentType>(deletedContentTypes.DistinctBy(x => x.Id), false), this);
}
Audit(AuditType.Delete, string.Format("Delete ContentTypes performed by user"), userId, -1);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(string alias)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(alias);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(params int[] ids)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(IEnumerable<Guid> ids)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids.ToArray());
}
}
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetMediaType(id);
if (found == null) return Enumerable.Empty<IMediaType>();
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == found.Id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetMediaType(id);
if (found == null) return false;
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == found.Id);
int count = repository.Count(query);
return count > 0;
}
}
public Attempt<OperationStatus<MoveOperationStatusType>> MoveMediaType(IMediaType toMove, int containerId)
{
var evtMsgs = EventMessagesFactory.Get();
if (MovingMediaType.IsRaisedEventCancelled(
new MoveEventArgs<IMediaType>(evtMsgs, new MoveEventInfo<IMediaType>(toMove, toMove.Path, containerId)),
this))
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(
MoveOperationStatusType.FailedCancelledByEvent, evtMsgs));
}
var moveInfo = new List<MoveEventInfo<IMediaType>>();
var uow = UowProvider.GetUnitOfWork();
using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
try
{
EntityContainer container = null;
if (containerId > 0)
{
container = containerRepository.Get(containerId);
if (container == null)
throw new DataOperationException<MoveOperationStatusType>(MoveOperationStatusType.FailedParentNotFound);
}
moveInfo.AddRange(repository.Move(toMove, container));
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(ex.Operation, evtMsgs));
}
uow.Commit();
}
MovedMediaType.RaiseEvent(new MoveEventArgs<IMediaType>(false, evtMsgs, moveInfo.ToArray()), this);
return Attempt.Succeed(
new OperationStatus<MoveOperationStatusType>(MoveOperationStatusType.Success, evtMsgs));
}
public Attempt<OperationStatus<MoveOperationStatusType>> MoveContentType(IContentType toMove, int containerId)
{
var evtMsgs = EventMessagesFactory.Get();
if (MovingContentType.IsRaisedEventCancelled(
new MoveEventArgs<IContentType>(evtMsgs, new MoveEventInfo<IContentType>(toMove, toMove.Path, containerId)),
this))
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(
MoveOperationStatusType.FailedCancelledByEvent, evtMsgs));
}
var moveInfo = new List<MoveEventInfo<IContentType>>();
var uow = UowProvider.GetUnitOfWork();
using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
try
{
EntityContainer container = null;
if (containerId > 0)
{
container = containerRepository.Get(containerId);
if (container == null)
throw new DataOperationException<MoveOperationStatusType>(MoveOperationStatusType.FailedParentNotFound);
}
moveInfo.AddRange(repository.Move(toMove, container));
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(ex.Operation, evtMsgs));
}
uow.Commit();
}
MovedContentType.RaiseEvent(new MoveEventArgs<IContentType>(false, evtMsgs, moveInfo.ToArray()), this);
return Attempt.Succeed(
new OperationStatus<MoveOperationStatusType>(MoveOperationStatusType.Success, evtMsgs));
}
public Attempt<OperationStatus<IMediaType, MoveOperationStatusType>> CopyMediaType(IMediaType toCopy, int containerId)
{
var evtMsgs = EventMessagesFactory.Get();
IMediaType copy;
var uow = UowProvider.GetUnitOfWork();
using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
try
{
if (containerId > 0)
{
var container = containerRepository.Get(containerId);
if (container == null)
throw new DataOperationException<MoveOperationStatusType>(MoveOperationStatusType.FailedParentNotFound);
}
var alias = repository.GetUniqueAlias(toCopy.Alias);
copy = toCopy.DeepCloneWithResetIdentities(alias);
copy.Name = copy.Name + " (copy)"; // might not be unique
// if it has a parent, and the parent is a content type, unplug composition
// all other compositions remain in place in the copied content type
if (copy.ParentId > 0)
{
var parent = repository.Get(copy.ParentId);
if (parent != null)
copy.RemoveContentType(parent.Alias);
}
copy.ParentId = containerId;
repository.AddOrUpdate(copy);
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(new OperationStatus<IMediaType, MoveOperationStatusType>(null, ex.Operation, evtMsgs));
}
uow.Commit();
}
return Attempt.Succeed(new OperationStatus<IMediaType, MoveOperationStatusType>(copy, MoveOperationStatusType.Success, evtMsgs));
}
public Attempt<OperationStatus<IContentType, MoveOperationStatusType>> CopyContentType(IContentType toCopy, int containerId)
{
var evtMsgs = EventMessagesFactory.Get();
IContentType copy;
var uow = UowProvider.GetUnitOfWork();
using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
try
{
if (containerId > 0)
{
var container = containerRepository.Get(containerId);
if (container == null)
throw new DataOperationException<MoveOperationStatusType>(MoveOperationStatusType.FailedParentNotFound);
}
var alias = repository.GetUniqueAlias(toCopy.Alias);
copy = toCopy.DeepCloneWithResetIdentities(alias);
copy.Name = copy.Name + " (copy)"; // might not be unique
// if it has a parent, and the parent is a content type, unplug composition
// all other compositions remain in place in the copied content type
if (copy.ParentId > 0)
{
var parent = repository.Get(copy.ParentId);
if (parent != null)
copy.RemoveContentType(parent.Alias);
}
copy.ParentId = containerId;
repository.AddOrUpdate(copy);
}
catch (DataOperationException<MoveOperationStatusType> ex)
{
return Attempt.Fail(new OperationStatus<IContentType, MoveOperationStatusType>(null, ex.Operation, evtMsgs));
}
uow.Commit();
}
return Attempt.Succeed(new OperationStatus<IContentType, MoveOperationStatusType>(copy, MoveOperationStatusType.Success, evtMsgs));
}
/// <summary>
/// Saves a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the user saving the MediaType</param>
public void Save(IMediaType mediaType, int userId = 0)
{
if (SavingMediaType.IsRaisedEventCancelled(new SaveEventArgs<IMediaType>(mediaType), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
ValidateLocked(mediaType); // throws if invalid
mediaType.CreatorId = userId;
repository.AddOrUpdate(mediaType);
uow.Commit();
}
UpdateContentXmlStructure(mediaType);
}
SavedMediaType.RaiseEvent(new SaveEventArgs<IMediaType>(mediaType, false), this);
Audit(AuditType.Save, string.Format("Save MediaType performed by user"), userId, mediaType.Id);
}
/// <summary>
/// Saves a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the user savging the MediaTypes</param>
public void Save(IEnumerable<IMediaType> mediaTypes, int userId = 0)
{
var asArray = mediaTypes.ToArray();
if (SavingMediaType.IsRaisedEventCancelled(new SaveEventArgs<IMediaType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
// all-or-nothing, validate them all first
foreach (var mediaType in asArray)
{
ValidateLocked(mediaType); // throws if invalid
}
foreach (var mediaType in asArray)
{
mediaType.CreatorId = userId;
repository.AddOrUpdate(mediaType);
}
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
}
SavedMediaType.RaiseEvent(new SaveEventArgs<IMediaType>(asArray, false), this);
Audit(AuditType.Save, string.Format("Save MediaTypes performed by user"), userId, -1);
}
/// <summary>
/// Deletes a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to delete</param>
/// <param name="userId">Optional Id of the user deleting the MediaType</param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
public void Delete(IMediaType mediaType, int userId = 0)
{
if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs<IMediaType>(mediaType), this))
return;
using (new WriteLock(Locker))
{
_mediaService.DeleteMediaOfType(mediaType.Id, userId);
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
var deletedMediaTypes = new List<IMediaType>() {mediaType};
deletedMediaTypes.AddRange(mediaType.Descendants().OfType<IMediaType>());
repository.Delete(mediaType);
uow.Commit();
DeletedMediaType.RaiseEvent(new DeleteEventArgs<IMediaType>(deletedMediaTypes.DistinctBy(x => x.Id), false), this);
}
Audit(AuditType.Delete, string.Format("Delete MediaType performed by user"), userId, mediaType.Id);
}
}
/// <summary>
/// Deletes a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to delete</param>
/// <param name="userId"></param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
public void Delete(IEnumerable<IMediaType> mediaTypes, int userId = 0)
{
var asArray = mediaTypes.ToArray();
if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs<IMediaType>(asArray), this))
return;
using (new WriteLock(Locker))
{
foreach (var mediaType in asArray)
{
_mediaService.DeleteMediaOfType(mediaType.Id);
}
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))
{
var deletedMediaTypes = new List<IMediaType>();
deletedMediaTypes.AddRange(asArray);
foreach (var mediaType in asArray)
{
deletedMediaTypes.AddRange(mediaType.Descendants().OfType<IMediaType>());
repository.Delete(mediaType);
}
uow.Commit();
DeletedMediaType.RaiseEvent(new DeleteEventArgs<IMediaType>(deletedMediaTypes.DistinctBy(x => x.Id), false), this);
}
Audit(AuditType.Delete, string.Format("Delete MediaTypes performed by user"), userId, -1);
}
}
/// <summary>
/// Generates the complete (simplified) XML DTD.
/// </summary>
/// <returns>The DTD as a string</returns>
public string GetDtd()
{
var dtd = new StringBuilder();
dtd.AppendLine("<!DOCTYPE root [ ");
dtd.AppendLine(GetContentTypesDtd());
dtd.AppendLine("]>");
return dtd.ToString();
}
/// <summary>
/// Generates the complete XML DTD without the root.
/// </summary>
/// <returns>The DTD as a string</returns>
public string GetContentTypesDtd()
{
var dtd = new StringBuilder();
if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema)
{
dtd.AppendLine("<!ELEMENT node ANY> <!ATTLIST node id ID #REQUIRED> <!ELEMENT data ANY>");
}
else
{
try
{
var strictSchemaBuilder = new StringBuilder();
var contentTypes = GetAllContentTypes();
foreach (ContentType contentType in contentTypes)
{
string safeAlias = contentType.Alias.ToUmbracoAlias();
if (safeAlias != null)
{
strictSchemaBuilder.AppendLine(String.Format("<!ELEMENT {0} ANY>", safeAlias));
strictSchemaBuilder.AppendLine(String.Format("<!ATTLIST {0} id ID #REQUIRED>", safeAlias));
}
}
// Only commit the strong schema to the container if we didn't generate an error building it
dtd.Append(strictSchemaBuilder);
}
catch (Exception exception)
{
LogHelper.Error<ContentTypeService>("Error while trying to build DTD for Xml schema; is Umbraco installed correctly and the connection string configured?", exception);
}
}
return dtd.ToString();
}
private void Audit(AuditType type, string message, int userId, int objectId)
{
var uow = UowProvider.GetUnitOfWork();
using (var auditRepo = RepositoryFactory.CreateAuditRepository(uow))
{
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
}
#region Event Handlers
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> SavingContentTypeContainer;
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> SavedContentTypeContainer;
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<EntityContainer>> DeletingContentTypeContainer;
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<EntityContainer>> DeletedContentTypeContainer;
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> SavingMediaTypeContainer;
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> SavedMediaTypeContainer;
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<EntityContainer>> DeletingMediaTypeContainer;
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<EntityContainer>> DeletedMediaTypeContainer;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IContentType>> DeletingContentType;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IContentType>> DeletedContentType;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IMediaType>> DeletingMediaType;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IMediaType>> DeletedMediaType;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IContentType>> SavingContentType;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IContentType>> SavedContentType;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IMediaType>> SavingMediaType;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IMediaType>> SavedMediaType;
/// <summary>
/// Occurs before Move
/// </summary>
public static event TypedEventHandler<IContentTypeService, MoveEventArgs<IMediaType>> MovingMediaType;
/// <summary>
/// Occurs after Move
/// </summary>
public static event TypedEventHandler<IContentTypeService, MoveEventArgs<IMediaType>> MovedMediaType;
/// <summary>
/// Occurs before Move
/// </summary>
public static event TypedEventHandler<IContentTypeService, MoveEventArgs<IContentType>> MovingContentType;
/// <summary>
/// Occurs after Move
/// </summary>
public static event TypedEventHandler<IContentTypeService, MoveEventArgs<IContentType>> MovedContentType;
#endregion
}
}
| |
namespace Lex
{
/*
* Class: Minimize
*/
using System;
using System.Collections;
public class Minimize
{
/*
* Member Variables
*/
Spec spec;
ArrayList group;
int[] ingroup;
/*
* Function: Minimize
* Description: Constructor.
*/
public Minimize()
{
reset();
}
/*
* Function: reset
* Description: Resets member variables.
*/
private void reset()
{
spec = null;
group = null;
ingroup = null;
}
/*
* Function: set
* Description: Sets member variables.
*/
private void set(Spec s)
{
#if DEBUG
Utility.assert(null != s);
#endif
spec = s;
group = null;
ingroup = null;
}
/*
* Function: min_dfa
* Description: High-level access function to module.
*/
public void min_dfa(Spec s)
{
set(s);
/* Remove redundant states. */
minimize();
/* Column and row compression.
Save accept states in auxilary vector. */
reduce();
reset();
}
/*
* Function: col_copy
* Description: Copies source column into destination column.
*/
private void col_copy(int dest, int src)
{
int n;
int i;
DTrans d;
n = spec.dtrans_list.Count;
for (i = 0; i < n; ++i)
{
d = (DTrans) spec.dtrans_list[i];
d.SetDTrans(dest, d.GetDTrans(src));
}
}
/*
* Function: row_copy
* Description: Copies source row into destination row.
*/
private void row_copy(int dest, int src)
{
spec.dtrans_list[dest] = spec.dtrans_list[src];
}
/*
* Function: col_equiv
*/
private bool col_equiv(int col1, int col2)
{
int n;
int i;
DTrans d;
n = spec.dtrans_list.Count;
for (i = 0; i < n; ++i)
{
d = (DTrans) spec.dtrans_list[i];
if (d.GetDTrans(col1) != d.GetDTrans(col2))
return false;
}
return true;
}
/*
* Function: row_equiv
*/
private bool row_equiv(int row1, int row2)
{
int i;
DTrans d1;
DTrans d2;
d1 = (DTrans) spec.dtrans_list[row1];
d2 = (DTrans) spec.dtrans_list[row2];
for (i = 0; i < spec.dtrans_ncols; ++i)
{
if (d1.GetDTrans(i) != d2.GetDTrans(i))
return false;
}
return true;
}
/*
* Function: reduce
*/
private void reduce()
{
int i;
int j;
int k;
int nrows;
int reduced_ncols;
int reduced_nrows;
BitArray set;
DTrans d;
int dtrans_size;
/* Save accept nodes and anchor entries. */
dtrans_size = spec.dtrans_list.Count;
set = new BitArray(dtrans_size);
spec.anchor_array = new int[dtrans_size];
spec.accept_list = new ArrayList();
for (i = 0; i < dtrans_size; ++i)
{
d = (DTrans) spec.dtrans_list[i];
spec.accept_list.Add(d.GetAccept());
spec.anchor_array[i] = d.GetAnchor();
d.SetAccept(null);
}
/* Allocate column map. */
spec.col_map = new int[spec.dtrans_ncols];
for (i = 0; i < spec.dtrans_ncols; ++i)
{
spec.col_map[i] = -1;
}
/* Process columns for reduction. */
for (reduced_ncols = 0; ; ++reduced_ncols)
{
#if DEBUG
for (i = 0; i < reduced_ncols; ++i)
{
Utility.assert(-1 != spec.col_map[i]);
}
#endif
for (i = reduced_ncols; i < spec.dtrans_ncols; ++i)
{
if (-1 == spec.col_map[i])
break;
}
if (i >= spec.dtrans_ncols)
break;
if (i >= set.Length)
set.Length = i+1;
#if DEBUG
Utility.assert(false == set.Get(i));
Utility.assert(-1 == spec.col_map[i]);
#endif
set.Set(i, true);
spec.col_map[i] = reduced_ncols;
/* UNDONE: Optimize by doing all comparisons in one batch. */
for (j = i + 1; j < spec.dtrans_ncols; ++j)
{
if (-1 == spec.col_map[j] && true == col_equiv(i,j))
{
spec.col_map[j] = reduced_ncols;
}
}
}
/* Reduce columns. */
k = 0;
for (i = 0; i < spec.dtrans_ncols; ++i)
{
if (i >= set.Length)
set.Length = i+1;
if (set.Get(i))
{
++k;
set.Set(i,false);
j = spec.col_map[i];
#if DEBUG
Utility.assert(j <= i);
#endif
if (j == i)
continue;
col_copy(j,i);
}
}
spec.dtrans_ncols = reduced_ncols;
#if DEBUG
Utility.assert(k == reduced_ncols);
#endif
/* Allocate row map. */
nrows = spec.dtrans_list.Count;
spec.row_map = new int[nrows];
for (i = 0; i < nrows; ++i)
spec.row_map[i] = -1;
/* Process rows to reduce. */
for (reduced_nrows = 0; ; ++reduced_nrows)
{
#if DEBUG
for (i = 0; i < reduced_nrows; ++i)
{
Utility.assert(-1 != spec.row_map[i]);
}
#endif
for (i = reduced_nrows; i < nrows; ++i)
{
if (-1 == spec.row_map[i])
break;
}
if (i >= nrows)
break;
#if DEBUG
Utility.assert(false == set.Get(i));
Utility.assert(-1 == spec.row_map[i]);
#endif
set.Set(i,true);
spec.row_map[i] = reduced_nrows;
/* UNDONE: Optimize by doing all comparisons in one batch. */
for (j = i + 1; j < nrows; ++j)
{
if (-1 == spec.row_map[j] && true == row_equiv(i,j))
{
spec.row_map[j] = reduced_nrows;
}
}
}
/* Reduce rows. */
k = 0;
for (i = 0; i < nrows; ++i)
{
if (set.Get(i))
{
k++;
set.Set(i,false);
j = spec.row_map[i];
#if DEBUG
Utility.assert(j <= i);
#endif
if (j == i)
continue;
row_copy(j,i);
}
}
#if DEBUG
Console.Write("k = " + k + "\nreduced_nrows = " + reduced_nrows + "\n");
Utility.assert(k == reduced_nrows);
#endif
spec.dtrans_list.RemoveRange(reduced_nrows,dtrans_size-reduced_nrows);
}
/*
* Function: fix_dtrans
* Description: Updates CDTrans table after minimization
* using groups, removing redundant transition table states.
*/
private void fix_dtrans()
{
ArrayList new_list;
int i;
int size;
ArrayList dtrans_group;
DTrans first;
int c;
new_list = new ArrayList();
size = spec.state_dtrans.Length;
for (i = 0; i < size; ++i)
{
if (DTrans.F != spec.state_dtrans[i])
{
spec.state_dtrans[i] = ingroup[spec.state_dtrans[i]];
}
}
size = group.Count;
for (i = 0; i < size; ++i)
{
dtrans_group = (ArrayList) group[i];
first = (DTrans) dtrans_group[0];
new_list.Add(first);
for (c = 0; c < spec.dtrans_ncols; c++)
{
if (DTrans.F != first.GetDTrans(c))
{
first.SetDTrans(c, ingroup[first.GetDTrans(c)]);
}
}
}
group = null;
spec.dtrans_list = new_list;
}
/*
* Function: minimize
* Description: Removes redundant transition table states.
*/
private void minimize()
{
ArrayList dtrans_group;
ArrayList new_group;
int i;
int j;
int old_group_count;
int group_count;
DTrans next;
DTrans first;
int goto_first;
int goto_next;
int c;
int group_size;
bool added;
init_groups();
group_count = group.Count;
old_group_count = group_count - 1;
while (old_group_count != group_count)
{
old_group_count = group_count;
#if DEBUG
Utility.assert(group.Count == group_count);
#endif
for (i = 0; i < group_count; ++i)
{
dtrans_group = (ArrayList) group[i];
group_size = dtrans_group.Count;
if (group_size <= 1)
continue;
new_group = new ArrayList();
added = false;
first = (DTrans) dtrans_group[0];
for (j = 1; j < group_size; ++j)
{
next = (DTrans) dtrans_group[j];
for (c = 0; c < spec.dtrans_ncols; ++c)
{
goto_first = first.GetDTrans(c);
goto_next = next.GetDTrans(c);
if (goto_first != goto_next
&& (goto_first == DTrans.F
|| goto_next == DTrans.F
|| ingroup[goto_next] != ingroup[goto_first]))
{
#if DEBUG
Utility.assert(dtrans_group[j] == next);
#endif
dtrans_group.RemoveAt(j);
j--;
group_size--;
new_group.Add(next);
if (!added)
{
added = true;
group_count++;
group.Add(new_group);
}
ingroup[next.GetLabel()] = group.Count - 1;
#if DEBUG
Utility.assert(group.Contains(new_group) == true);
Utility.assert(group.Contains(dtrans_group) == true);
Utility.assert(dtrans_group.Contains(first) == true);
Utility.assert(dtrans_group.Contains(next) == false);
Utility.assert(new_group.Contains(first) == false);
Utility.assert(new_group.Contains(next) == true);
Utility.assert(dtrans_group.Count == group_size);
Utility.assert(i == ingroup[first.GetLabel()]);
Utility.assert((group.Count - 1) == ingroup[next.GetLabel()]);
#endif
break;
}
}
}
}
}
Console.WriteLine(group.Count + " states after removal of redundant states.");
// if (spec.verbose) && Utility.OLD_DUMP_DEBUG)
#if OLD_DUMP_DEBUG
Console.WriteLine("\nStates grouped as follows after minimization");
pgroups();
#endif
fix_dtrans();
}
/*
* Function: init_groups
*/
private void init_groups()
{
bool group_found;
int group_count = 0;
group = new ArrayList();
int size = spec.dtrans_list.Count;
ingroup = new int[size];
for (int i = 0; i < size; ++i)
{
group_found = false;
DTrans dtrans = (DTrans) spec.dtrans_list[i];
#if DEBUG
Utility.assert(i == dtrans.GetLabel());
Utility.assert(false == group_found);
Utility.assert(group_count == group.Count);
#endif
for (int j = 0; j < group_count; j++)
{
ArrayList dtrans_group = (ArrayList) group[j];
#if DEBUG
Utility.assert(false == group_found);
Utility.assert(0 < dtrans_group.Count);
#endif
DTrans first = (DTrans) dtrans_group[0];
#if DEBUG
int s = dtrans_group.Count;
Utility.assert(0 < s);
for (int k = 1; k < s; k++)
{
DTrans check = (DTrans) dtrans_group[k];
Utility.assert(check.GetAccept() == first.GetAccept());
}
#endif
if (first.GetAccept() == dtrans.GetAccept())
{
dtrans_group.Add(dtrans);
ingroup[i] = j;
group_found = true;
#if DEBUG
Utility.assert(j == ingroup[dtrans.GetLabel()]);
#endif
break;
}
}
if (!group_found)
{
ArrayList dtrans_group = new ArrayList();
dtrans_group.Add(dtrans);
ingroup[i] = group.Count;
group.Add(dtrans_group);
group_count++;
}
}
#if OLD_DUMP_DEBUG
Console.WriteLine("Initial grouping:");
pgroups();
Console.WriteLine("");
#endif
}
/*
* Function: pset
*/
private void pset(ArrayList dtrans_group)
{
int size = dtrans_group.Count;
for (int i = 0; i < size; ++i)
{
DTrans dtrans = (DTrans) dtrans_group[i];
Console.Write(dtrans.GetLabel() + " ");
}
}
/*
* Function: pgroups
*/
private void pgroups()
{
int dtrans_size;
int group_size = group.Count;
for (int i = 0; i < group_size; ++i)
{
Console.Write("\tGroup " + i + " {");
pset((ArrayList) group[i]);
Console.WriteLine("}\n");
}
Console.WriteLine("");
dtrans_size = spec.dtrans_list.Count;
for (int i = 0; i < dtrans_size; ++i)
{
Console.WriteLine("\tstate " + i
+ " is in group " + ingroup[i]);
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Used by MockDirectoryWrapper to create an input stream that
/// keeps track of when it's been closed.
/// </summary>
public class MockIndexInputWrapper : IndexInput
{
private MockDirectoryWrapper Dir;
internal readonly string Name;
private IndexInput @delegate;
private bool IsClone;
private bool Closed;
/// <summary>
/// Construct an empty output buffer. </summary>
public MockIndexInputWrapper(MockDirectoryWrapper dir, string name, IndexInput @delegate)
: base("MockIndexInputWrapper(name=" + name + " delegate=" + @delegate + ")")
{
this.Name = name;
this.Dir = dir;
this.@delegate = @delegate;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
// turn on the following to look for leaks closing inputs,
// after fixing TestTransactions
// Dir.MaybeThrowDeterministicException();
}
finally
{
Closed = true;
@delegate.Dispose();
// Pending resolution on LUCENE-686 we may want to
// remove the conditional check so we also track that
// all clones get closed:
if (!IsClone)
{
Dir.RemoveIndexInput(this, Name);
}
}
}
}
private void EnsureOpen()
{
if (Closed)
{
throw new Exception("Abusing closed IndexInput!");
}
}
public override object Clone()
{
EnsureOpen();
Dir.InputCloneCount_Renamed.IncrementAndGet();
IndexInput iiclone = (IndexInput)@delegate.Clone();
MockIndexInputWrapper clone = new MockIndexInputWrapper(Dir, Name, iiclone);
clone.IsClone = true;
// Pending resolution on LUCENE-686 we may want to
// uncomment this code so that we also track that all
// clones get closed:
/*
synchronized(dir.openFiles) {
if (dir.openFiles.containsKey(name)) {
Integer v = (Integer) dir.openFiles.get(name);
v = Integer.valueOf(v.intValue()+1);
dir.openFiles.put(name, v);
} else {
throw new RuntimeException("BUG: cloned file was not open?");
}
}
*/
return clone;
}
public override long GetFilePointer()
{
EnsureOpen();
return @delegate.GetFilePointer();
}
public override void Seek(long pos)
{
EnsureOpen();
@delegate.Seek(pos);
}
public override long Length
{
get
{
EnsureOpen();
return @delegate.Length;
}
}
public override byte ReadByte()
{
EnsureOpen();
return @delegate.ReadByte();
}
public override void ReadBytes(byte[] b, int offset, int len)
{
EnsureOpen();
@delegate.ReadBytes(b, offset, len);
}
public override void ReadBytes(byte[] b, int offset, int len, bool useBuffer)
{
EnsureOpen();
@delegate.ReadBytes(b, offset, len, useBuffer);
}
/// <summary>
/// NOTE: this was readShort() in Lucene
/// </summary>
public override short ReadInt16()
{
EnsureOpen();
return @delegate.ReadInt16();
}
/// <summary>
/// NOTE: this was readInt() in Lucene
/// </summary>
public override int ReadInt32()
{
EnsureOpen();
return @delegate.ReadInt32();
}
/// <summary>
/// NOTE: this was readLong() in Lucene
/// </summary>
public override long ReadInt64()
{
EnsureOpen();
return @delegate.ReadInt64();
}
public override string ReadString()
{
EnsureOpen();
return @delegate.ReadString();
}
public override IDictionary<string, string> ReadStringStringMap()
{
EnsureOpen();
return @delegate.ReadStringStringMap();
}
/// <summary>
/// NOTE: this was readVInt() in Lucene
/// </summary>
public override int ReadVInt32()
{
EnsureOpen();
return @delegate.ReadVInt32();
}
/// <summary>
/// NOTE: this was readVLong() in Lucene
/// </summary>
public override long ReadVInt64()
{
EnsureOpen();
return @delegate.ReadVInt64();
}
public override string ToString()
{
return "MockIndexInputWrapper(" + @delegate + ")";
}
}
}
| |
#region Using Statements
using System;
using System.Linq;
using System.Threading;
using Microsoft.Web.Administration;
using Cake.Core;
using Cake.Core.Diagnostics;
#endregion
namespace Cake.IIS
{
public class ApplicationPoolManager : BaseManager
{
#region Fields (1)
private static readonly string[] ApplicationPoolBlackList =
{
"DefaultAppPool",
"Classic .NET AppPool",
"ASP.NET v4.0 Classic",
"ASP.NET v4.0"
};
#endregion
#region Constructor (1)
public ApplicationPoolManager(ICakeEnvironment environment, ICakeLog log)
: base(environment, log)
{
}
#endregion
#region Functions (8)
public static ApplicationPoolManager Using(ICakeEnvironment environment, ICakeLog log, ServerManager server)
{
ApplicationPoolManager manager = new ApplicationPoolManager(environment, log);
manager.SetServer(server);
return manager;
}
public void Create(ApplicationPoolSettings settings)
{
if (settings == null)
{
throw new ArgumentNullException("settings");
}
if (string.IsNullOrWhiteSpace(settings.Name))
{
throw new ArgumentException("Application pool name cannot be null!");
}
if (this.IsSystemDefault(settings.Name))
{
return;
}
//Get Pool
var pool = _Server.ApplicationPools.FirstOrDefault(p => p.Name == settings.Name);
if(pool != null)
{
_Log.Information("Application pool '{0}' already exists.", settings.Name);
if(settings.Overwrite)
{
_Log.Information("Application pool '{0}' will be overriden by request.", settings.Name);
this.Delete(settings.Name);
}
else return;
}
//Add Pool
pool = _Server.ApplicationPools.Add(settings.Name);
pool.AutoStart = settings.Autostart;
pool.Enable32BitAppOnWin64 = settings.Enable32BitAppOnWin64;
pool.ManagedRuntimeVersion = settings.ManagedRuntimeVersion;
pool.ManagedPipelineMode = settings.ClassicManagedPipelineMode
? ManagedPipelineMode.Classic
: ManagedPipelineMode.Integrated;
//Set Identity
_Log.Information("Application pool identity type: {0}", settings.IdentityType.ToString());
switch(settings.IdentityType)
{
case IdentityType.LocalSystem:
pool.ProcessModel.IdentityType = ProcessModelIdentityType.LocalSystem;
break;
case IdentityType.LocalService:
pool.ProcessModel.IdentityType = ProcessModelIdentityType.LocalService;
break;
case IdentityType.NetworkService:
pool.ProcessModel.IdentityType = ProcessModelIdentityType.NetworkService;
break;
case IdentityType.ApplicationPoolIdentity:
pool.ProcessModel.IdentityType = ProcessModelIdentityType.ApplicationPoolIdentity;
break;
case IdentityType.SpecificUser:
pool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
pool.ProcessModel.UserName = settings.Username;
pool.ProcessModel.Password = settings.Password;
break;
default:
throw new ArgumentOutOfRangeException();
}
//Set ProcessModel
pool.ProcessModel.LoadUserProfile = settings.LoadUserProfile;
pool.ProcessModel.MaxProcesses = settings.MaxProcesses;
pool.ProcessModel.PingingEnabled = settings.PingingEnabled;
if (settings.PingResponseTime != TimeSpan.MinValue)
{
pool.ProcessModel.PingInterval = settings.PingInterval;
}
if (settings.PingResponseTime != TimeSpan.MinValue)
{
pool.ProcessModel.PingResponseTime = settings.PingResponseTime;
}
if (settings.IdleTimeout != TimeSpan.MinValue)
{
pool.ProcessModel.IdleTimeout = settings.IdleTimeout;
}
if (settings.ShutdownTimeLimit != TimeSpan.MinValue)
{
pool.ProcessModel.ShutdownTimeLimit = settings.ShutdownTimeLimit;
}
if (settings.StartupTimeLimit != TimeSpan.MinValue)
{
pool.ProcessModel.StartupTimeLimit = settings.StartupTimeLimit;
}
_Server.CommitChanges();
_Log.Information("Application pool created.");
}
public bool Delete(string name)
{
if (!this.IsSystemDefault(name))
{
var pool = _Server.ApplicationPools.FirstOrDefault(p => p.Name == name);
if (pool == null)
{
_Log.Information("Application pool '{0}' not found.", name);
return false;
}
else
{
_Server.ApplicationPools.Remove(pool);
_Server.CommitChanges();
_Log.Information("Application pool '{0}' deleted.", pool.Name);
return true;
}
}
else
{
return false;
}
}
public bool Recycle(string name)
{
var pool = _Server.ApplicationPools.FirstOrDefault(p => p.Name == name);
if (pool == null)
{
_Log.Information("Application pool '{0}' not found.", name);
return false;
}
else
{
try
{
pool.Recycle();
}
catch (System.Runtime.InteropServices.COMException)
{
_Log.Information("Waiting for IIS to activate new config");
Thread.Sleep(1000);
}
_Log.Information("Application pool '{0}' recycled.", pool.Name);
return true;
}
}
public bool Start(string name)
{
var pool = _Server.ApplicationPools.FirstOrDefault(p => p.Name == name);
if (pool == null)
{
_Log.Information("Application pool '{0}' not found.", name);
return false;
}
else
{
try
{
pool.Start();
}
catch (System.Runtime.InteropServices.COMException)
{
_Log.Information("Waiting for IIS to activate new config");
Thread.Sleep(1000);
}
_Log.Information("Application pool '{0}' started.", pool.Name);
return true;
}
}
public bool Stop(string name)
{
var pool = _Server.ApplicationPools.FirstOrDefault(p => p.Name == name);
if (pool == null)
{
_Log.Information("Application pool '{0}' not found.", name);
return false;
}
else
{
try
{
pool.Stop();
}
catch (System.Runtime.InteropServices.COMException)
{
_Log.Information("Waiting for IIS to activate new config");
Thread.Sleep(1000);
}
_Log.Information("Application pool '{0}' stopped.", pool.Name);
return true;
}
}
public bool Exists(string name)
{
if (_Server.ApplicationPools.SingleOrDefault(p => p.Name == name) != null)
{
_Log.Information("The ApplicationPool '{0}' exists.", name);
return true;
}
else
{
_Log.Information("The ApplicationPool '{0}' does not exist.", name);
return false;
}
}
public bool IsSystemDefault(string name)
{
if (ApplicationPoolBlackList.Contains(name))
{
return true;
}
_Log.Information("Application pool '{0}' is system's default.", name);
return false;
}
#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 Api.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
namespace Epi.Windows.Globalization.Forms
{
partial class Import
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnFindDataSource = new System.Windows.Forms.Button();
this.cmbDataSourcePlugIns = new System.Windows.Forms.ComboBox();
this.dataGroupBox = new System.Windows.Forms.GroupBox();
this.gbxShow = new System.Windows.Forms.GroupBox();
this.lvDataSourceObjects = new System.Windows.Forms.ListView();
this.columnHeaderItem = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.lblLanguage = new System.Windows.Forms.Label();
this.ddlCultures = new System.Windows.Forms.ComboBox();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.panelMain = new System.Windows.Forms.Panel();
this.txtDataSource = new System.Windows.Forms.TextBox();
this.dataGroupBox.SuspendLayout();
this.gbxShow.SuspendLayout();
this.statusStrip.SuspendLayout();
this.panelMain.SuspendLayout();
this.SuspendLayout();
//
// btnOK
//
this.btnOK.Location = new System.Drawing.Point(252, 351);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 25);
this.btnOK.TabIndex = 2;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.AutoSize = true;
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(333, 351);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 25);
this.btnCancel.TabIndex = 3;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnFindDataSource
//
this.btnFindDataSource.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnFindDataSource.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnFindDataSource.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnFindDataSource.Location = new System.Drawing.Point(6, 45);
this.btnFindDataSource.Name = "btnFindDataSource";
this.btnFindDataSource.Size = new System.Drawing.Size(147, 23);
this.btnFindDataSource.TabIndex = 12;
this.btnFindDataSource.Text = "Connect to Data Source";
this.btnFindDataSource.Click += new System.EventHandler(this.btnFindDataSource_Click);
//
// cmbDataSourcePlugIns
//
this.cmbDataSourcePlugIns.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cmbDataSourcePlugIns.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbDataSourcePlugIns.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
this.cmbDataSourcePlugIns.Location = new System.Drawing.Point(15, 27);
this.cmbDataSourcePlugIns.Name = "cmbDataSourcePlugIns";
this.cmbDataSourcePlugIns.Size = new System.Drawing.Size(234, 21);
this.cmbDataSourcePlugIns.TabIndex = 9;
this.cmbDataSourcePlugIns.Visible = false;
this.cmbDataSourcePlugIns.SelectedIndexChanged += new System.EventHandler(this.cmbDataSourcePlugIns_SelectedIndexChanged);
//
// dataGroupBox
//
this.dataGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGroupBox.Controls.Add(this.txtDataSource);
this.dataGroupBox.Controls.Add(this.btnFindDataSource);
this.dataGroupBox.Location = new System.Drawing.Point(6, 60);
this.dataGroupBox.Name = "dataGroupBox";
this.dataGroupBox.Size = new System.Drawing.Size(402, 80);
this.dataGroupBox.TabIndex = 13;
this.dataGroupBox.TabStop = false;
this.dataGroupBox.Text = "Data Source";
//
// gbxShow
//
this.gbxShow.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.gbxShow.Controls.Add(this.lvDataSourceObjects);
this.gbxShow.Controls.Add(this.cmbDataSourcePlugIns);
this.gbxShow.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.gbxShow.Location = new System.Drawing.Point(6, 146);
this.gbxShow.Name = "gbxShow";
this.gbxShow.Padding = new System.Windows.Forms.Padding(0);
this.gbxShow.Size = new System.Drawing.Size(402, 199);
this.gbxShow.TabIndex = 15;
this.gbxShow.TabStop = false;
this.gbxShow.Text = "Data Source Explorer";
//
// lvDataSourceObjects
//
this.lvDataSourceObjects.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lvDataSourceObjects.BackColor = System.Drawing.SystemColors.Window;
this.lvDataSourceObjects.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeaderItem});
this.lvDataSourceObjects.FullRowSelect = true;
this.lvDataSourceObjects.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.lvDataSourceObjects.Location = new System.Drawing.Point(4, 16);
this.lvDataSourceObjects.MultiSelect = false;
this.lvDataSourceObjects.Name = "lvDataSourceObjects";
this.lvDataSourceObjects.Size = new System.Drawing.Size(392, 172);
this.lvDataSourceObjects.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.lvDataSourceObjects.TabIndex = 1;
this.lvDataSourceObjects.UseCompatibleStateImageBehavior = false;
this.lvDataSourceObjects.View = System.Windows.Forms.View.Details;
this.lvDataSourceObjects.SelectedIndexChanged += new System.EventHandler(this.lvDataSourceObjects_SelectedIndexChanged);
this.lvDataSourceObjects.Resize += new System.EventHandler(this.lvDataSourceObjects_Resize);
//
// columnHeaderItem
//
this.columnHeaderItem.Text = "Item";
this.columnHeaderItem.Width = 300;
//
// lblLanguage
//
this.lblLanguage.Location = new System.Drawing.Point(6, 9);
this.lblLanguage.Name = "lblLanguage";
this.lblLanguage.Size = new System.Drawing.Size(402, 21);
this.lblLanguage.TabIndex = 17;
this.lblLanguage.Text = "Please choose the language or culture to import from the following list:";
//
// ddlCultures
//
this.ddlCultures.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ddlCultures.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ddlCultures.FormattingEnabled = true;
this.ddlCultures.Location = new System.Drawing.Point(9, 33);
this.ddlCultures.Name = "ddlCultures";
this.ddlCultures.Size = new System.Drawing.Size(291, 21);
this.ddlCultures.TabIndex = 16;
this.ddlCultures.SelectedIndexChanged += new System.EventHandler(this.ddlCultures_SelectedIndexChanged);
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel});
this.statusStrip.Location = new System.Drawing.Point(0, 392);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(417, 22);
this.statusStrip.TabIndex = 18;
this.statusStrip.Text = "statusStrip1";
//
// toolStripStatusLabel
//
this.toolStripStatusLabel.Name = "toolStripStatusLabel";
this.toolStripStatusLabel.Overflow = System.Windows.Forms.ToolStripItemOverflow.Always;
this.toolStripStatusLabel.Size = new System.Drawing.Size(0, 17);
//
// panelMain
//
this.panelMain.Controls.Add(this.lblLanguage);
this.panelMain.Controls.Add(this.btnOK);
this.panelMain.Controls.Add(this.ddlCultures);
this.panelMain.Controls.Add(this.btnCancel);
this.panelMain.Controls.Add(this.gbxShow);
this.panelMain.Controls.Add(this.dataGroupBox);
this.panelMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelMain.Location = new System.Drawing.Point(0, 0);
this.panelMain.Name = "panelMain";
this.panelMain.Size = new System.Drawing.Size(417, 414);
this.panelMain.TabIndex = 19;
//
// txtDataSource
//
this.txtDataSource.Location = new System.Drawing.Point(6, 19);
this.txtDataSource.Name = "txtDataSource";
this.txtDataSource.ReadOnly = true;
this.txtDataSource.Size = new System.Drawing.Size(390, 20);
this.txtDataSource.TabIndex = 13;
//
// Import
//
this.AcceptButton = this.btnOK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(417, 414);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.panelMain);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Import";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Import Language Database";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Import_FormClosing);
this.Load += new System.EventHandler(this.Import_Load);
this.dataGroupBox.ResumeLayout(false);
this.dataGroupBox.PerformLayout();
this.gbxShow.ResumeLayout(false);
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.panelMain.ResumeLayout(false);
this.panelMain.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnFindDataSource;
private System.Windows.Forms.ComboBox cmbDataSourcePlugIns;
private System.Windows.Forms.GroupBox dataGroupBox;
private System.Windows.Forms.GroupBox gbxShow;
private System.Windows.Forms.ListView lvDataSourceObjects;
private System.Windows.Forms.ColumnHeader columnHeaderItem;
private System.Windows.Forms.Label lblLanguage;
private System.Windows.Forms.ComboBox ddlCultures;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel;
private System.Windows.Forms.Panel panelMain;
private System.Windows.Forms.TextBox txtDataSource;
}
}
| |
//------------------------------------------------------------------------------
// <copyright company="LeanKit Inc.">
// Copyright (c) LeanKit Inc. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using LeanKit.API.Client.Library.Enumerations;
using LeanKit.API.Client.Library.EventArguments;
using LeanKit.API.Client.Library.Exceptions;
using LeanKit.API.Client.Library.Extensions;
using LeanKit.API.Client.Library.TransferObjects;
namespace LeanKit.API.Client.Library
{
public enum CheckForUpdatesLoopResult
{
Continue,
Exit
}
/// <summary>
/// This class represents a wrapper on top of the LeanKit API that creates a stateful
/// representation of a LeanKit Board. This will allow an integration to manage a board as
/// though it is local to the customer's system.
/// </summary>
public class LeanKitIntegration : ILeanKitIntegration
{
private readonly ILeanKitApi _api;
private readonly long _boardId;
private readonly ReaderWriterLockSlim _boardLock = new ReaderWriterLockSlim();
private readonly IntegrationSettings _integrationSettings;
private Board _board;
private bool _includeTaskboards;
public LeanKitIntegration(long boardId, ILeanKitApi apiClient) : this(boardId, apiClient, new IntegrationSettings())
{
}
public LeanKitIntegration(long boardId, ILeanKitApi apiClient, IntegrationSettings settings)
{
_integrationSettings = settings;
_boardId = boardId;
_api = apiClient;
ShouldContinue = true;
}
public bool ShouldContinue { get; set; }
public event EventHandler<BoardStatusCheckedEventArgs> BoardStatusChecked;
public event EventHandler<BoardInfoRefreshedEventArgs> BoardInfoRefreshed;
public event EventHandler<BoardChangedEventArgs> BoardChanged;
public event EventHandler<ClientErrorEventArgs> ClientError;
public void StartWatching()
{
StartWatching(false);
}
public void StartWatching(bool includeTaskboards)
{
_includeTaskboards = includeTaskboards;
InitBoard();
}
private void InitBoard()
{
//setup the loop intervals
//Probably need to do this on a different thread
do
{
try
{
_boardLock.EnterWriteLock();
_board = _api.GetBoard(_boardId);
//_boardIdentifiers = _api.GetBoardIdentifiers(_boardId);
}
finally
{
_boardLock.ExitWriteLock();
}
} while (SetupCheckForUpdatesLoop() != CheckForUpdatesLoopResult.Exit);
// SetupBoardRefreshLoop();
}
#region Board Monitoring and Event Notifications
public virtual void OnBoardStatusChecked(BoardStatusCheckedEventArgs eventArgs)
{
var eventToRaise = BoardStatusChecked;
if (eventToRaise != null)
eventToRaise(this, eventArgs);
}
public virtual void OnBoardRefresh(BoardInfoRefreshedEventArgs eventArgs)
{
var eventToRaise = BoardInfoRefreshed;
if (eventToRaise != null)
eventToRaise(this, eventArgs);
}
public virtual void OnBoardChanged(BoardChangedEventArgs eventArgs)
{
var eventToRaise = BoardChanged;
if (eventToRaise != null)
eventToRaise(this, eventArgs);
}
public virtual void OnClientError(ClientErrorEventArgs eventArgs)
{
var eventToRaise = ClientError;
if (eventToRaise != null)
eventToRaise(this, eventArgs);
}
private CheckForUpdatesLoopResult SetupCheckForUpdatesLoop()
{
const int pulse = 1000;
var pollingInterval = (long) _integrationSettings.CheckForUpdatesIntervalSeconds*1000;
var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
do
{
if (!stopWatch.IsRunning) stopWatch.Restart();
if (ShouldContinue)
{
while (stopWatch.ElapsedMilliseconds < pollingInterval)
{
if (!ShouldContinue) return CheckForUpdatesLoopResult.Exit;
Thread.Sleep(pulse);
}
}
try
{
stopWatch.Stop();
//Now do the work
var checkResults = _api.CheckForUpdates(_board.Id, _board.Version);
if (checkResults == null) continue;
OnBoardStatusChecked(new BoardStatusCheckedEventArgs {HasChanges = checkResults.HasUpdates});
if (!checkResults.HasUpdates) continue;
try
{
_boardLock.EnterUpgradeableReadLock();
var boardChangedEventArgs = new BoardChangedEventArgs();
if (checkResults.Events.Any(x => x.RequiresBoardRefresh))
{
boardChangedEventArgs.BoardWasReloaded = true;
OnBoardChanged(boardChangedEventArgs);
return CheckForUpdatesLoopResult.Continue;
}
//Now we need to spin through and update the board
//and create the information to event
foreach (var boardEvent in checkResults.Events)
{
try
{
switch (GetEventType(boardEvent.EventType))
{
case EventType.CardCreation:
var addCardEvent = CreateCardAddEvent(boardEvent, checkResults.AffectedLanes);
if (addCardEvent != null) boardChangedEventArgs.AddedCards.Add(addCardEvent);
break;
case EventType.CardMove:
var movedCardEvent = CreateCardMoveEvent(boardEvent, checkResults.AffectedLanes);
if (movedCardEvent != null) boardChangedEventArgs.MovedCards.Add(movedCardEvent);
break;
case EventType.CardFieldsChanged:
var changedFieldsEvent = CreateCardUpdateEvent(boardEvent, checkResults.AffectedLanes);
if (changedFieldsEvent != null) boardChangedEventArgs.UpdatedCards.Add(changedFieldsEvent);
break;
case EventType.CardDeleted:
boardChangedEventArgs.DeletedCards.Add(CreateCardDeletedEvent(boardEvent));
break;
case EventType.CardBlocked:
if (boardEvent.IsBlocked)
boardChangedEventArgs.BlockedCards.Add(CreateCardBlockedEvent(boardEvent,
checkResults.AffectedLanes));
else
boardChangedEventArgs.UnBlockedCards.Add(CreateCardUnBlockedEvent(boardEvent,
checkResults.AffectedLanes));
break;
case EventType.UserAssignment:
if (boardEvent.IsUnassigning)
boardChangedEventArgs.UnAssignedUsers.Add(CreateCardUserUnAssignmentEvent(boardEvent,
checkResults.AffectedLanes));
else
boardChangedEventArgs.AssignedUsers.Add(CreateCardUserAssignmentEvent(boardEvent,
checkResults.AffectedLanes));
break;
case EventType.CommentPost:
boardChangedEventArgs.PostedComments.Add(CreateCommentPostedEvent(boardEvent));
break;
case EventType.WipOverride:
boardChangedEventArgs.WipOverrides.Add(CreateWipOverrideEvent(boardEvent,
checkResults.AffectedLanes));
break;
case EventType.UserWipOverride:
boardChangedEventArgs.UserWipOverrides.Add(CreateUserWipOverrideEvent(boardEvent));
break;
case EventType.AttachmentChange:
var attachmentEvent = CreateAttachmentEvent(boardEvent);
if (attachmentEvent != null) boardChangedEventArgs.AttachmentChangedEvents.Add(attachmentEvent);
break;
case EventType.CardMoveToBoard:
boardChangedEventArgs.CardMoveToBoardEvents.Add(CreateCardMoveToBoardEvent(boardEvent));
break;
case EventType.CardMoveFromBoard:
boardChangedEventArgs.CardMoveFromBoardEvents.Add(CreateCardMoveFromBoardEvent(boardEvent));
break;
case EventType.BoardEdit:
boardChangedEventArgs.BoardEditedEvents.Add(CreateBoardEditedEvent(boardEvent));
boardChangedEventArgs.BoardStructureChanged = true;
break;
case EventType.BoardCardTypesChanged:
boardChangedEventArgs.BoardCardTypesChangedEvents.Add(new BoardCardTypesChangedEvent(boardEvent.EventDateTime));
boardChangedEventArgs.BoardStructureChanged = true;
break;
case EventType.BoardClassOfServiceChanged:
boardChangedEventArgs.BoardClassOfServiceChangedEvents.Add(
new BoardClassOfServiceChangedEvent(boardEvent.EventDateTime));
boardChangedEventArgs.BoardStructureChanged = true;
break;
case EventType.Unrecognized:
//Console.Beep();
break;
}
}
catch (Exception ex)
{
OnClientError(new ClientErrorEventArgs
{
Exception = ex,
Message = "Error processing board change event. " + ex.Message
});
}
}
OnBoardChanged(boardChangedEventArgs);
_boardLock.EnterWriteLock();
try
{
//we need to check to see if there is a need to refresh the entire board
//if so, we need to refresh the entire board and raise the board refreshed event
if (!checkResults.RequiresRefesh())
{
//since the board does not require a refresh, then just change the effected lanes
ApplyBoardChanges(checkResults.CurrentBoardVersion, checkResults.AffectedLanes);
}
else
{
_board = checkResults.NewPayload;
OnBoardRefresh(new BoardInfoRefreshedEventArgs {FromBoardChange = true});
}
}
catch (Exception ex)
{
OnClientError(new ClientErrorEventArgs
{
Exception = ex,
Message = "Error applying board changes or raising board refresh."
});
}
finally
{
_boardLock.ExitWriteLock();
}
}
catch (Exception ex)
{
OnClientError(new ClientErrorEventArgs {Exception = ex, Message = "Error processing board events."});
}
finally
{
_boardLock.ExitUpgradeableReadLock();
}
}
catch (Exception ex)
{
OnClientError(new ClientErrorEventArgs {Exception = ex, Message = "Error checking for board events."});
}
} while (ShouldContinue);
stopWatch.Stop();
return CheckForUpdatesLoopResult.Exit;
}
private void ApplyBoardChanges(long boardVersion, IEnumerable<Lane> affectedLanes)
{
_board.Version = boardVersion;
foreach (Lane affectedLane in affectedLanes)
{
_board.UpdateLane(affectedLane);
}
}
private static CardBlockedEvent CreateCardBlockedEvent(BoardHistoryEvent boardEvent, IEnumerable<Lane> affectedLanes)
{
//Get the effected lanes from the original board
var card = affectedLanes.FindContainedCard(boardEvent.ToLaneId, boardEvent.CardId);
return new CardBlockedEvent(boardEvent.EventDateTime, card, boardEvent.BlockedComment);
}
private static CardUnBlockedEvent CreateCardUnBlockedEvent(BoardHistoryEvent boardEvent,
IEnumerable<Lane> affectedLanes)
{
//Get the effected lanes from the original board
var card = affectedLanes.FindContainedCard(boardEvent.ToLaneId, boardEvent.CardId);
return new CardUnBlockedEvent(boardEvent.EventDateTime, card, boardEvent.BlockedComment);
}
private CardUserAssignmentEvent CreateCardUserAssignmentEvent(BoardHistoryEvent boardEvent,
IEnumerable<Lane> affectedLanes)
{
// Is the card on a taskboard?
if (!_includeTaskboards && !_board.AllLanes().ContainsLane(boardEvent.ToLaneId))
return null;
try
{
var card = affectedLanes.FindContainedCard(boardEvent.ToLaneId, boardEvent.CardId);
var assignedUser = _board.BoardUsers.FindUser(boardEvent.AssignedUserId);
return new CardUserAssignmentEvent(boardEvent.EventDateTime, card, assignedUser);
}
catch (ItemNotFoundException ex)
{
throw new ItemNotFoundException(
string.Format(
"Unable to create Card User Assignment Event for board [{0}], lane [{1}], card [{2}], and user [{3}]. User count: {4}. {5}",
_boardId, boardEvent.ToLaneId, boardEvent.CardId, boardEvent.AssignedUserId, _board.BoardUsers.Count(), ex.Message));
}
}
private CardUserUnAssignmentEvent CreateCardUserUnAssignmentEvent(BoardHistoryEvent boardEvent,
IEnumerable<Lane> affectedLanes)
{
// Is the card on a taskboard?
if (!_includeTaskboards && !_board.AllLanes().ContainsLane(boardEvent.ToLaneId))
return null;
try
{
var card = affectedLanes.FindContainedCard(boardEvent.ToLaneId, boardEvent.CardId);
var unAssignedUser = _board.BoardUsers.FindUser(boardEvent.AssignedUserId);
return new CardUserUnAssignmentEvent(boardEvent.EventDateTime, card, unAssignedUser);
}
catch (ItemNotFoundException ex)
{
throw new ItemNotFoundException(
string.Format(
"Unable to create Card User Unassignment Event for board [{0}], lane [{1}], card [{2}], and user [{3}]. User count: {4}. {5}",
_boardId, boardEvent.ToLaneId, boardEvent.CardId, boardEvent.AssignedUserId, _board.BoardUsers.Count(), ex.Message));
}
}
private CommentPostedEvent CreateCommentPostedEvent(BoardHistoryEvent boardEvent)
{
//since no info in affectedLanes getting card from board
Card affectedCard = _board.GetCardById(boardEvent.CardId);
return new CommentPostedEvent(boardEvent.EventDateTime, affectedCard, boardEvent.CommentText);
}
private WipOverrideEvent CreateWipOverrideEvent(BoardHistoryEvent boardEvent, IEnumerable<Lane> affectedLanes)
{
try
{
Lane affectedLane = affectedLanes.FindLane(boardEvent.WipOverrideLane);
return new WipOverrideEvent(boardEvent.EventDateTime, boardEvent.WipOverrideComment, affectedLane);
}
catch (ItemNotFoundException ex)
{
throw new ItemNotFoundException(
string.Format("Unable to create Wip Override Event for board [{0}] and lane [{1}]. {2}", _boardId,
boardEvent.WipOverrideLane, ex.Message));
}
}
private UserWipOverrideEvent CreateUserWipOverrideEvent(BoardHistoryEvent boardEvent)
{
try
{
User affectedUser = _board.BoardUsers.FindUser(boardEvent.WipOverrideUser);
return new UserWipOverrideEvent(boardEvent.EventDateTime, boardEvent.WipOverrideComment, affectedUser);
}
catch (ItemNotFoundException)
{
throw new ItemNotFoundException(
string.Format("Unable to create User Wip Override Event for board [{0}] and user [{1}]", _boardId,
boardEvent.WipOverrideUser));
}
}
private AttachmentChangedEvent CreateAttachmentEvent(BoardHistoryEvent boardEvent)
{
// Is the card on a taskboard?
if (!_board.AllLanes().ContainsLane(boardEvent.ToLaneId) && !_includeTaskboards)
return null;
var card = _board.AllLanes().FindContainedCard(boardEvent.ToLaneId, boardEvent.CardId);
return new AttachmentChangedEvent(boardEvent.EventDateTime, card, boardEvent.FileName, boardEvent.CommentText,
boardEvent.IsFileBeingDeleted);
}
private CardMoveToBoardEvent CreateCardMoveToBoardEvent(BoardHistoryEvent boardEvent)
{
return new CardMoveToBoardEvent(boardEvent.EventDateTime, boardEvent.CardId, boardEvent.ToLaneId);
}
private CardMoveFromBoardEvent CreateCardMoveFromBoardEvent(BoardHistoryEvent boardEvent)
{
return new CardMoveFromBoardEvent(boardEvent.EventDateTime, boardEvent.CardId, boardEvent.FromLaneId);
}
private CardDeletedEvent CreateCardDeletedEvent(BoardHistoryEvent boardEvent)
{
// Is the card being deleted from a taskboard?
if (!_includeTaskboards && !_board.AllLanes().ContainsLane(boardEvent.ToLaneId))
return null;
var card = (_board.AllLanes().ContainsLane(boardEvent.ToLaneId))
? _board.AllLanes().FindContainedCard(boardEvent.ToLaneId, boardEvent.CardId)
: GetCard(boardEvent.CardId);
return new CardDeletedEvent(boardEvent.EventDateTime, card);
}
private CardMoveEvent CreateCardMoveEvent(BoardHistoryEvent boardEvent, IEnumerable<Lane> affectedLanes)
{
try
{
// Is the card being moved in or to a taskboard?
if (!_board.AllLanes().ContainsLane(boardEvent.ToLaneId) && !_includeTaskboards)
return null;
var fromLaneId = boardEvent.FromLaneId.GetValueOrDefault();
var toLaneId = boardEvent.ToLaneId;
var lanes = affectedLanes as IList<Lane> ?? affectedLanes.ToList();
var fromLane = _board.AllLanes().ContainsLane(fromLaneId)
? _board.AllLanes().FindLane(fromLaneId)
: null;
Lane toLane = null;
CardView affectedCardView = null;
if (lanes.ContainsLane(toLaneId))
{
toLane = lanes.FindLane(toLaneId);
affectedCardView = toLane.Cards.FirstOrDefault(aCard => aCard.Id == boardEvent.CardId);
}
else if (_board.Archive.ContainsLane(toLaneId))
{
toLane = _board.Archive.FindLane(toLaneId);
affectedCardView = GetCard(boardEvent.CardId).ToCardView();
}
// If fromLane or toLane are null, then the card is probably on a taskboard
if (affectedCardView == null || (toLane == null && !_includeTaskboards)) return null;
var card = affectedCardView.ToCard();
return new CardMoveEvent(boardEvent.EventDateTime, fromLane, toLane, card);
}
catch (ItemNotFoundException ex)
{
throw new ItemNotFoundException(
string.Format(
"Unable to create Card Move Event for board [{0}], card [{1}], from lane [{2}] and to lane [{3}]. {4}", _boardId,
boardEvent.CardId, boardEvent.FromLaneId.GetValueOrDefault(), boardEvent.ToLaneId, ex.Message));
}
}
private CardAddEvent CreateCardAddEvent(BoardHistoryEvent boardEvent, IEnumerable<Lane> affectedLanes)
{
try
{
// Is the card being created on a taskboard?
if (!_board.AllLanes().ContainsLane(boardEvent.ToLaneId) && !_includeTaskboards)
return null;
var lanes = affectedLanes as IList<Lane> ?? affectedLanes.ToList();
var addedCard = lanes.ContainsCard(boardEvent.CardId)
? lanes.FindContainedCard(boardEvent.ToLaneId, boardEvent.CardId)
: GetCard(boardEvent.CardId);
return new CardAddEvent(boardEvent.EventDateTime, addedCard);
}
catch (ItemNotFoundException ex)
{
throw new ItemNotFoundException(
string.Format("Unable to create Card Add Event for board [{0}], card [{1}], and to lane [{2}]. {3}", _boardId,
boardEvent.CardId, boardEvent.ToLaneId, ex.Message));
}
}
private CardUpdateEvent CreateCardUpdateEvent(BoardHistoryEvent boardEvent, IEnumerable<Lane> affectedLanes)
{
try
{
// Is the card being updated on a taskboard?
if (!_board.AllLanes().ContainsLane(boardEvent.ToLaneId) && !_includeTaskboards)
return null;
var originalCard = _board.GetCardById(boardEvent.CardId);
if (originalCard == null)
return null;
var lanes = affectedLanes.ToList();
var updatedCard = (lanes.ContainsCard(boardEvent.CardId))
? lanes.FindContainedCard(boardEvent.ToLaneId, boardEvent.CardId)
: GetCard(boardEvent.CardId, true);
return new CardUpdateEvent(boardEvent.EventDateTime, originalCard, updatedCard);
}
catch (ItemNotFoundException ex)
{
throw new ItemNotFoundException(
string.Format("Unable to create Card Update Event for board [{0}], card [{1}], and to lane [{2}]. {3}", _boardId,
boardEvent.CardId, boardEvent.ToLaneId, ex.Message));
}
}
private BoardEditedEvent CreateBoardEditedEvent(BoardHistoryEvent boardEvent)
{
return new BoardEditedEvent(boardEvent.EventDateTime, boardEvent.Message);
}
private static EventType GetEventType(string eventType)
{
eventType = eventType.Replace("LeanKit.Core.Events.", string.Empty).Replace("Event", string.Empty);
EventType candidateEventType;
return Enum.TryParse(eventType, true, out candidateEventType) ? candidateEventType : EventType.Unrecognized;
}
#endregion
#region Pass through calls
/* Pass through API */
public virtual Card GetCard(long cardId)
{
return GetCard(cardId, false);
}
public virtual Card GetCard(long cardId, bool bypassCache)
{
Card card = null;
if (!bypassCache)
{
_boardLock.EnterReadLock();
try
{
card = _board.GetCardById(cardId);
}
finally
{
_boardLock.ExitReadLock();
}
}
if (card != null) return card;
// try getting card directly from the api
var c = _api.GetCard(_boardId, cardId);
card = (c != null) ? c.ToCard() : null;
if (card != null) return card;
//try to find in archive, suppose it is not loaded
var archive = _api.GetArchiveCards(_boardId);
var firstOrDefault = (archive != null) ? archive.FirstOrDefault(x => x.Id == cardId) : null;
if (firstOrDefault != null) card = firstOrDefault.ToCard();
//TODO: need to load the archive
//Also, could be possible that the card is part of the cards older than 90 days
//In that case we my need to do a search too.
if (card == null) throw new ItemNotFoundException();
return card;
}
public Card GetCardByExternalId(long boardId, string externalCardId)
{
Card card;
_boardLock.EnterReadLock();
try
{
card = _board.GetCardByExternalId(externalCardId);
}
finally
{
_boardLock.ExitReadLock();
}
//try to find in archive, suppose it is not loaded
if (card == null)
{
var archive = _api.GetArchiveCards(_boardId).ToList();
var cardView = archive.FirstOrDefault(x => x.ExternalCardID == externalCardId);
card = cardView == null ? null : cardView.ToCard();
//TODO: need to load the archive
//Also, could be possible that the card is part of the cards older than 90 days
//In that case we my need to do a search too.
}
if (card == null) throw new ItemNotFoundException();
return card;
}
public virtual void AddCard(Card card)
{
AddCard(card, string.Empty);
}
public void AddCard(Card card, string wipOverrideReason)
{
var results = string.IsNullOrEmpty(wipOverrideReason)
? _api.AddCard(_boardId, card)
: _api.AddCard(_boardId, card, wipOverrideReason);
_boardLock.EnterWriteLock();
try
{
ApplyBoardChanges(results.BoardVersion, new[] {results.Lane});
}
finally
{
_boardLock.ExitWriteLock();
}
}
public virtual void UpdateCard(Card card)
{
UpdateCard(card, string.Empty);
}
public virtual void UpdateCard(Card card, string wipOverrideReason)
{
var results = string.IsNullOrEmpty(wipOverrideReason)
? _api.UpdateCard(_boardId, card)
: _api.UpdateCard(_boardId, card, wipOverrideReason);
var cardView = results.CardDTO;
var lane = _board.GetLaneById(cardView.LaneId);
//TODO: handle the situation where a card in moved through the Update method
_boardLock.EnterWriteLock();
try
{
lane.UpdateCard(cardView);
ApplyBoardChanges(results.BoardVersion, new[] {lane});
}
finally
{
_boardLock.ExitWriteLock();
}
}
public virtual IEnumerable<Comment> GetComments(long cardId)
{
var card = _board.GetCardById(cardId);
if (card.Comments != null) return card.Comments;
var comments = _api.GetComments(_board.Id, cardId);
card.Comments = new List<Comment>(comments);
return card.Comments;
}
public virtual void PostComment(long cardId, Comment comment)
{
var cardComments = GetComments(cardId).ToList();
cardComments.Add(comment);
_api.PostComment(_board.Id, cardId, comment);
}
public virtual IEnumerable<CardEvent> GetCardHistory(long cardId)
{
//TODO: What is the history has changed, might be better to just go and get the history everytime
var card = _board.GetCardById(cardId);
if (card.HistoryEvents != null) return card.HistoryEvents;
var historyEvents = _api.GetCardHistory(_board.Id, cardId);
card.HistoryEvents = new List<CardEvent>(historyEvents);
return card.HistoryEvents;
}
public virtual void DeleteCard(long cardId)
{
var newVersion = _api.DeleteCard(_board.Id, cardId);
_boardLock.EnterWriteLock();
try
{
_board.ApplyCardDelete(cardId);
_board.Version = newVersion;
}
finally
{
_boardLock.ExitWriteLock();
}
}
public virtual void DeleteCards(IEnumerable<long> cardIds)
{
var cardIdList = cardIds as IList<long> ?? cardIds.ToList();
var results = _api.DeleteCards(_board.Id, cardIdList);
_boardLock.EnterWriteLock();
try
{
foreach (var cardId in cardIdList)
{
_board.ApplyCardDelete(cardId);
}
_board.Version = results.BoardVersion;
}
finally
{
_boardLock.ExitReadLock();
}
}
public virtual IEnumerable<Lane> GetArchive()
{
if (_board.Archive != null && _board.Archive.Count != 0) return _board.Archive;
var hlanes = _api.GetArchiveLanes(_boardId);
_boardLock.EnterWriteLock();
try
{
_board.Archive = hlanes.GetFlatLanes().ToList();
}
finally
{
_boardLock.ExitWriteLock();
}
return _board.Archive;
}
public Board GetBoard()
{
_boardLock.EnterReadLock();
try
{
return _board;
}
finally
{
_boardLock.ExitReadLock();
}
}
public void MoveCard(long cardId, long toLaneId, int position, string wipOverrideReason)
{
var results = string.IsNullOrEmpty(wipOverrideReason)
? _api.MoveCard(_board.Id, cardId, toLaneId, position)
: _api.MoveCard(_board.Id, cardId, toLaneId, position, wipOverrideReason);
_boardLock.EnterWriteLock();
try
{
_board.ApplyCardMove(cardId, toLaneId, position);
_board.Version = results;
}
finally
{
_boardLock.ExitWriteLock();
}
}
public void MoveCard(long cardId, long toLaneId, int position)
{
MoveCard(cardId, toLaneId, position, string.Empty);
}
public IEnumerable<CardView> SearchCards(SearchOptions options)
{
//for now just pass through the Card Search
return _api.SearchCards(_board.Id, options);
}
public Taskboard GetTaskboard(long cardId)
{
return _api.GetTaskboard(_boardId, cardId);
}
public void AddTask(Card task, long cardId)
{
AddTask(task, cardId, string.Empty);
}
public void AddTask(Card task, long cardId, string wipOverrideReason)
{
//var results = string.IsNullOrEmpty(wipOverrideReason)
// ? _api.AddTask(_boardId, cardId, task)
// : _api.AddTask(_boardId, cardId, task, wipOverrideReason);
//_boardLock.EnterWriteLock();
//try {
// //TODO: Figure out what to do for taskboards
// //ApplyBoardChanges(results.BoardVersion, new[] {results.Lane});
//} finally {
// _boardLock.ExitWriteLock();
//}
}
public void UpdateTask(Card task, long cardId)
{
UpdateTask(task, cardId, string.Empty);
}
public void UpdateTask(Card task, long cardId, string wipOverrideReason)
{
//var results = string.IsNullOrEmpty(wipOverrideReason)
// ? _api.UpdateTask(_boardId, cardId, task)
// : _api.UpdateTask(_boardId, cardId, task, wipOverrideReason);
//TODO: Figure out how to handle taskboards
// CardView cardView = results.CardDTO;
// Lane lane = _board.GetLaneById(cardView.LaneId);
//
//TODO: handle the situation where a card in moved through the Update method
//
// _boardLock.EnterWriteLock();
// try {
// lane.UpdateCard(cardView);
// ApplyBoardChanges(results.BoardVersion, new[] { lane });
// }
// finally {
// _boardLock.ExitWriteLock();
// }
}
public void DeleteTask(long taskId, long cardId)
{
// var results = _api.DeleteTask(_boardId, cardId, taskId);
//TODO: Figure out how to handle taskboards
}
public void MoveTask(long taskId, long cardId, long toLaneId, int position)
{
MoveTask(taskId, cardId, toLaneId, position, string.Empty);
}
public void MoveTask(long taskId, long cardId, long toLaneId, int position, string wipOverrideReason)
{
// var results = _api.MoveTask(_boardId, cardId, taskId, toLaneId, position, wipOverrideReason);
//TODO: Figure out how to handle taskboards
}
public IEnumerable<Asset> GetAttachments(long cardId)
{
return _api.GetAttachments(_boardId, cardId);
}
public Asset GetAttachment(long cardId, long attachmentId)
{
return _api.GetAttachment(_boardId, cardId, attachmentId);
}
public void SaveAttachment(long cardId, string fileName, string description, string mimeType, byte[] fileBytes)
{
_api.SaveAttachment(_boardId, cardId, fileName, description, mimeType, fileBytes);
}
public void DeleteAttachment(long cardId, long attachmentId)
{
_api.DeleteAttachment(_boardId, cardId, attachmentId);
}
public DrillThroughStatistics GetDrillThroughStatistics(long boardId, long cardId)
{
return _api.GetDrillThroughStatistics(boardId, cardId);
}
#region obsolete
[Obsolete("Creating taskboards is no longer supported", true)]
public void CreateTaskboard(long cardId, TaskboardTemplateType templateType, long cardContextId)
{
//_boardLock.EnterUpgradeableReadLock();
//try
//{
// var card = _board.GetCardById(cardId);
//
// if (card.CardContexts.Any(cc => cc.Id == cardContextId))
// {
// throw new DuplicateItemException("A taskboard already exists for this Card Context.");
// }
//
// _boardLock.EnterWriteLock();
// try
// {
// var result = _api.CreateTaskboard(_board.Id, cardId, templateType, cardContextId);
// _board.Version = result.BoardVersion;
// }
// finally
// {
// _boardLock.ExitWriteLock();
// }
//}
//finally
//{
// _boardLock.ExitUpgradeableReadLock();
//}
throw new NotImplementedException("Creating taskboards is no longer supported");
}
[Obsolete("Deleting taskboards is no longer supported", true)]
public void DeleteTaskboard(long cardId, long taskboardId)
{
//_boardLock.EnterUpgradeableReadLock();
//try
//{
// var card = _board.GetCardById(cardId);
//
// if (card.CardContexts.All(cc => cc.TaskBoardId != taskboardId))
// {
// throw new ItemNotFoundException(string.Format("Could not find the Taskboard [{0}] for the Card [{1}].", taskboardId, cardId));
// }
//
// _boardLock.EnterWriteLock();
// try
// {
// //TODO: need to determine how to handle taskboards, how to apply the change
// var result = _api.DeleteTaskboard(_board.Id, taskboardId);
// _board.Version = result.BoardVersion;
// }
// finally
// {
// _boardLock.ExitWriteLock();
// }
//}
//finally
//{
// _boardLock.ExitUpgradeableReadLock();
//}
throw new NotImplementedException("Creating taskboards is no longer supported");
}
[Obsolete("Use AddTask instead")]
public void AddTaskboardCard(Card card, long taskboardId)
{
AddTaskboardCard(card, taskboardId, string.Empty);
}
[Obsolete("Use AddTask instead")]
public void AddTaskboardCard(Card card, long taskboardId, string wipOverrideReason)
{
//var results = string.IsNullOrEmpty(wipOverrideReason)
// ? _api.AddTaskboardCard(_boardId, taskboardId, card)
// : _api.AddTaskboardCard(_boardId, taskboardId, card, wipOverrideReason);
//_boardLock.EnterWriteLock();
//try {
// //TODO: Figure out what to do for taskboards
// //ApplyBoardChanges(results.BoardVersion, new[] {results.Lane});
//} finally {
// _boardLock.ExitWriteLock();
//}
}
[Obsolete("Use UpdateTask instead")]
public void UpdateTaskboardCard(Card card, long taskboardId)
{
UpdateTaskboardCard(card, taskboardId, string.Empty);
}
[Obsolete("Use UpdateTask instead")]
public void UpdateTaskboardCard(Card card, long taskboardId, string wipOverrideReason)
{
//var results = string.IsNullOrEmpty(wipOverrideReason)
// ? _api.UpdateTaskboardCard(_boardId, taskboardId, card)
// : _api.UpdateTaskboardCard(_boardId, taskboardId, card, wipOverrideReason);
//TODO: Figure out how to handle taskboards
// CardView cardView = results.CardDTO;
// Lane lane = _board.GetLaneById(cardView.LaneId);
//
//TODO: handle the situation where a card in moved through the Update method
//
// _boardLock.EnterWriteLock();
// try {
// lane.UpdateCard(cardView);
// ApplyBoardChanges(results.BoardVersion, new[] { lane });
// }
// finally {
// _boardLock.ExitWriteLock();
// }
}
[Obsolete("Use DeleteTask instead")]
public void DeleteTaskboardCard(long cardId, long taskboardId)
{
throw new NotImplementedException();
}
[Obsolete("Use MoveTask instead")]
public void MoveTaskboardCard(long cardId, long taskboardId, long toLaneId, int position, string wipOverrideReason)
{
throw new NotImplementedException();
}
[Obsolete("Use MoveTask instead")]
public void MoveTaskboardCard(long cardId, long taskboardId, long toLaneId, int position)
{
throw new NotImplementedException();
}
#endregion
#endregion
}
}
| |
// Copyright (c) 2002-2015 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace SIL.Reporting
{
/// <summary>
/// Helper class that makes it easier to get information out of nested exceptions to
/// display in the UI.
/// </summary>
public static class ExceptionHelper
{
/// <summary>
/// Get the messages from all nested exceptions
/// </summary>
/// <param name="e">The exception</param>
/// <returns>String with the messages of all nested exceptions</returns>
public static string GetAllExceptionMessages(Exception e)
{
var strB = new StringBuilder();
while (e != null)
{
strB.Append("\n\t");
strB.Append(e.Message);
e = e.InnerException;
}
strB.Remove(0, 2); // remove \n\t from beginning
return strB.ToString();
}
/// <summary>
/// Gets the exception types of all nested exceptions.
/// </summary>
/// <param name="e">The exception</param>
/// <returns>String with the types of all nested exceptions. The string has the
/// form type1(type2(type3...)).</returns>
public static string GetExceptionTypes(Exception e)
{
var strB = new StringBuilder();
int nTypes = 0;
while (e != null)
{
if (nTypes > 0)
strB.Append("(");
strB.Append(e.GetType());
nTypes++;
}
for (; nTypes > 1; nTypes--) // don't need ) for first type
strB.Append(")");
return strB.ToString();
}
/// <summary>
/// Gets a string with the stack traces of all nested exceptions. The stack
/// for the inner most exception is displayed first. Each stack is preceded
/// by the exception type, module name, method name and message.
/// </summary>
/// <param name="e">The exception</param>
/// <returns>String with stack traces of all nested exceptions.</returns>
public static string GetAllStackTraces(Exception e)
{
StringBuilder strB = new StringBuilder();
while (e != null)
{
strB = new StringBuilder(
string.Format("Stack trace for {0} in module {1}, {2} ({3}):\n{4}\n\n{5}",
e.GetType().Name, e.Source, e.TargetSite.Name, e.Message, e.StackTrace,
strB));
e = e.InnerException;
}
return strB.ToString();
}
/// <summary>
/// Gets the names of all the target sites of nested exceptions.
/// </summary>
/// <param name="e">The exception</param>
/// <returns>String with the names of all the target sites.</returns>
public static string GetTargetSiteNames(Exception e)
{
StringBuilder strB = new StringBuilder();
int nSite = 0;
while (e != null)
{
if (nSite > 0)
strB.Append("/");
strB.Append(e.TargetSite.Name);
}
return strB.ToString();
}
/// <summary>
/// Gets the inner most exception
/// </summary>
/// <param name="e">The exception</param>
/// <returns>Returns the inner most exception.</returns>
public static Exception GetInnerMostException(Exception e)
{
while (e.InnerException != null)
e = e.InnerException;
return e;
}
/// <summary>
/// Gets the help string.
/// </summary>
/// <param name="e">The exception</param>
/// <returns>The help link</returns>
public static string GetHelpLink(Exception e)
{
string helpLink = string.Empty;
while (e != null)
{
if (!string.IsNullOrEmpty(e.HelpLink))
helpLink = e.HelpLink;
e = e.InnerException;
}
return helpLink;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the hiearchical exception info.
/// </summary>
/// <param name="error">The error.</param>
/// <param name="innerMostException">The inner most exception or null if the error is
/// the inner most exception</param>
/// <returns>A string containing the text of the specified error</returns>
/// ------------------------------------------------------------------------------------
public static string GetHiearchicalExceptionInfo(Exception error,
ref Exception innerMostException)
{
innerMostException = error.InnerException;
var strBldr = new StringBuilder();
strBldr.Append(GetExceptionText(error));
if (error.InnerException != null)
{
strBldr.AppendLine("**Inner Exception:");
strBldr.Append(GetHiearchicalExceptionInfo(error.InnerException, ref innerMostException));
}
return strBldr.ToString();
}
public static string GetExceptionText(Exception error)
{
var strBldr = new StringBuilder();
strBldr.Append("Msg: ");
strBldr.AppendLine(error.Message);
try
{
var comException = error as COMException;
if (comException != null)
{
strBldr.Append("COM message: ");
strBldr.AppendLine(new Win32Exception(comException.ErrorCode).Message);
}
}
catch
{
}
try
{
strBldr.Append("Source: ");
strBldr.AppendLine(error.Source);
}
catch
{
}
try
{
if (error.TargetSite != null)
{
strBldr.Append("Assembly: ");
strBldr.AppendLine(error.TargetSite.DeclaringType.Assembly.FullName);
}
}
catch
{
}
try
{
strBldr.Append("Stack: ");
strBldr.AppendLine(error.StackTrace);
}
catch
{
}
strBldr.AppendFormat("Thread: {0}", Thread.CurrentThread.Name);
strBldr.AppendLine();
strBldr.AppendFormat("Thread UI culture: {0}", Thread.CurrentThread.CurrentUICulture);
strBldr.AppendLine();
strBldr.AppendFormat("Exception: {0}", error.GetType());
strBldr.AppendLine();
try
{
if (error.Data.Count > 0)
{
strBldr.AppendLine("Additional Exception Information:");
foreach (DictionaryEntry de in error.Data)
{
strBldr.AppendFormat("{0}={1}", de.Key, de.Value);
strBldr.AppendLine();
}
}
}
catch
{
}
return strBldr.ToString();
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Executes the action, logging and ignoring any exceptions.
/// </summary>
/// <param name="action">The action.</param>
/// ------------------------------------------------------------------------------------
public static void LogAndIgnoreErrors(Action action)
{
LogAndIgnoreErrors(action, null);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Executes the action, logging and ignoring any exceptions.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="onError">Additional action to perform after logging the error.</param>
/// ------------------------------------------------------------------------------------
public static void LogAndIgnoreErrors(Action action, Action<Exception> onError)
{
try
{
action();
}
catch (Exception e)
{
Logger.WriteError(e);
if (onError != null)
onError(e);
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using System.Globalization;
using Xunit;
public class MessageTests : NLogTestBase
{
[Fact]
public void MessageWithoutPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Fact]
public void MessageRightPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Fact]
public void MessageFixedLengthRightPaddingLeftAlignmentTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3:fixedlength=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01");
}
[Fact]
public void MessageFixedLengthRightPaddingRightAlignmentTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3:fixedlength=true:alignmentOnTruncation=right}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", ":00");
}
[Fact]
public void MessageLeftPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Fact]
public void MessageFixedLengthLeftPaddingLeftAlignmentTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x:fixedlength=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01");
}
[Fact]
public void MessageFixedLengthLeftPaddingRightAlignmentTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x:fixedlength=true:alignmentOnTruncation=right}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", ":00");
}
[Fact]
public void MessageWithExceptionTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog exceptionLoggingOldStyle='true'>
<targets><target name='debug' type='Debug' layout='${message:withException=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
var ex = new InvalidOperationException("Exception message.");
#if !SILVERLIGHT
string newline = Environment.NewLine;
#else
string newline = "\r\n";
#endif
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.DebugException("Foo", ex);
AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString());
#pragma warning restore 0618
logger.Debug(ex, "Foo");
AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString());
logger.Debug( "Foo", ex);
AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString());
}
[Fact]
public void MessageWithExceptionAndCustomSeparatorTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:withException=true:exceptionSeparator=,}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
var ex = new InvalidOperationException("Exception message.");
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.DebugException("Foo", ex);
AssertDebugLastMessage("debug", "Foo," + ex.ToString());
#pragma warning restore 0618
logger.Debug(ex, "Foo");
AssertDebugLastMessage("debug", "Foo," + ex.ToString());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Dynamic.Utils;
namespace System.Linq.Expressions.Interpreter
{
internal sealed class InterpretedFrame
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
[ThreadStatic]
public static InterpretedFrame CurrentFrame;
internal readonly Interpreter Interpreter;
internal InterpretedFrame _parent;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
private int[] _continuations;
private int _continuationIndex;
private int _pendingContinuation;
private object _pendingValue;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
public readonly object[] Data;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
public readonly IStrongBox[] Closure;
public int StackIndex;
public int InstructionIndex;
#if FEATURE_THREAD_ABORT
// When a ThreadAbortException is raised from interpreted code this is the first frame that caught it.
// No handlers within this handler re-abort the current thread when left.
public ExceptionHandler CurrentAbortHandler;
#endif
internal InterpretedFrame(Interpreter interpreter, IStrongBox[] closure)
{
Interpreter = interpreter;
StackIndex = interpreter.LocalCount;
Data = new object[StackIndex + interpreter.Instructions.MaxStackDepth];
int c = interpreter.Instructions.MaxContinuationDepth;
if (c > 0)
{
_continuations = new int[c];
}
Closure = closure;
_pendingContinuation = -1;
_pendingValue = Interpreter.NoValue;
}
public DebugInfo GetDebugInfo(int instructionIndex)
{
return DebugInfo.GetMatchingDebugInfo(Interpreter._debugInfos, instructionIndex);
}
public string Name
{
get { return Interpreter._name; }
}
#region Data Stack Operations
public void Push(object value)
{
Data[StackIndex++] = value;
}
public void Push(bool value)
{
Data[StackIndex++] = value ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
}
public void Push(int value)
{
Data[StackIndex++] = ScriptingRuntimeHelpers.Int32ToObject(value);
}
public void Push(byte value)
{
Data[StackIndex++] = value;
}
public void Push(sbyte value)
{
Data[StackIndex++] = value;
}
public void Push(Int16 value)
{
Data[StackIndex++] = value;
}
public void Push(UInt16 value)
{
Data[StackIndex++] = value;
}
public object Pop()
{
return Data[--StackIndex];
}
internal void SetStackDepth(int depth)
{
StackIndex = Interpreter.LocalCount + depth;
}
public object Peek()
{
return Data[StackIndex - 1];
}
public void Dup()
{
int i = StackIndex;
Data[i] = Data[i - 1];
StackIndex = i + 1;
}
#endregion
#region Stack Trace
public InterpretedFrame Parent
{
get { return _parent; }
}
public static bool IsInterpretedFrame(MethodBase method)
{
//ContractUtils.RequiresNotNull(method, "method");
return method.DeclaringType == typeof(Interpreter) && method.Name == "Run";
}
public IEnumerable<InterpretedFrameInfo> GetStackTraceDebugInfo()
{
var frame = this;
do
{
yield return new InterpretedFrameInfo(frame.Name, frame.GetDebugInfo(frame.InstructionIndex));
frame = frame.Parent;
} while (frame != null);
}
internal void SaveTraceToException(Exception exception)
{
if (exception.Data[typeof(InterpretedFrameInfo)] == null)
{
exception.Data[typeof(InterpretedFrameInfo)] = new List<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray();
}
}
public static InterpretedFrameInfo[] GetExceptionStackTrace(Exception exception)
{
return exception.Data[typeof(InterpretedFrameInfo)] as InterpretedFrameInfo[];
}
#if DEBUG
internal string[] Trace
{
get
{
var trace = new List<string>();
var frame = this;
do
{
trace.Add(frame.Name);
frame = frame.Parent;
} while (frame != null);
return trace.ToArray();
}
}
#endif
internal InterpretedFrame Enter()
{
var currentFrame = CurrentFrame;
CurrentFrame = this;
return _parent = currentFrame;
}
internal void Leave(InterpretedFrame prevFrame)
{
CurrentFrame = prevFrame;
}
#endregion
#region Continuations
internal bool IsJumpHappened()
{
return _pendingContinuation >= 0;
}
public void RemoveContinuation()
{
_continuationIndex--;
}
public void PushContinuation(int continuation)
{
_continuations[_continuationIndex++] = continuation;
}
public int YieldToCurrentContinuation()
{
var target = Interpreter._labels[_continuations[_continuationIndex - 1]];
SetStackDepth(target.StackDepth);
return target.Index - InstructionIndex;
}
/// <summary>
/// Get called from the LeaveFinallyInstruction
/// </summary>
public int YieldToPendingContinuation()
{
Debug.Assert(_pendingContinuation >= 0);
RuntimeLabel pendingTarget = Interpreter._labels[_pendingContinuation];
// the current continuation might have higher priority (continuationIndex is the depth of the current continuation):
if (pendingTarget.ContinuationStackDepth < _continuationIndex)
{
RuntimeLabel currentTarget = Interpreter._labels[_continuations[_continuationIndex - 1]];
SetStackDepth(currentTarget.StackDepth);
return currentTarget.Index - InstructionIndex;
}
SetStackDepth(pendingTarget.StackDepth);
if (_pendingValue != Interpreter.NoValue)
{
Data[StackIndex - 1] = _pendingValue;
}
// Set the _pendingContinuation and _pendingValue to the default values if we finally gets to the Goto target
_pendingContinuation = -1;
_pendingValue = Interpreter.NoValue;
return pendingTarget.Index - InstructionIndex;
}
internal void PushPendingContinuation()
{
Push(_pendingContinuation);
Push(_pendingValue);
_pendingContinuation = -1;
_pendingValue = Interpreter.NoValue;
}
internal void PopPendingContinuation()
{
_pendingValue = Pop();
_pendingContinuation = (int)Pop();
}
public int Goto(int labelIndex, object value, bool gotoExceptionHandler)
{
// TODO: we know this at compile time (except for compiled loop):
RuntimeLabel target = Interpreter._labels[labelIndex];
Debug.Assert(!gotoExceptionHandler || (gotoExceptionHandler && _continuationIndex == target.ContinuationStackDepth),
"When it's time to jump to the exception handler, all previous finally blocks should already be processed");
if (_continuationIndex == target.ContinuationStackDepth)
{
SetStackDepth(target.StackDepth);
if (value != Interpreter.NoValue)
{
Data[StackIndex - 1] = value;
}
return target.Index - InstructionIndex;
}
// if we are in the middle of executing jump we forget the previous target and replace it by a new one:
_pendingContinuation = labelIndex;
_pendingValue = value;
return YieldToCurrentContinuation();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
namespace System.Data.Common
{
public abstract partial class DbDataReader : MarshalByRefObject, IDataReader, IEnumerable
{
protected DbDataReader() : base() { }
public abstract int Depth { get; }
public abstract int FieldCount { get; }
public abstract bool HasRows { get; }
public abstract bool IsClosed { get; }
public abstract int RecordsAffected { get; }
public virtual int VisibleFieldCount => FieldCount;
public abstract object this[int ordinal] { get; }
public abstract object this[string name] { get; }
public virtual void Close() { }
[EditorBrowsable(EditorBrowsableState.Never)]
public void Dispose() => Dispose(true);
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Close();
}
}
public abstract string GetDataTypeName(int ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract IEnumerator GetEnumerator();
public abstract Type GetFieldType(int ordinal);
public abstract string GetName(int ordinal);
public abstract int GetOrdinal(string name);
public virtual DataTable GetSchemaTable()
{
throw new NotSupportedException();
}
public abstract bool GetBoolean(int ordinal);
public abstract byte GetByte(int ordinal);
public abstract long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length);
public abstract char GetChar(int ordinal);
public abstract long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length);
[EditorBrowsable(EditorBrowsableState.Never)]
public DbDataReader GetData(int ordinal) => GetDbDataReader(ordinal);
IDataReader IDataRecord.GetData(int ordinal) => GetDbDataReader(ordinal);
protected virtual DbDataReader GetDbDataReader(int ordinal)
{
throw ADP.NotSupported();
}
public abstract DateTime GetDateTime(int ordinal);
public abstract decimal GetDecimal(int ordinal);
public abstract double GetDouble(int ordinal);
public abstract float GetFloat(int ordinal);
public abstract Guid GetGuid(int ordinal);
public abstract short GetInt16(int ordinal);
public abstract int GetInt32(int ordinal);
public abstract long GetInt64(int ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Type GetProviderSpecificFieldType(int ordinal)
{
// NOTE: This is virtual because not all providers may choose to support
// this method, since it was added in Whidbey.
return GetFieldType(ordinal);
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public virtual object GetProviderSpecificValue(int ordinal)
{
// NOTE: This is virtual because not all providers may choose to support
// this method, since it was added in Whidbey
return GetValue(ordinal);
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public virtual int GetProviderSpecificValues(object[] values) => GetValues(values);
public abstract string GetString(int ordinal);
public virtual Stream GetStream(int ordinal)
{
using (MemoryStream bufferStream = new MemoryStream())
{
long bytesRead = 0;
long bytesReadTotal = 0;
byte[] buffer = new byte[4096];
do
{
bytesRead = GetBytes(ordinal, bytesReadTotal, buffer, 0, buffer.Length);
bufferStream.Write(buffer, 0, (int)bytesRead);
bytesReadTotal += bytesRead;
}
while (bytesRead > 0);
return new MemoryStream(bufferStream.ToArray(), false);
}
}
public virtual TextReader GetTextReader(int ordinal)
{
if (IsDBNull(ordinal))
{
return new StringReader(string.Empty);
}
else
{
return new StringReader(GetString(ordinal));
}
}
public abstract object GetValue(int ordinal);
public virtual T GetFieldValue<T>(int ordinal) => (T)GetValue(ordinal);
public Task<T> GetFieldValueAsync<T>(int ordinal) =>
GetFieldValueAsync<T>(ordinal, CancellationToken.None);
public virtual Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<T>();
}
else
{
try
{
return Task.FromResult<T>(GetFieldValue<T>(ordinal));
}
catch (Exception e)
{
return Task.FromException<T>(e);
}
}
}
public abstract int GetValues(object[] values);
public abstract bool IsDBNull(int ordinal);
public Task<bool> IsDBNullAsync(int ordinal) => IsDBNullAsync(ordinal, CancellationToken.None);
public virtual Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<bool>();
}
else
{
try
{
return IsDBNull(ordinal) ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
return Task.FromException<bool>(e);
}
}
}
public abstract bool NextResult();
public abstract bool Read();
public Task<bool> ReadAsync() => ReadAsync(CancellationToken.None);
public virtual Task<bool> ReadAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<bool>();
}
else
{
try
{
return Read() ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
return Task.FromException<bool>(e);
}
}
}
public Task<bool> NextResultAsync() => NextResultAsync(CancellationToken.None);
public virtual Task<bool> NextResultAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return ADP.CreatedTaskWithCancellation<bool>();
}
else
{
try
{
return NextResult() ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
return Task.FromException<bool>(e);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Linq;
using Xunit;
namespace System.Text.Unicode.Tests
{
public partial class Utf8Tests
{
[Theory]
[InlineData("", "")] // empty string is OK
[InlineData(X_UTF16, X_UTF8)]
[InlineData(E_ACUTE_UTF16, E_ACUTE_UTF8)]
[InlineData(EURO_SYMBOL_UTF16, EURO_SYMBOL_UTF8)]
public void ToBytes_WithSmallValidBuffers(string utf16Input, string expectedUtf8TranscodingHex)
{
// These test cases are for the "slow processing" code path at the end of TranscodeToUtf8,
// so inputs should be less than 2 chars.
Assert.InRange(utf16Input.Length, 0, 1);
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: expectedUtf8TranscodingHex.Length / 2,
replaceInvalidSequences: false,
isFinalChunk: false,
expectedOperationStatus: OperationStatus.Done,
expectedNumCharsRead: utf16Input.Length,
expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex));
}
[Theory]
[InlineData("AB")] // 2 ASCII chars, hits fast inner loop
[InlineData("ABCD")] // 4 ASCII chars, hits fast inner loop
[InlineData("ABCDEF")] // 6 ASCII chars, hits fast inner loop
[InlineData("ABCDEFGH")] // 8 ASCII chars, hits fast inner loop
[InlineData("ABCDEFGHIJ")] // 10 ASCII chars, hits fast inner loop
[InlineData("ABCDEF" + E_ACUTE_UTF16 + "HIJ")] // interrupts inner loop due to non-ASCII char in first char of first DWORD
[InlineData("ABCDEFG" + EURO_SYMBOL_UTF16 + "IJ")] // interrupts inner loop due to non-ASCII char in second char of first DWORD
[InlineData("ABCDEFGH" + E_ACUTE_UTF16 + "J")] // interrupts inner loop due to non-ASCII char in first char of second DWORD
[InlineData("ABCDEFGHI" + EURO_SYMBOL_UTF16)] // interrupts inner loop due to non-ASCII char in second char of second DWORD
[InlineData(X_UTF16 + E_ACUTE_UTF16)] // drains first ASCII char then falls down to slow path
[InlineData(X_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16)] // drains first ASCII char then consumes 2x 2-byte sequences at once
[InlineData(E_ACUTE_UTF16 + X_UTF16)] // no first ASCII char to drain, consumes 2-byte seq followed by ASCII char
[InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16)] // stay within 2x 2-byte sequence processing loop
[InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + X_UTF16)] // break out of 2x 2-byte seq loop due to ASCII data in second char of DWORD
[InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + X_UTF16 + X_UTF16)] // break out of 2x 2-byte seq loop due to ASCII data in first char of DWORD
[InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + EURO_SYMBOL_UTF16)] // break out of 2x 2-byte seq loop due to 3-byte data
[InlineData(E_ACUTE_UTF16 + EURO_SYMBOL_UTF16)] // 2-byte logic sees next char isn't ASCII, cannot read full DWORD from remaining input buffer, falls down to slow drain loop
[InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + X_UTF16)] // 2x 3-byte logic can't read a full DWORD from next part of buffer, falls down to slow drain loop
[InlineData(EURO_SYMBOL_UTF16 + X_UTF16)] // 3-byte processing loop consumes trailing ASCII char, but can't read next DWORD, falls down to slow drain loop
[InlineData(EURO_SYMBOL_UTF16 + X_UTF16 + X_UTF16)] // 3-byte processing loop consumes trailing ASCII char, but can't read next DWORD, falls down to slow drain loop
[InlineData(EURO_SYMBOL_UTF16 + E_ACUTE_UTF16)] // 3-byte processing loop can't consume next ASCII char, can't read DWORD, falls down to slow drain loop
[InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // stay within 2x 3-byte sequence processing loop
[InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + X_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // consume stray ASCII char at beginning of DWORD after 2x 3-byte sequence
[InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + X_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // consume stray ASCII char at end of DWORD after 2x 3-byte sequence
[InlineData(EURO_SYMBOL_UTF16 + E_ACUTE_UTF16 + X_UTF16)] // consume 2-byte sequence as second char in DWORD which begins with 3-byte encoded char
[InlineData(EURO_SYMBOL_UTF16 + GRINNING_FACE_UTF16)] // 3-byte sequence followed by 4-byte sequence
[InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + GRINNING_FACE_UTF16)] // 2x 3-byte sequence followed by 4-byte sequence
[InlineData(GRINNING_FACE_UTF16)] // single 4-byte surrogate char pair
[InlineData(GRINNING_FACE_UTF16 + EURO_SYMBOL_UTF16)] // 4-byte surrogate char pair, cannot read next DWORD, falls down to slow drain loop
public void ToBytes_WithLargeValidBuffers(string utf16Input)
{
// These test cases are for the "fast processing" code which is the main loop of TranscodeToUtf8,
// so inputs should be at least 2 chars.
Assert.True(utf16Input.Length >= 2);
// We're going to run the tests with destination buffer lengths ranging from 0 all the way
// to buffers large enough to hold the full output. This allows us to test logic that
// detects whether we're about to overrun our destination buffer and instead returns DestinationTooSmall.
Rune[] enumeratedScalars = utf16Input.EnumerateRunes().ToArray();
// 0-length buffer test
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: 0,
replaceInvalidSequences: false,
isFinalChunk: false,
expectedOperationStatus: OperationStatus.DestinationTooSmall,
expectedNumCharsRead: 0,
expectedUtf8Transcoding: ReadOnlySpan<byte>.Empty);
int expectedNumCharsConsumed = 0;
byte[] concatenatedUtf8 = Array.Empty<byte>();
for (int i = 0; i < enumeratedScalars.Length; i++)
{
Rune thisScalar = enumeratedScalars[i];
// provide partial destination buffers all the way up to (but not including) enough to hold the next full scalar encoding
for (int j = 1; j < thisScalar.Utf8SequenceLength; j++)
{
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: concatenatedUtf8.Length + j,
replaceInvalidSequences: false,
isFinalChunk: false,
expectedOperationStatus: OperationStatus.DestinationTooSmall,
expectedNumCharsRead: expectedNumCharsConsumed,
expectedUtf8Transcoding: concatenatedUtf8);
}
// now provide a destination buffer large enough to hold the next full scalar encoding
expectedNumCharsConsumed += thisScalar.Utf16SequenceLength;
concatenatedUtf8 = concatenatedUtf8.Concat(ToUtf8(thisScalar)).ToArray();
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: concatenatedUtf8.Length,
replaceInvalidSequences: false,
isFinalChunk: false,
expectedOperationStatus: (i == enumeratedScalars.Length - 1) ? OperationStatus.Done : OperationStatus.DestinationTooSmall,
expectedNumCharsRead: expectedNumCharsConsumed,
expectedUtf8Transcoding: concatenatedUtf8);
}
// now throw lots of ASCII data at the beginning so that we exercise the vectorized code paths
utf16Input = new string('x', 64) + utf16Input;
concatenatedUtf8 = utf16Input.EnumerateRunes().SelectMany(ToUtf8).ToArray();
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: concatenatedUtf8.Length,
replaceInvalidSequences: false,
isFinalChunk: true,
expectedOperationStatus: OperationStatus.Done,
expectedNumCharsRead: utf16Input.Length,
expectedUtf8Transcoding: concatenatedUtf8);
// now throw some non-ASCII data at the beginning so that we *don't* exercise the vectorized code paths
utf16Input = WOMAN_CARTWHEELING_MEDSKIN_UTF16 + utf16Input[64..];
concatenatedUtf8 = utf16Input.EnumerateRunes().SelectMany(ToUtf8).ToArray();
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: concatenatedUtf8.Length,
replaceInvalidSequences: false,
isFinalChunk: true,
expectedOperationStatus: OperationStatus.Done,
expectedNumCharsRead: utf16Input.Length,
expectedUtf8Transcoding: concatenatedUtf8);
}
[Theory]
[InlineData('\uD800', OperationStatus.NeedMoreData)] // standalone high surrogate
[InlineData('\uDFFF', OperationStatus.InvalidData)] // standalone low surrogate
public void ToBytes_WithOnlyStandaloneSurrogates(char charValue, OperationStatus expectedOperationStatus)
{
ToBytes_Test_Core(
utf16Input: new[] { charValue },
destinationSize: 0,
replaceInvalidSequences: false,
isFinalChunk: false,
expectedOperationStatus: expectedOperationStatus,
expectedNumCharsRead: 0,
expectedUtf8Transcoding: Span<byte>.Empty);
}
[Theory]
[InlineData("<LOW><HIGH>", 0, "")] // swapped surrogate pair characters
[InlineData("A<LOW><HIGH>", 1, "41")] // consume standalone ASCII char, then swapped surrogate pair characters
[InlineData("A<HIGH>B", 1, "41")] // consume standalone ASCII char, then standalone high surrogate char
[InlineData("A<LOW>B", 1, "41")] // consume standalone ASCII char, then standalone low surrogate char
[InlineData("AB<HIGH><HIGH>", 2, "4142")] // consume two ASCII chars, then standalone high surrogate char
[InlineData("AB<LOW><LOW>", 2, "4142")] // consume two ASCII chars, then standalone low surrogate char
public void ToBytes_WithInvalidSurrogates(string utf16Input, int expectedNumCharsConsumed, string expectedUtf8TranscodingHex)
{
// xUnit can't handle ill-formed strings in [InlineData], so we replace here.
utf16Input = utf16Input.Replace("<HIGH>", "\uD800").Replace("<LOW>", "\uDFFF");
// These test cases are for the "fast processing" code which is the main loop of TranscodeToUtf8,
// so inputs should be at least 2 chars.
Assert.True(utf16Input.Length >= 2);
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: expectedUtf8TranscodingHex.Length / 2,
replaceInvalidSequences: false,
isFinalChunk: false,
expectedOperationStatus: OperationStatus.InvalidData,
expectedNumCharsRead: expectedNumCharsConsumed,
expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex));
// Now try the tests again with a larger buffer.
// This ensures that running out of destination space wasn't the reason we failed.
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: (expectedUtf8TranscodingHex.Length) / 2 + 16,
replaceInvalidSequences: false,
isFinalChunk: false,
expectedOperationStatus: OperationStatus.InvalidData,
expectedNumCharsRead: expectedNumCharsConsumed,
expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex));
}
[Theory]
[InlineData("<LOW><HIGH>", REPLACEMENT_CHAR_UTF8)] // standalone low surr. and incomplete high surr.
[InlineData("<HIGH><HIGH>", REPLACEMENT_CHAR_UTF8)] // standalone high surr. and incomplete high surr.
[InlineData("<LOW><LOW>", REPLACEMENT_CHAR_UTF8 + REPLACEMENT_CHAR_UTF8)] // standalone low surr. and incomplete low surr.
[InlineData("A<LOW>B<LOW>C<HIGH>D", "41" + REPLACEMENT_CHAR_UTF8 + "42" + REPLACEMENT_CHAR_UTF8 + "43" + REPLACEMENT_CHAR_UTF8 + "44")] // standalone low, low, high surrounded by other data
public void ToBytes_WithReplacements(string utf16Input, string expectedUtf8TranscodingHex)
{
// xUnit can't handle ill-formed strings in [InlineData], so we replace here.
utf16Input = utf16Input.Replace("<HIGH>", "\uD800").Replace("<LOW>", "\uDFFF");
bool isFinalCharHighSurrogate = char.IsHighSurrogate(utf16Input.Last());
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: expectedUtf8TranscodingHex.Length / 2,
replaceInvalidSequences: true,
isFinalChunk: false,
expectedOperationStatus: (isFinalCharHighSurrogate) ? OperationStatus.NeedMoreData : OperationStatus.Done,
expectedNumCharsRead: (isFinalCharHighSurrogate) ? (utf16Input.Length - 1) : utf16Input.Length,
expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex));
if (isFinalCharHighSurrogate)
{
// Also test with isFinalChunk = true
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: expectedUtf8TranscodingHex.Length / 2 + Rune.ReplacementChar.Utf8SequenceLength /* for replacement char */,
replaceInvalidSequences: true,
isFinalChunk: true,
expectedOperationStatus: OperationStatus.Done,
expectedNumCharsRead: utf16Input.Length,
expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex + REPLACEMENT_CHAR_UTF8));
}
}
[Theory]
[InlineData(E_ACUTE_UTF16 + "<LOW>", true, 1, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8)] // not enough output buffer to hold U+FFFD
[InlineData(E_ACUTE_UTF16 + "<LOW>", true, 2, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // replace standalone low surr. at end
[InlineData(E_ACUTE_UTF16 + "<HIGH>", true, 1, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8)] // not enough output buffer to hold U+FFFD
[InlineData(E_ACUTE_UTF16 + "<HIGH>", true, 2, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // replace standalone high surr. at end
[InlineData(E_ACUTE_UTF16 + "<HIGH>", false, 1, OperationStatus.NeedMoreData, E_ACUTE_UTF8)] // don't replace standalone high surr. at end
[InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, true, 2, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // not enough output buffer to hold 'X'
[InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, false, 2, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // not enough output buffer to hold 'X'
[InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, true, 3, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8 + X_UTF8)] // replacement followed by 'X'
[InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, false, 3, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8 + X_UTF8)] // replacement followed by 'X'
public void ToBytes_WithReplacements_AndCustomBufferSizes(string utf16Input, bool isFinalChunk, int expectedNumCharsConsumed, OperationStatus expectedOperationStatus, string expectedUtf8TranscodingHex)
{
// xUnit can't handle ill-formed strings in [InlineData], so we replace here.
utf16Input = utf16Input.Replace("<HIGH>", "\uD800").Replace("<LOW>", "\uDFFF");
ToBytes_Test_Core(
utf16Input: utf16Input,
destinationSize: expectedUtf8TranscodingHex.Length / 2,
replaceInvalidSequences: true,
isFinalChunk: isFinalChunk,
expectedOperationStatus: expectedOperationStatus,
expectedNumCharsRead: expectedNumCharsConsumed,
expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex));
}
[Fact]
public void ToBytes_AllPossibleScalarValues()
{
ToBytes_Test_Core(
utf16Input: s_allScalarsAsUtf16.Span,
destinationSize: s_allScalarsAsUtf8.Length,
replaceInvalidSequences: false,
isFinalChunk: false,
expectedOperationStatus: OperationStatus.Done,
expectedNumCharsRead: s_allScalarsAsUtf16.Length,
expectedUtf8Transcoding: s_allScalarsAsUtf8.Span);
}
private static void ToBytes_Test_Core(ReadOnlySpan<char> utf16Input, int destinationSize, bool replaceInvalidSequences, bool isFinalChunk, OperationStatus expectedOperationStatus, int expectedNumCharsRead, ReadOnlySpan<byte> expectedUtf8Transcoding)
{
// Arrange
using (BoundedMemory<char> boundedSource = BoundedMemory.AllocateFromExistingData(utf16Input))
using (BoundedMemory<byte> boundedDestination = BoundedMemory.Allocate<byte>(destinationSize))
{
boundedSource.MakeReadonly();
// Act
OperationStatus actualOperationStatus = Utf8.FromUtf16(boundedSource.Span, boundedDestination.Span, out int actualNumCharsRead, out int actualNumBytesWritten, replaceInvalidSequences, isFinalChunk);
// Assert
Assert.Equal(expectedOperationStatus, actualOperationStatus);
Assert.Equal(expectedNumCharsRead, actualNumCharsRead);
Assert.Equal(expectedUtf8Transcoding.Length, actualNumBytesWritten);
Assert.Equal(expectedUtf8Transcoding.ToArray(), boundedDestination.Span.Slice(0, actualNumBytesWritten).ToArray());
}
}
}
}
| |
/**
* Couchbase Lite for .NET
*
* Original iOS version by Jens Alfke
* Android Port by Marty Schoch, Traun Leyden
* C# Port by Zack Gramana
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
* Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System.Collections;
using System.Collections.Generic;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using NUnit.Framework;
using Sharpen;
namespace Couchbase.Lite
{
public class RevTreeTest : LiteTestCase
{
public const string Tag = "RevTree";
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
public virtual void TestForceInsertEmptyHistory()
{
IList<string> revHistory = null;
RevisionInternal rev = new RevisionInternal("FakeDocId", "1-tango", false, database
);
IDictionary<string, object> revProperties = new Dictionary<string, object>();
revProperties.Put("_id", rev.GetDocId());
revProperties.Put("_rev", rev.GetRevId());
revProperties.Put("message", "hi");
rev.SetProperties(revProperties);
database.ForceInsert(rev, revHistory, null);
}
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
public virtual void TestRevTree()
{
RevisionInternal rev = new RevisionInternal("MyDocId", "4-foxy", false, database);
IDictionary<string, object> revProperties = new Dictionary<string, object>();
revProperties.Put("_id", rev.GetDocId());
revProperties.Put("_rev", rev.GetRevId());
revProperties.Put("message", "hi");
rev.SetProperties(revProperties);
IList<string> revHistory = new AList<string>();
revHistory.AddItem(rev.GetRevId());
revHistory.AddItem("3-thrice");
revHistory.AddItem("2-too");
revHistory.AddItem("1-won");
database.ForceInsert(rev, revHistory, null);
NUnit.Framework.Assert.AreEqual(1, database.GetDocumentCount());
VerifyHistory(database, rev, revHistory);
RevisionInternal conflict = new RevisionInternal("MyDocId", "5-epsilon", false, database
);
IDictionary<string, object> conflictProperties = new Dictionary<string, object>();
conflictProperties.Put("_id", conflict.GetDocId());
conflictProperties.Put("_rev", conflict.GetRevId());
conflictProperties.Put("message", "yo");
conflict.SetProperties(conflictProperties);
IList<string> conflictHistory = new AList<string>();
conflictHistory.AddItem(conflict.GetRevId());
conflictHistory.AddItem("4-delta");
conflictHistory.AddItem("3-gamma");
conflictHistory.AddItem("2-too");
conflictHistory.AddItem("1-won");
IList wasInConflict = new ArrayList();
Database.ChangeListener listener = new _ChangeListener_84(wasInConflict);
database.AddChangeListener(listener);
database.ForceInsert(conflict, conflictHistory, null);
NUnit.Framework.Assert.IsTrue(wasInConflict.Count > 0);
database.RemoveChangeListener(listener);
NUnit.Framework.Assert.AreEqual(1, database.GetDocumentCount());
VerifyHistory(database, conflict, conflictHistory);
// Add an unrelated document:
RevisionInternal other = new RevisionInternal("AnotherDocID", "1-ichi", false, database
);
IDictionary<string, object> otherProperties = new Dictionary<string, object>();
otherProperties.Put("language", "jp");
other.SetProperties(otherProperties);
IList<string> otherHistory = new AList<string>();
otherHistory.AddItem(other.GetRevId());
database.ForceInsert(other, otherHistory, null);
// Fetch one of those phantom revisions with no body:
RevisionInternal rev2 = database.GetDocumentWithIDAndRev(rev.GetDocId(), "2-too",
EnumSet.NoneOf<Database.TDContentOptions>());
NUnit.Framework.Assert.AreEqual(rev.GetDocId(), rev2.GetDocId());
NUnit.Framework.Assert.AreEqual("2-too", rev2.GetRevId());
//Assert.assertNull(rev2.getContent());
// Make sure no duplicate rows were inserted for the common revisions:
NUnit.Framework.Assert.AreEqual(8, database.GetLastSequenceNumber());
// Make sure the revision with the higher revID wins the conflict:
RevisionInternal current = database.GetDocumentWithIDAndRev(rev.GetDocId(), null,
EnumSet.NoneOf<Database.TDContentOptions>());
NUnit.Framework.Assert.AreEqual(conflict, current);
// Get the _changes feed and verify only the winner is in it:
ChangesOptions options = new ChangesOptions();
RevisionList changes = database.ChangesSince(0, options, null);
RevisionList expectedChanges = new RevisionList();
expectedChanges.AddItem(conflict);
expectedChanges.AddItem(other);
NUnit.Framework.Assert.AreEqual(changes, expectedChanges);
options.SetIncludeConflicts(true);
changes = database.ChangesSince(0, options, null);
expectedChanges = new RevisionList();
expectedChanges.AddItem(rev);
expectedChanges.AddItem(conflict);
expectedChanges.AddItem(other);
NUnit.Framework.Assert.AreEqual(changes, expectedChanges);
}
private sealed class _ChangeListener_84 : Database.ChangeListener
{
public _ChangeListener_84(IList wasInConflict)
{
this.wasInConflict = wasInConflict;
}
public void Changed(Database.ChangeEvent @event)
{
if (@event.GetChanges()[0].IsConflict())
{
wasInConflict.AddItem(new object());
}
}
private readonly IList wasInConflict;
}
/// <summary>
/// Test that the public API works as expected in change notifications after a rev tree
/// insertion.
/// </summary>
/// <remarks>
/// Test that the public API works as expected in change notifications after a rev tree
/// insertion. See https://github.com/couchbase/couchbase-lite-android-core/pull/27
/// </remarks>
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
public virtual void TestRevTreeChangeNotifications()
{
string DocumentId = "MyDocId";
// add a document with a single (first) revision
RevisionInternal rev = new RevisionInternal(DocumentId, "1-one", false, database);
IDictionary<string, object> revProperties = new Dictionary<string, object>();
revProperties.Put("_id", rev.GetDocId());
revProperties.Put("_rev", rev.GetRevId());
revProperties.Put("message", "hi");
rev.SetProperties(revProperties);
IList<string> revHistory = Arrays.AsList(rev.GetRevId());
Database.ChangeListener listener = new _ChangeListener_154(this, DocumentId, rev);
database.AddChangeListener(listener);
database.ForceInsert(rev, revHistory, null);
database.RemoveChangeListener(listener);
// add two more revisions to the document
RevisionInternal rev3 = new RevisionInternal(DocumentId, "3-three", false, database
);
IDictionary<string, object> rev3Properties = new Dictionary<string, object>();
rev3Properties.Put("_id", rev3.GetDocId());
rev3Properties.Put("_rev", rev3.GetRevId());
rev3Properties.Put("message", "hi again");
rev3.SetProperties(rev3Properties);
IList<string> rev3History = Arrays.AsList(rev3.GetRevId(), "2-two", rev.GetRevId(
));
listener = new _ChangeListener_182(this, DocumentId, rev3);
database.AddChangeListener(listener);
database.ForceInsert(rev3, rev3History, null);
database.RemoveChangeListener(listener);
// add a conflicting revision, with the same history length as the last revision we
// inserted. Since this new revision's revID has a higher ASCII sort, it should become the
// new winning revision.
RevisionInternal conflictRev = new RevisionInternal(DocumentId, "3-winner", false
, database);
IDictionary<string, object> conflictProperties = new Dictionary<string, object>();
conflictProperties.Put("_id", conflictRev.GetDocId());
conflictProperties.Put("_rev", conflictRev.GetRevId());
conflictProperties.Put("message", "winner");
conflictRev.SetProperties(conflictProperties);
IList<string> conflictRevHistory = Arrays.AsList(conflictRev.GetRevId(), "2-two",
rev.GetRevId());
listener = new _ChangeListener_217(this, DocumentId, conflictRev);
database.AddChangeListener(listener);
database.ForceInsert(conflictRev, conflictRevHistory, null);
database.RemoveChangeListener(listener);
}
private sealed class _ChangeListener_154 : Database.ChangeListener
{
public _ChangeListener_154(RevTreeTest _enclosing, string DocumentId, RevisionInternal
rev)
{
this._enclosing = _enclosing;
this.DocumentId = DocumentId;
this.rev = rev;
}
public void Changed(Database.ChangeEvent @event)
{
NUnit.Framework.Assert.AreEqual(1, @event.GetChanges().Count);
DocumentChange change = @event.GetChanges()[0];
NUnit.Framework.Assert.AreEqual(DocumentId, change.GetDocumentId());
NUnit.Framework.Assert.AreEqual(rev.GetRevId(), change.GetRevisionId());
NUnit.Framework.Assert.IsTrue(change.IsCurrentRevision());
NUnit.Framework.Assert.IsFalse(change.IsConflict());
SavedRevision current = this._enclosing.database.GetDocument(change.GetDocumentId
()).GetCurrentRevision();
NUnit.Framework.Assert.AreEqual(rev.GetRevId(), current.GetId());
}
private readonly RevTreeTest _enclosing;
private readonly string DocumentId;
private readonly RevisionInternal rev;
}
private sealed class _ChangeListener_182 : Database.ChangeListener
{
public _ChangeListener_182(RevTreeTest _enclosing, string DocumentId, RevisionInternal
rev3)
{
this._enclosing = _enclosing;
this.DocumentId = DocumentId;
this.rev3 = rev3;
}
public void Changed(Database.ChangeEvent @event)
{
NUnit.Framework.Assert.AreEqual(1, @event.GetChanges().Count);
DocumentChange change = @event.GetChanges()[0];
NUnit.Framework.Assert.AreEqual(DocumentId, change.GetDocumentId());
NUnit.Framework.Assert.AreEqual(rev3.GetRevId(), change.GetRevisionId());
NUnit.Framework.Assert.IsTrue(change.IsCurrentRevision());
NUnit.Framework.Assert.IsFalse(change.IsConflict());
Document doc = this._enclosing.database.GetDocument(change.GetDocumentId());
NUnit.Framework.Assert.AreEqual(rev3.GetRevId(), doc.GetCurrentRevisionId());
try
{
NUnit.Framework.Assert.AreEqual(3, doc.GetRevisionHistory().Count);
}
catch (CouchbaseLiteException ex)
{
Assert.Fail("CouchbaseLiteException in change listener: " + ex.ToString());
}
}
private readonly RevTreeTest _enclosing;
private readonly string DocumentId;
private readonly RevisionInternal rev3;
}
private sealed class _ChangeListener_217 : Database.ChangeListener
{
public _ChangeListener_217(RevTreeTest _enclosing, string DocumentId, RevisionInternal
conflictRev)
{
this._enclosing = _enclosing;
this.DocumentId = DocumentId;
this.conflictRev = conflictRev;
}
public void Changed(Database.ChangeEvent @event)
{
NUnit.Framework.Assert.AreEqual(1, @event.GetChanges().Count);
DocumentChange change = @event.GetChanges()[0];
NUnit.Framework.Assert.AreEqual(DocumentId, change.GetDocumentId());
NUnit.Framework.Assert.AreEqual(conflictRev.GetRevId(), change.GetRevisionId());
NUnit.Framework.Assert.IsTrue(change.IsCurrentRevision());
NUnit.Framework.Assert.IsTrue(change.IsConflict());
Document doc = this._enclosing.database.GetDocument(change.GetDocumentId());
NUnit.Framework.Assert.AreEqual(conflictRev.GetRevId(), doc.GetCurrentRevisionId(
));
try
{
NUnit.Framework.Assert.AreEqual(2, doc.GetConflictingRevisions().Count);
NUnit.Framework.Assert.AreEqual(3, doc.GetRevisionHistory().Count);
}
catch (CouchbaseLiteException ex)
{
Assert.Fail("CouchbaseLiteException in change listener: " + ex.ToString());
}
}
private readonly RevTreeTest _enclosing;
private readonly string DocumentId;
private readonly RevisionInternal conflictRev;
}
private static void VerifyHistory(Database db, RevisionInternal rev, IList<string
> history)
{
RevisionInternal gotRev = db.GetDocumentWithIDAndRev(rev.GetDocId(), null, EnumSet
.NoneOf<Database.TDContentOptions>());
NUnit.Framework.Assert.AreEqual(rev, gotRev);
NUnit.Framework.Assert.AreEqual(rev.GetProperties(), gotRev.GetProperties());
IList<RevisionInternal> revHistory = db.GetRevisionHistory(gotRev);
NUnit.Framework.Assert.AreEqual(history.Count, revHistory.Count);
for (int i = 0; i < history.Count; i++)
{
RevisionInternal hrev = revHistory[i];
NUnit.Framework.Assert.AreEqual(rev.GetDocId(), hrev.GetDocId());
NUnit.Framework.Assert.AreEqual(history[i], hrev.GetRevId());
NUnit.Framework.Assert.IsFalse(rev.IsDeleted());
}
}
}
}
| |
// 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.Globalization;
namespace System.Net
{
// More sophisticated password cache that stores multiple
// name-password pairs and associates these with host/realm.
public class CredentialCache : ICredentials, ICredentialsByHost, IEnumerable
{
private readonly Dictionary<CredentialKey, NetworkCredential> _cache = new Dictionary<CredentialKey, NetworkCredential>();
private readonly Dictionary<CredentialHostKey, NetworkCredential> _cacheForHosts = new Dictionary<CredentialHostKey, NetworkCredential>();
internal int _version;
private int _numbDefaultCredInCache = 0;
// [thread token optimization] The resulting counter of default credential resided in the cache.
internal bool IsDefaultInCache
{
get
{
return _numbDefaultCredInCache != 0;
}
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.CredentialCache'/> class.
/// </para>
/// </devdoc>
public CredentialCache()
{
}
/// <devdoc>
/// <para>
/// Adds a <see cref='System.Net.NetworkCredential'/> instance to the credential cache.
/// </para>
/// </devdoc>
public void Add(Uri uriPrefix, string authenticationType, NetworkCredential credential)
{
// Parameter validation
if (uriPrefix == null)
{
throw new ArgumentNullException(nameof(uriPrefix));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
++_version;
CredentialKey key = new CredentialKey(uriPrefix, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]");
}
_cache.Add(key, credential);
if (credential is SystemNetworkCredential)
{
++_numbDefaultCredInCache;
}
}
public void Add(string host, int port, string authenticationType, NetworkCredential credential)
{
// Parameter validation
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
if (host.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, "host"));
}
if (port < 0)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
++_version;
CredentialHostKey key = new CredentialHostKey(host, port, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]");
}
_cacheForHosts.Add(key, credential);
if (credential is SystemNetworkCredential)
{
++_numbDefaultCredInCache;
}
}
/// <devdoc>
/// <para>
/// Removes a <see cref='System.Net.NetworkCredential'/> instance from the credential cache.
/// </para>
/// </devdoc>
public void Remove(Uri uriPrefix, string authenticationType)
{
if (uriPrefix == null || authenticationType == null)
{
// These couldn't possibly have been inserted into
// the cache because of the test in Add().
return;
}
++_version;
CredentialKey key = new CredentialKey(uriPrefix, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
}
if (_cache[key] is SystemNetworkCredential)
{
--_numbDefaultCredInCache;
}
_cache.Remove(key);
}
public void Remove(string host, int port, string authenticationType)
{
if (host == null || authenticationType == null)
{
// These couldn't possibly have been inserted into
// the cache because of the test in Add().
return;
}
if (port < 0)
{
return;
}
++_version;
CredentialHostKey key = new CredentialHostKey(host, port, authenticationType);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
}
if (_cacheForHosts[key] is SystemNetworkCredential)
{
--_numbDefaultCredInCache;
}
_cacheForHosts.Remove(key);
}
/// <devdoc>
/// <para>
/// Returns the <see cref='System.Net.NetworkCredential'/>
/// instance associated with the supplied Uri and
/// authentication type.
/// </para>
/// </devdoc>
public NetworkCredential GetCredential(Uri uriPrefix, string authenticationType)
{
if (uriPrefix == null)
{
throw new ArgumentNullException(nameof(uriPrefix));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential(uriPrefix=\"" + uriPrefix + "\", authType=\"" + authenticationType + "\")");
}
int longestMatchPrefix = -1;
NetworkCredential mostSpecificMatch = null;
IDictionaryEnumerator credEnum = _cache.GetEnumerator();
// Enumerate through every credential in the cache
while (credEnum.MoveNext())
{
CredentialKey key = (CredentialKey)credEnum.Key;
// Determine if this credential is applicable to the current Uri/AuthType
if (key.Match(uriPrefix, authenticationType))
{
int prefixLen = key.UriPrefixLength;
// Check if the match is better than the current-most-specific match
if (prefixLen > longestMatchPrefix)
{
// Yes: update the information about currently preferred match
longestMatchPrefix = prefixLen;
mostSpecificMatch = (NetworkCredential)credEnum.Value;
}
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential returning " + ((mostSpecificMatch == null) ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")"));
}
return mostSpecificMatch;
}
public NetworkCredential GetCredential(string host, int port, string authenticationType)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (authenticationType == null)
{
throw new ArgumentNullException(nameof(authenticationType));
}
if (host.Length == 0)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, "host"));
}
if (port < 0)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential(host=\"" + host + ":" + port.ToString() + "\", authenticationType=\"" + authenticationType + "\")");
}
NetworkCredential match = null;
IDictionaryEnumerator credEnum = _cacheForHosts.GetEnumerator();
// Enumerate through every credential in the cache
while (credEnum.MoveNext())
{
CredentialHostKey key = (CredentialHostKey)credEnum.Key;
// Determine if this credential is applicable to the current Uri/AuthType
if (key.Match(host, port, authenticationType))
{
match = (NetworkCredential)credEnum.Value;
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialCache::GetCredential returning " + ((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")"));
}
return match;
}
public IEnumerator GetEnumerator()
{
return new CredentialEnumerator(this, _cache, _cacheForHosts, _version);
}
/// <devdoc>
/// <para>
/// Gets the default system credentials from the <see cref='System.Net.CredentialCache'/>.
/// </para>
/// </devdoc>
public static ICredentials DefaultCredentials
{
get
{
return SystemNetworkCredential.s_defaultCredential;
}
}
public static NetworkCredential DefaultNetworkCredentials
{
get
{
return SystemNetworkCredential.s_defaultCredential;
}
}
private class CredentialEnumerator : IEnumerator
{
private CredentialCache _cache;
private ICredentials[] _array;
private int _index = -1;
private int _version;
internal CredentialEnumerator(CredentialCache cache, Dictionary<CredentialKey, NetworkCredential> table, Dictionary<CredentialHostKey, NetworkCredential> hostTable, int version)
{
_cache = cache;
_array = new ICredentials[table.Count + hostTable.Count];
((ICollection)table.Values).CopyTo(_array, 0);
((ICollection)hostTable.Values).CopyTo(_array, table.Count);
_version = version;
}
object IEnumerator.Current
{
get
{
if (_index < 0 || _index >= _array.Length)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
if (_version != _cache._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
return _array[_index];
}
}
bool IEnumerator.MoveNext()
{
if (_version != _cache._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if (++_index < _array.Length)
{
return true;
}
_index = _array.Length;
return false;
}
void IEnumerator.Reset()
{
_index = -1;
}
}
}
// Abstraction for credentials in password-based
// authentication schemes (basic, digest, NTLM, Kerberos).
//
// Note that this is not applicable to public-key based
// systems such as SSL client authentication.
//
// "Password" here may be the clear text password or it
// could be a one-way hash that is sufficient to
// authenticate, as in HTTP/1.1 digest.
internal class SystemNetworkCredential : NetworkCredential
{
internal static readonly SystemNetworkCredential s_defaultCredential = new SystemNetworkCredential();
// We want reference equality to work. Making this private is a good way to guarantee that.
private SystemNetworkCredential() :
base(string.Empty, string.Empty, string.Empty)
{
}
}
internal class CredentialHostKey : IEquatable<CredentialHostKey>
{
public readonly string Host;
public readonly string AuthenticationType;
public readonly int Port;
internal CredentialHostKey(string host, int port, string authenticationType)
{
Host = host;
Port = port;
AuthenticationType = authenticationType;
}
internal bool Match(string host, int port, string authenticationType)
{
if (host == null || authenticationType == null)
{
return false;
}
// If the protocols don't match, this credential is not applicable for the given Uri.
if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase) ||
!string.Equals(Host, host, StringComparison.OrdinalIgnoreCase) ||
port != Port)
{
return false;
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialKey::Match(" + Host.ToString() + ":" + Port.ToString() + " & " + host.ToString() + ":" + port.ToString() + ")");
}
return true;
}
private int _hashCode = 0;
private bool _computedHashCode = false;
public override int GetHashCode()
{
if (!_computedHashCode)
{
// Compute HashCode on demand
_hashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + Host.ToUpperInvariant().GetHashCode() + Port.GetHashCode();
_computedHashCode = true;
}
return _hashCode;
}
public bool Equals(CredentialHostKey other)
{
if (other == null)
{
return false;
}
bool equals =
string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) &&
string.Equals(Host, other.Host, StringComparison.OrdinalIgnoreCase) &&
Port == other.Port;
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString());
}
return equals;
}
public override bool Equals(object comparand)
{
return Equals(comparand as CredentialHostKey);
}
public override string ToString()
{
return "[" + Host.Length.ToString(NumberFormatInfo.InvariantInfo) + "]:" + Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + LoggingHash.ObjectToString(AuthenticationType);
}
}
internal class CredentialKey : IEquatable<CredentialKey>
{
public readonly Uri UriPrefix;
public readonly int UriPrefixLength = -1;
public readonly string AuthenticationType;
private int _hashCode = 0;
private bool _computedHashCode = false;
internal CredentialKey(Uri uriPrefix, string authenticationType)
{
UriPrefix = uriPrefix;
UriPrefixLength = UriPrefix.ToString().Length;
AuthenticationType = authenticationType;
}
internal bool Match(Uri uri, string authenticationType)
{
if (uri == null || authenticationType == null)
{
return false;
}
// If the protocols don't match, this credential is not applicable for the given Uri.
if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialKey::Match(" + UriPrefix.ToString() + " & " + uri.ToString() + ")");
}
return IsPrefix(uri, UriPrefix);
}
// IsPrefix (Uri)
//
// Determines whether <prefixUri> is a prefix of this URI. A prefix
// match is defined as:
//
// scheme match
// + host match
// + port match, if any
// + <prefix> path is a prefix of <URI> path, if any
//
// Returns:
// True if <prefixUri> is a prefix of this URI
internal bool IsPrefix(Uri uri, Uri prefixUri)
{
if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port)
{
return false;
}
int prefixLen = prefixUri.AbsolutePath.LastIndexOf('/');
if (prefixLen > uri.AbsolutePath.LastIndexOf('/'))
{
return false;
}
return String.Compare(uri.AbsolutePath, 0, prefixUri.AbsolutePath, 0, prefixLen, StringComparison.OrdinalIgnoreCase) == 0;
}
public override int GetHashCode()
{
if (!_computedHashCode)
{
// Compute HashCode on demand
_hashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + UriPrefixLength + UriPrefix.GetHashCode();
_computedHashCode = true;
}
return _hashCode;
}
public bool Equals(CredentialKey other)
{
if (other == null)
{
return false;
}
bool equals =
string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) &&
UriPrefix.Equals(other.UriPrefix);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + other.ToString() + ") returns " + equals.ToString());
}
return equals;
}
public override bool Equals(object comparand)
{
return Equals(comparand as CredentialKey);
}
public override string ToString()
{
return "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + LoggingHash.ObjectToString(UriPrefix) + ":" + LoggingHash.ObjectToString(AuthenticationType);
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// <para> The AutoScalingGroup data type. </para>
/// </summary>
public class AutoScalingGroup
{
private string autoScalingGroupName;
private string autoScalingGroupARN;
private string launchConfigurationName;
private int? minSize;
private int? maxSize;
private int? desiredCapacity;
private int? defaultCooldown;
private List<string> availabilityZones = new List<string>();
private List<string> loadBalancerNames = new List<string>();
private string healthCheckType;
private int? healthCheckGracePeriod;
private List<Instance> instances = new List<Instance>();
private DateTime? createdTime;
private List<SuspendedProcess> suspendedProcesses = new List<SuspendedProcess>();
private string placementGroup;
private string vPCZoneIdentifier;
private List<EnabledMetric> enabledMetrics = new List<EnabledMetric>();
private string status;
private List<TagDescription> tags = new List<TagDescription>();
private List<string> terminationPolicies = new List<string>();
/// <summary>
/// Specifies the name of the group.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string AutoScalingGroupName
{
get { return this.autoScalingGroupName; }
set { this.autoScalingGroupName = value; }
}
/// <summary>
/// Sets the AutoScalingGroupName property
/// </summary>
/// <param name="autoScalingGroupName">The value to set for the AutoScalingGroupName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithAutoScalingGroupName(string autoScalingGroupName)
{
this.autoScalingGroupName = autoScalingGroupName;
return this;
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this.autoScalingGroupName != null;
}
/// <summary>
/// The Amazon Resource Name (ARN) of the Auto Scaling group.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 1600</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string AutoScalingGroupARN
{
get { return this.autoScalingGroupARN; }
set { this.autoScalingGroupARN = value; }
}
/// <summary>
/// Sets the AutoScalingGroupARN property
/// </summary>
/// <param name="autoScalingGroupARN">The value to set for the AutoScalingGroupARN property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithAutoScalingGroupARN(string autoScalingGroupARN)
{
this.autoScalingGroupARN = autoScalingGroupARN;
return this;
}
// Check to see if AutoScalingGroupARN property is set
internal bool IsSetAutoScalingGroupARN()
{
return this.autoScalingGroupARN != null;
}
/// <summary>
/// Specifies the name of the associated <a>LaunchConfiguration</a>.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string LaunchConfigurationName
{
get { return this.launchConfigurationName; }
set { this.launchConfigurationName = value; }
}
/// <summary>
/// Sets the LaunchConfigurationName property
/// </summary>
/// <param name="launchConfigurationName">The value to set for the LaunchConfigurationName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithLaunchConfigurationName(string launchConfigurationName)
{
this.launchConfigurationName = launchConfigurationName;
return this;
}
// Check to see if LaunchConfigurationName property is set
internal bool IsSetLaunchConfigurationName()
{
return this.launchConfigurationName != null;
}
/// <summary>
/// Contains the minimum size of the Auto Scaling group.
///
/// </summary>
public int MinSize
{
get { return this.minSize ?? default(int); }
set { this.minSize = value; }
}
/// <summary>
/// Sets the MinSize property
/// </summary>
/// <param name="minSize">The value to set for the MinSize property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithMinSize(int minSize)
{
this.minSize = minSize;
return this;
}
// Check to see if MinSize property is set
internal bool IsSetMinSize()
{
return this.minSize.HasValue;
}
/// <summary>
/// Contains the maximum size of the Auto Scaling group.
///
/// </summary>
public int MaxSize
{
get { return this.maxSize ?? default(int); }
set { this.maxSize = value; }
}
/// <summary>
/// Sets the MaxSize property
/// </summary>
/// <param name="maxSize">The value to set for the MaxSize property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithMaxSize(int maxSize)
{
this.maxSize = maxSize;
return this;
}
// Check to see if MaxSize property is set
internal bool IsSetMaxSize()
{
return this.maxSize.HasValue;
}
/// <summary>
/// Specifies the desired capacity for the Auto Scaling group.
///
/// </summary>
public int DesiredCapacity
{
get { return this.desiredCapacity ?? default(int); }
set { this.desiredCapacity = value; }
}
/// <summary>
/// Sets the DesiredCapacity property
/// </summary>
/// <param name="desiredCapacity">The value to set for the DesiredCapacity property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithDesiredCapacity(int desiredCapacity)
{
this.desiredCapacity = desiredCapacity;
return this;
}
// Check to see if DesiredCapacity property is set
internal bool IsSetDesiredCapacity()
{
return this.desiredCapacity.HasValue;
}
/// <summary>
/// The number of seconds after a scaling activity completes before any further scaling activities can start.
///
/// </summary>
public int DefaultCooldown
{
get { return this.defaultCooldown ?? default(int); }
set { this.defaultCooldown = value; }
}
/// <summary>
/// Sets the DefaultCooldown property
/// </summary>
/// <param name="defaultCooldown">The value to set for the DefaultCooldown property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithDefaultCooldown(int defaultCooldown)
{
this.defaultCooldown = defaultCooldown;
return this;
}
// Check to see if DefaultCooldown property is set
internal bool IsSetDefaultCooldown()
{
return this.defaultCooldown.HasValue;
}
/// <summary>
/// Contains a list of Availability Zones for the group.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - </description>
/// </item>
/// </list>
/// </para>
/// </summary>
public List<string> AvailabilityZones
{
get { return this.availabilityZones; }
set { this.availabilityZones = value; }
}
/// <summary>
/// Adds elements to the AvailabilityZones collection
/// </summary>
/// <param name="availabilityZones">The values to add to the AvailabilityZones collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithAvailabilityZones(params string[] availabilityZones)
{
foreach (string element in availabilityZones)
{
this.availabilityZones.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the AvailabilityZones collection
/// </summary>
/// <param name="availabilityZones">The values to add to the AvailabilityZones collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithAvailabilityZones(IEnumerable<string> availabilityZones)
{
foreach (string element in availabilityZones)
{
this.availabilityZones.Add(element);
}
return this;
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this.availabilityZones.Count > 0;
}
/// <summary>
/// A list of load balancers associated with this Auto Scaling group.
///
/// </summary>
public List<string> LoadBalancerNames
{
get { return this.loadBalancerNames; }
set { this.loadBalancerNames = value; }
}
/// <summary>
/// Adds elements to the LoadBalancerNames collection
/// </summary>
/// <param name="loadBalancerNames">The values to add to the LoadBalancerNames collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithLoadBalancerNames(params string[] loadBalancerNames)
{
foreach (string element in loadBalancerNames)
{
this.loadBalancerNames.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the LoadBalancerNames collection
/// </summary>
/// <param name="loadBalancerNames">The values to add to the LoadBalancerNames collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithLoadBalancerNames(IEnumerable<string> loadBalancerNames)
{
foreach (string element in loadBalancerNames)
{
this.loadBalancerNames.Add(element);
}
return this;
}
// Check to see if LoadBalancerNames property is set
internal bool IsSetLoadBalancerNames()
{
return this.loadBalancerNames.Count > 0;
}
/// <summary>
/// The service of interest for the health status check, either "EC2" for Amazon EC2 or "ELB" for Elastic Load Balancing.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 32</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string HealthCheckType
{
get { return this.healthCheckType; }
set { this.healthCheckType = value; }
}
/// <summary>
/// Sets the HealthCheckType property
/// </summary>
/// <param name="healthCheckType">The value to set for the HealthCheckType property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithHealthCheckType(string healthCheckType)
{
this.healthCheckType = healthCheckType;
return this;
}
// Check to see if HealthCheckType property is set
internal bool IsSetHealthCheckType()
{
return this.healthCheckType != null;
}
/// <summary>
/// The length of time that Auto Scaling waits before checking an instance's health status. The grace period begins when an instance comes into
/// service.
///
/// </summary>
public int HealthCheckGracePeriod
{
get { return this.healthCheckGracePeriod ?? default(int); }
set { this.healthCheckGracePeriod = value; }
}
/// <summary>
/// Sets the HealthCheckGracePeriod property
/// </summary>
/// <param name="healthCheckGracePeriod">The value to set for the HealthCheckGracePeriod property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithHealthCheckGracePeriod(int healthCheckGracePeriod)
{
this.healthCheckGracePeriod = healthCheckGracePeriod;
return this;
}
// Check to see if HealthCheckGracePeriod property is set
internal bool IsSetHealthCheckGracePeriod()
{
return this.healthCheckGracePeriod.HasValue;
}
/// <summary>
/// Provides a summary list of Amazon EC2 instances.
///
/// </summary>
public List<Instance> Instances
{
get { return this.instances; }
set { this.instances = value; }
}
/// <summary>
/// Adds elements to the Instances collection
/// </summary>
/// <param name="instances">The values to add to the Instances collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithInstances(params Instance[] instances)
{
foreach (Instance element in instances)
{
this.instances.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Instances collection
/// </summary>
/// <param name="instances">The values to add to the Instances collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithInstances(IEnumerable<Instance> instances)
{
foreach (Instance element in instances)
{
this.instances.Add(element);
}
return this;
}
// Check to see if Instances property is set
internal bool IsSetInstances()
{
return this.instances.Count > 0;
}
/// <summary>
/// Specifies the date and time the Auto Scaling group was created.
///
/// </summary>
public DateTime CreatedTime
{
get { return this.createdTime ?? default(DateTime); }
set { this.createdTime = value; }
}
/// <summary>
/// Sets the CreatedTime property
/// </summary>
/// <param name="createdTime">The value to set for the CreatedTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithCreatedTime(DateTime createdTime)
{
this.createdTime = createdTime;
return this;
}
// Check to see if CreatedTime property is set
internal bool IsSetCreatedTime()
{
return this.createdTime.HasValue;
}
/// <summary>
/// Suspended processes associated with this Auto Scaling group.
///
/// </summary>
public List<SuspendedProcess> SuspendedProcesses
{
get { return this.suspendedProcesses; }
set { this.suspendedProcesses = value; }
}
/// <summary>
/// Adds elements to the SuspendedProcesses collection
/// </summary>
/// <param name="suspendedProcesses">The values to add to the SuspendedProcesses collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithSuspendedProcesses(params SuspendedProcess[] suspendedProcesses)
{
foreach (SuspendedProcess element in suspendedProcesses)
{
this.suspendedProcesses.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the SuspendedProcesses collection
/// </summary>
/// <param name="suspendedProcesses">The values to add to the SuspendedProcesses collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithSuspendedProcesses(IEnumerable<SuspendedProcess> suspendedProcesses)
{
foreach (SuspendedProcess element in suspendedProcesses)
{
this.suspendedProcesses.Add(element);
}
return this;
}
// Check to see if SuspendedProcesses property is set
internal bool IsSetSuspendedProcesses()
{
return this.suspendedProcesses.Count > 0;
}
/// <summary>
/// The name of the cluster placement group, if applicable. For more information, go to <a
/// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using_cluster_computing.html"> Using Cluster Instances</a> in the Amazon EC2 User
/// Guide.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string PlacementGroup
{
get { return this.placementGroup; }
set { this.placementGroup = value; }
}
/// <summary>
/// Sets the PlacementGroup property
/// </summary>
/// <param name="placementGroup">The value to set for the PlacementGroup property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithPlacementGroup(string placementGroup)
{
this.placementGroup = placementGroup;
return this;
}
// Check to see if PlacementGroup property is set
internal bool IsSetPlacementGroup()
{
return this.placementGroup != null;
}
/// <summary>
/// The subnet identifier for the Amazon VPC connection, if applicable. You can specify several subnets in a comma-separated list. When you
/// specify <c>VPCZoneIdentifier</c> with <c>AvailabilityZones</c>, ensure that the subnets' Availability Zones match the values you specify for
/// <c>AvailabilityZones</c>.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string VPCZoneIdentifier
{
get { return this.vPCZoneIdentifier; }
set { this.vPCZoneIdentifier = value; }
}
/// <summary>
/// Sets the VPCZoneIdentifier property
/// </summary>
/// <param name="vPCZoneIdentifier">The value to set for the VPCZoneIdentifier property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithVPCZoneIdentifier(string vPCZoneIdentifier)
{
this.vPCZoneIdentifier = vPCZoneIdentifier;
return this;
}
// Check to see if VPCZoneIdentifier property is set
internal bool IsSetVPCZoneIdentifier()
{
return this.vPCZoneIdentifier != null;
}
/// <summary>
/// A list of metrics enabled for this Auto Scaling group.
///
/// </summary>
public List<EnabledMetric> EnabledMetrics
{
get { return this.enabledMetrics; }
set { this.enabledMetrics = value; }
}
/// <summary>
/// Adds elements to the EnabledMetrics collection
/// </summary>
/// <param name="enabledMetrics">The values to add to the EnabledMetrics collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithEnabledMetrics(params EnabledMetric[] enabledMetrics)
{
foreach (EnabledMetric element in enabledMetrics)
{
this.enabledMetrics.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the EnabledMetrics collection
/// </summary>
/// <param name="enabledMetrics">The values to add to the EnabledMetrics collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithEnabledMetrics(IEnumerable<EnabledMetric> enabledMetrics)
{
foreach (EnabledMetric element in enabledMetrics)
{
this.enabledMetrics.Add(element);
}
return this;
}
// Check to see if EnabledMetrics property is set
internal bool IsSetEnabledMetrics()
{
return this.enabledMetrics.Count > 0;
}
/// <summary>
/// The current state of the Auto Scaling group when a <a>DeleteAutoScalingGroup</a> action is in progress.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Status
{
get { return this.status; }
set { this.status = value; }
}
/// <summary>
/// Sets the Status property
/// </summary>
/// <param name="status">The value to set for the Status property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithStatus(string status)
{
this.status = status;
return this;
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this.status != null;
}
/// <summary>
/// A list of tags for the Auto Scaling group.
///
/// </summary>
public List<TagDescription> Tags
{
get { return this.tags; }
set { this.tags = value; }
}
/// <summary>
/// Adds elements to the Tags collection
/// </summary>
/// <param name="tags">The values to add to the Tags collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithTags(params TagDescription[] tags)
{
foreach (TagDescription element in tags)
{
this.tags.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Tags collection
/// </summary>
/// <param name="tags">The values to add to the Tags collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithTags(IEnumerable<TagDescription> tags)
{
foreach (TagDescription element in tags)
{
this.tags.Add(element);
}
return this;
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this.tags.Count > 0;
}
/// <summary>
/// A standalone termination policy or a list of termination policies for this Auto Scaling group.
///
/// </summary>
public List<string> TerminationPolicies
{
get { return this.terminationPolicies; }
set { this.terminationPolicies = value; }
}
/// <summary>
/// Adds elements to the TerminationPolicies collection
/// </summary>
/// <param name="terminationPolicies">The values to add to the TerminationPolicies collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithTerminationPolicies(params string[] terminationPolicies)
{
foreach (string element in terminationPolicies)
{
this.terminationPolicies.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the TerminationPolicies collection
/// </summary>
/// <param name="terminationPolicies">The values to add to the TerminationPolicies collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AutoScalingGroup WithTerminationPolicies(IEnumerable<string> terminationPolicies)
{
foreach (string element in terminationPolicies)
{
this.terminationPolicies.Add(element);
}
return this;
}
// Check to see if TerminationPolicies property is set
internal bool IsSetTerminationPolicies()
{
return this.terminationPolicies.Count > 0;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.WebControls.PagedDataSource.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
sealed public partial class PagedDataSource : System.Collections.ICollection, System.Collections.IEnumerable, System.ComponentModel.ITypedList
{
#region Methods and constructors
public void CopyTo (Array array, int index)
{
}
public System.Collections.IEnumerator GetEnumerator ()
{
return default(System.Collections.IEnumerator);
}
public System.ComponentModel.PropertyDescriptorCollection GetItemProperties (System.ComponentModel.PropertyDescriptor[] listAccessors)
{
return default(System.ComponentModel.PropertyDescriptorCollection);
}
public string GetListName (System.ComponentModel.PropertyDescriptor[] listAccessors)
{
return default(string);
}
public PagedDataSource ()
{
}
#endregion
#region Properties and indexers
public bool AllowCustomPaging
{
get
{
return default(bool);
}
set
{
}
}
public bool AllowPaging
{
get
{
return default(bool);
}
set
{
}
}
public bool AllowServerPaging
{
get
{
return default(bool);
}
set
{
}
}
public int Count
{
get
{
return default(int);
}
}
public int CurrentPageIndex
{
get
{
return default(int);
}
set
{
}
}
public System.Collections.IEnumerable DataSource
{
get
{
return default(System.Collections.IEnumerable);
}
set
{
}
}
public int DataSourceCount
{
get
{
return default(int);
}
}
public int FirstIndexInPage
{
get
{
return default(int);
}
}
public bool IsCustomPagingEnabled
{
get
{
return default(bool);
}
}
public bool IsFirstPage
{
get
{
return default(bool);
}
}
public bool IsLastPage
{
get
{
return default(bool);
}
}
public bool IsPagingEnabled
{
get
{
return default(bool);
}
}
public bool IsReadOnly
{
get
{
Contract.Ensures (Contract.Result<bool>() == false);
return default(bool);
}
}
public bool IsServerPagingEnabled
{
get
{
return default(bool);
}
}
public bool IsSynchronized
{
get
{
return default(bool);
}
}
public int PageCount
{
get
{
return default(int);
}
}
public int PageSize
{
get
{
return default(int);
}
set
{
}
}
public Object SyncRoot
{
get
{
return default(Object);
}
}
public int VirtualCount
{
get
{
return default(int);
}
set
{
}
}
#endregion
}
}
| |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using EventStore.Core.Data;
using EventStore.Core.Messaging;
using EventStore.Projections.Core.Services.Processing;
using ResolvedEvent = EventStore.Projections.Core.Services.Processing.ResolvedEvent;
namespace EventStore.Projections.Core.Messages
{
public static class ReaderSubscriptionMessage
{
public class SubscriptionMessage : Message
{
private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId);
public override int MsgTypeId { get { return TypeId; } }
private readonly Guid _correlationId;
private readonly CheckpointTag _preTagged;
private readonly object _source;
public SubscriptionMessage(Guid correlationId, CheckpointTag preTagged, object source)
{
_correlationId = correlationId;
_preTagged = preTagged;
_source = source;
}
public Guid CorrelationId
{
get { return _correlationId; }
}
public CheckpointTag PreTagged
{
get { return _preTagged; }
}
public object Source
{
get { return _source; }
}
}
public class EventReaderIdle : SubscriptionMessage
{
private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId);
public override int MsgTypeId { get { return TypeId; } }
private readonly DateTime _idleTimestampUtc;
public EventReaderIdle(Guid correlationId, DateTime idleTimestampUtc, object source = null)
: base(correlationId, null, source)
{
_idleTimestampUtc = idleTimestampUtc;
}
public DateTime IdleTimestampUtc
{
get { return _idleTimestampUtc; }
}
}
public sealed class EventReaderStarting : SubscriptionMessage
{
private readonly long _lastCommitPosition;
private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId);
public override int MsgTypeId { get { return TypeId; } }
public EventReaderStarting(Guid correlationId, long lastCommitPosition, object source = null)
: base(correlationId, null, source)
{
_lastCommitPosition = lastCommitPosition;
}
public long LastCommitPosition
{
get { return _lastCommitPosition; }
}
}
public class EventReaderEof : SubscriptionMessage
{
private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId);
public override int MsgTypeId { get { return TypeId; } }
private readonly bool _maxEventsReached;
public EventReaderEof(Guid correlationId, bool maxEventsReached = false, object source = null)
: base(correlationId, null, source)
{
_maxEventsReached = maxEventsReached;
}
public bool MaxEventsReached
{
get { return _maxEventsReached; }
}
}
public class EventReaderPartitionEof : SubscriptionMessage
{
private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId);
public override int MsgTypeId
{
get { return TypeId; }
}
private readonly string _partition;
public EventReaderPartitionEof(
Guid correlationId, string partition, CheckpointTag preTagged, object source = null)
: base(correlationId, preTagged, source)
{
_partition = partition;
}
public string Partition
{
get { return _partition; }
}
}
public class EventReaderPartitionMeasured : SubscriptionMessage
{
private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId);
public override int MsgTypeId
{
get { return TypeId; }
}
private readonly string _partition;
private readonly int _size;
public EventReaderPartitionMeasured(
Guid correlationId, string partition, int size, object source = null)
: base(correlationId, null, source)
{
_partition = partition;
_size = size;
}
public string Partition
{
get { return _partition; }
}
public int Size
{
get { return _size; }
}
}
public sealed class EventReaderNotAuthorized : SubscriptionMessage
{
private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId);
public override int MsgTypeId { get { return TypeId; } }
public EventReaderNotAuthorized(Guid correlationId, object source = null)
: base(correlationId, null, source)
{
}
}
public class CommittedEventDistributed : SubscriptionMessage
{
private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId);
public override int MsgTypeId { get { return TypeId; } }
public static CommittedEventDistributed Sample(
Guid correlationId, TFPos position, TFPos originalPosition, string positionStreamId, int positionSequenceNumber,
string eventStreamId, int eventSequenceNumber, bool resolvedLinkTo, Guid eventId, string eventType,
bool isJson, byte[] data, byte[] metadata, long? safeTransactionFileReaderJoinPosition, float progress)
{
return new CommittedEventDistributed(
correlationId,
new ResolvedEvent(
positionStreamId, positionSequenceNumber, eventStreamId, eventSequenceNumber, resolvedLinkTo,
position, originalPosition, eventId, eventType, isJson, data, metadata, null, null, default(DateTime)),
safeTransactionFileReaderJoinPosition, progress);
}
public static CommittedEventDistributed Sample(
Guid correlationId, TFPos position, string eventStreamId, int eventSequenceNumber,
bool resolvedLinkTo, Guid eventId, string eventType, bool isJson, byte[] data, byte[] metadata,
DateTime? timestamp = null)
{
return new CommittedEventDistributed(
correlationId,
new ResolvedEvent(
eventStreamId, eventSequenceNumber, eventStreamId, eventSequenceNumber, resolvedLinkTo, position,
position, eventId, eventType, isJson, data, metadata, null, null, timestamp.GetValueOrDefault()),
position.PreparePosition, 11.1f);
}
private readonly ResolvedEvent _data;
private readonly long? _safeTransactionFileReaderJoinPosition;
private readonly float _progress;
//NOTE: committed event with null event _data means - end of the source reached.
// Current last available TF commit position is in _position.CommitPosition
// TODO: separate message?
public CommittedEventDistributed(
Guid correlationId, ResolvedEvent data, long? safeTransactionFileReaderJoinPosition, float progress,
object source = null, CheckpointTag preTagged = null)
: base(correlationId, preTagged, source)
{
_data = data;
_safeTransactionFileReaderJoinPosition = safeTransactionFileReaderJoinPosition;
_progress = progress;
}
public CommittedEventDistributed(Guid correlationId, ResolvedEvent data, CheckpointTag preTagged = null)
: this(correlationId, data, data.Position.PreparePosition, 11.1f, preTagged)
{
}
public ResolvedEvent Data
{
get { return _data; }
}
public long? SafeTransactionFileReaderJoinPosition
{
get { return _safeTransactionFileReaderJoinPosition; }
}
public float Progress
{
get { return _progress; }
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using org.apache.commons.math3.exception;
using org.apache.commons.math3.analysis.solvers;
using org.apache.commons.math3.analysis.util;
using org.apache.commons.math3.util;
namespace org.apache.commons.math3.analysis.integration
{
/// <summary>
/// Provide a default implementation for several generic functions.
///
/// @version $Id: BaseAbstractUnivariateIntegrator.java 1455194 2013-03-11 15:45:54Z luc $
/// @since 1.2
/// </summary>
public abstract class BaseAbstractUnivariateIntegrator : UnivariateIntegrator
{
/// <summary>
/// Default absolute accuracy. </summary>
public const double DEFAULT_ABSOLUTE_ACCURACY = 1.0e-15;
/// <summary>
/// Default relative accuracy. </summary>
public const double DEFAULT_RELATIVE_ACCURACY = 1.0e-6;
/// <summary>
/// Default minimal iteration count. </summary>
public const int DEFAULT_MIN_ITERATIONS_COUNT = 3;
/// <summary>
/// Default maximal iteration count. </summary>
public static readonly int DEFAULT_MAX_ITERATIONS_COUNT = int.MaxValue;
/// <summary>
/// The iteration count. </summary>
protected internal readonly Incrementor iterations;
/// <summary>
/// Maximum absolute error. </summary>
private readonly double absoluteAccuracy;
/// <summary>
/// Maximum relative error. </summary>
private readonly double relativeAccuracy;
/// <summary>
/// minimum number of iterations </summary>
private readonly int minimalIterationCount;
/// <summary>
/// The functions evaluation count. </summary>
private readonly Incrementor evaluations;
/// <summary>
/// Function to integrate. </summary>
private UnivariateFunction function;
/// <summary>
/// Lower bound for the interval. </summary>
private double min;
/// <summary>
/// Upper bound for the interval. </summary>
private double max;
/// <summary>
/// Construct an integrator with given accuracies and iteration counts.
/// <para>
/// The meanings of the various parameters are:
/// <ul>
/// <li>relative accuracy:
/// this is used to stop iterations if the absolute accuracy can't be
/// achieved due to large values or short mantissa length. If this
/// should be the primary criterion for convergence rather then a
/// safety measure, set the absolute accuracy to a ridiculously small value,
/// like <seealso cref="org.apache.commons.math3.util.Precision#SAFE_MIN Precision.SAFE_MIN"/>.</li>
/// <li>absolute accuracy:
/// The default is usually chosen so that results in the interval
/// -10..-0.1 and +0.1..+10 can be found with a reasonable accuracy. If the
/// expected absolute value of your results is of much smaller magnitude, set
/// this to a smaller value.</li>
/// <li>minimum number of iterations:
/// minimal iteration is needed to avoid false early convergence, e.g.
/// the sample points happen to be zeroes of the function. Users can
/// use the default value or choose one that they see as appropriate.</li>
/// <li>maximum number of iterations:
/// usually a high iteration count indicates convergence problems. However,
/// the "reasonable value" varies widely for different algorithms. Users are
/// advised to use the default value supplied by the algorithm.</li>
/// </ul>
/// </para> </summary>
/// <param name="relativeAccuracy"> relative accuracy of the result </param>
/// <param name="absoluteAccuracy"> absolute accuracy of the result </param>
/// <param name="minimalIterationCount"> minimum number of iterations </param>
/// <param name="maximalIterationCount"> maximum number of iterations </param>
/// <exception cref="NotStrictlyPositiveException"> if minimal number of iterations
/// is not strictly positive </exception>
/// <exception cref="NumberIsTooSmallException"> if maximal number of iterations
/// is lesser than or equal to the minimal number of iterations </exception>
protected internal BaseAbstractUnivariateIntegrator(double relativeAccuracy, double absoluteAccuracy, int minimalIterationCount, int maximalIterationCount)
{
// accuracy settings
this.relativeAccuracy = relativeAccuracy;
this.absoluteAccuracy = absoluteAccuracy;
// iterations count settings
if (minimalIterationCount <= 0)
{
throw new NotStrictlyPositiveException(minimalIterationCount);
}
if (maximalIterationCount <= minimalIterationCount)
{
throw new NumberIsTooSmallException(maximalIterationCount, minimalIterationCount, false);
}
this.minimalIterationCount = minimalIterationCount;
this.iterations = new Incrementor();
this.iterations.MaximalCount = maximalIterationCount;
// prepare evaluations counter, but do not set it yet
this.evaluations = new Incrementor();
}
/// <summary>
/// Construct an integrator with given accuracies. </summary>
/// <param name="relativeAccuracy"> relative accuracy of the result </param>
/// <param name="absoluteAccuracy"> absolute accuracy of the result </param>
protected internal BaseAbstractUnivariateIntegrator(double relativeAccuracy, double absoluteAccuracy)
: this(relativeAccuracy, absoluteAccuracy, DEFAULT_MIN_ITERATIONS_COUNT, DEFAULT_MAX_ITERATIONS_COUNT)
{
}
/// <summary>
/// Construct an integrator with given iteration counts. </summary>
/// <param name="minimalIterationCount"> minimum number of iterations </param>
/// <param name="maximalIterationCount"> maximum number of iterations </param>
/// <exception cref="NotStrictlyPositiveException"> if minimal number of iterations
/// is not strictly positive </exception>
/// <exception cref="NumberIsTooSmallException"> if maximal number of iterations
/// is lesser than or equal to the minimal number of iterations </exception>
protected internal BaseAbstractUnivariateIntegrator(int minimalIterationCount, int maximalIterationCount)
: this(DEFAULT_RELATIVE_ACCURACY, DEFAULT_ABSOLUTE_ACCURACY, minimalIterationCount, maximalIterationCount)
{
}
/// <summary>
/// {@inheritDoc} </summary>
public virtual double RelativeAccuracy
{
get { return this.relativeAccuracy; }
}
/// <summary>
/// {@inheritDoc} </summary>
public virtual double AbsoluteAccuracy
{
get { return this.absoluteAccuracy; }
}
/// <summary>
/// {@inheritDoc} </summary>
public virtual int MinimalIterationCount
{
get { return this.minimalIterationCount; }
}
/// <summary>
/// {@inheritDoc} </summary>
public virtual int MaximalIterationCount
{
get { return this.iterations.MaximalCount; }
}
/// <summary>
/// {@inheritDoc} </summary>
public virtual int Evaluations
{
get { return this.evaluations.Count; }
}
/// <summary>
/// {@inheritDoc} </summary>
public virtual int Iterations
{
get { return this.iterations.Count; }
}
/// <returns> the lower bound. </returns>
protected internal virtual double Min
{
get { return this.min; }
}
/// <returns> the upper bound. </returns>
protected internal virtual double Max
{
get { return this.max; }
}
/// <summary>
/// Compute the objective function value.
/// </summary>
/// <param name="point"> Point at which the objective function must be evaluated. </param>
/// <returns> the objective function value at specified point. </returns>
/// <exception cref="TooManyEvaluationsException"> if the maximal number of function
/// evaluations is exceeded. </exception>
protected internal virtual double ComputeObjectiveValue(double point)
{
try
{
this.evaluations.IncrementCount();
}
catch (MaxCountExceededException e)
{
throw new TooManyEvaluationsException(e.Max);
}
return this.function.Value(point);
}
/// <summary>
/// Prepare for computation.
/// Subclasses must call this method if they override any of the
/// {@code solve} methods.
/// </summary>
/// <param name="maxEval"> Maximum number of evaluations. </param>
/// <param name="f"> the integrand function </param>
/// <param name="lower"> the min bound for the interval </param>
/// <param name="upper"> the upper bound for the interval </param>
/// <exception cref="NullArgumentException"> if {@code f} is {@code null}. </exception>
/// <exception cref="MathIllegalArgumentException"> if {@code min >= max}. </exception>
protected internal virtual void Setup(int maxEval, UnivariateFunction f, double lower, double upper)
{
// Checks.
MyUtils.CheckNotNull(f);
UnivariateSolverUtils.VerifyInterval(lower, upper);
// Reset.
this.min = lower;
this.max = upper;
this.function = f;
this.evaluations.MaximalCount = maxEval;
this.evaluations.ResetCount();
this.iterations.ResetCount();
}
/// <summary>
/// {@inheritDoc} </summary>
public virtual double Integrate(int maxEval, UnivariateFunction f, double lower, double upper)
{
// Initialization.
this.Setup(maxEval, f, lower, upper);
// Perform computation.
return this.DoIntegrate();
}
/// <summary>
/// Method for implementing actual integration algorithms in derived
/// classes.
/// </summary>
/// <returns> the root. </returns>
/// <exception cref="TooManyEvaluationsException"> if the maximal number of evaluations
/// is exceeded. </exception>
/// <exception cref="MaxCountExceededException"> if the maximum iteration count is exceeded
/// or the integrator detects convergence problems otherwise </exception>
protected internal abstract double DoIntegrate();
}
}
| |
// 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.Globalization;
using TestLibrary;
/// <summary>
/// UInt64.ToString(System.IFormatProvider)
/// </summary>
public class UInt64ToString1
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
if (TestLibrary.Utilities.IsWindows)
{
// retVal = NegTest1() && retVal; // Disabled until neutral cultures are available
}
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert UInt64MaxValue to string value and using cultureinfo \"en-US\"");
try
{
UInt64 u64 = UInt64.MaxValue;
CultureInfo cultureInfo = new CultureInfo("en-US");
string str = u64.ToString(cultureInfo);
if (str != "18446744073709551615")
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Convert UInt64MinValue to string value and using cultureinfo \"fr-FR\"");
try
{
UInt64 u64 = UInt64.MinValue;
CultureInfo cultureInfo = new CultureInfo("fr-FR");
string str = u64.ToString(cultureInfo);
if (str != "0")
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: A UInt64 number begin with zeros and using cultureinfo \"en-US\"");
try
{
UInt64 u64 = 00009876;
CultureInfo cultureInfo = new CultureInfo("en-US");
string str = u64.ToString(cultureInfo);
if (str != "9876")
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert a random uint64 to string value and using \"en-GB\"");
try
{
UInt64 u64 = this.GetInt64(0, UInt64.MaxValue);
CultureInfo cultureInfo = new CultureInfo("en-GB");
string str = u64.ToString(cultureInfo);
string str2 = Convert.ToString(u64);
if (str != str2)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: The provider is a null reference");
try
{
UInt64 u64 = 000217639083000;
CultureInfo cultureInfo = null;
string str = u64.ToString(cultureInfo);
if (str != "217639083000")
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The provider argument is invalid");
try
{
UInt64 u64 = 1234500233;
CultureInfo cultureInfo = new CultureInfo("pl");
string str = u64.ToString(cultureInfo);
TestLibrary.TestFramework.LogError("101", "The NotSupportedException is not thrown as expected");
retVal = false;
}
catch (NotSupportedException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
UInt64ToString1 test = new UInt64ToString1();
TestLibrary.TestFramework.BeginTestCase("UInt64ToString1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region ForTestObject
private UInt64 GetInt64(UInt64 minValue, UInt64 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + (UInt64)TestLibrary.Generator.GetInt64(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
using SIL.IO;
using System;
using System.IO;
using System.Reflection;
namespace SIL.Reflection
{
public static class ReflectionHelper
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Loads a DLL.
/// </summary>
/// ------------------------------------------------------------------------------------
public static Assembly LoadAssembly(string dllPath)
{
try
{
if (!File.Exists(dllPath))
{
string dllFile = Path.GetFileName(dllPath);
string startingDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
dllPath = Path.Combine(startingDir, dllFile);
if (!File.Exists(dllPath))
return null;
}
return Assembly.LoadFrom(dllPath);
}
catch (Exception)
{
return null;
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CreateClassInstance(Assembly assembly, string className)
{
return CreateClassInstance(assembly, className, null);
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CreateClassInstance(Assembly assembly, string className, object[] args)
{
try
{
// First, take a stab at creating the instance with the specified name.
object instance = assembly.CreateInstance(className, false,
BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.NonPublic, null, args, null, null);
if (instance != null)
return instance;
Type[] types = assembly.GetTypes();
// At this point, we know we failed to instantiate a class with the
// specified name, so try to find a type with that name and attempt
// to instantiate the class using the full namespace.
foreach (Type type in types)
{
if (type.Name == className)
{
return assembly.CreateInstance(type.FullName, false,
BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.NonPublic, null, args, null, null);
}
}
}
catch { }
return null;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a string value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static string GetStrResult(object binding, string methodName, object[] args)
{
return (GetResult(binding, methodName, args) as string);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a string value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static string GetStrResult(object binding, string methodName, object args)
{
return (GetResult(binding, methodName, args) as string);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a integer value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static int GetIntResult(object binding, string methodName, object args)
{
return ((int)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a integer value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static int GetIntResult(object binding, string methodName, object[] args)
{
return ((int)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a float value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static float GetFloatResult(object binding, string methodName, object args)
{
return ((float)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a float value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static float GetFloatResult(object binding, string methodName, object[] args)
{
return ((float)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a boolean value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An single arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static bool GetBoolResult(object binding, string methodName, object args)
{
return ((bool)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a boolean value returned from a call to a private method.
/// </summary>
/// <param name="binding">This is either the Type of the object on which the method
/// is called or an instance of that type of object. When the method being called
/// is static then binding should be a type.</param>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="args">An array of arguments to pass to the method call.</param>
/// ------------------------------------------------------------------------------------
public static bool GetBoolResult(object binding, string methodName, object[] args)
{
return ((bool)GetResult(binding, methodName, args));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName)
{
CallMethod(binding, methodName, null);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object args)
{
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1, object arg2)
{
object[] args = new[] { arg1, arg2 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1,
object arg2, object arg3)
{
object[] args = new[] { arg1, arg2, arg3 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object arg1,
object arg2, object arg3, object arg4)
{
object[] args = new[] { arg1, arg2, arg3, arg4 };
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void CallMethod(object binding, string methodName, object[] args)
{
GetResult(binding, methodName, args);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns the result of calling a method on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetResult(object binding, string methodName, object args)
{
return Invoke(binding, methodName, new[] { args }, BindingFlags.InvokeMethod);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns the result of calling a method on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetResult(object binding, string methodName, object[] args)
{
return Invoke(binding, methodName, args, BindingFlags.InvokeMethod);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified property on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void SetProperty(object binding, string propertyName, object args)
{
Invoke(binding, propertyName, new[] { args }, BindingFlags.SetProperty);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified field (i.e. member variable) on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void SetField(object binding, string fieldName, object args)
{
Invoke(binding, fieldName, new[] { args }, BindingFlags.SetField);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the specified property on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetProperty(object binding, string propertyName)
{
return Invoke(binding, propertyName, null, BindingFlags.GetProperty);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the specified field (i.e. member variable) on the specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object GetField(object binding, string fieldName)
{
return Invoke(binding, fieldName, null, BindingFlags.GetField);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified member variable or property (specified by name) on the
/// specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
private static object Invoke(object binding, string name, object[] args, BindingFlags flags)
{
//if (CanInvoke(binding, name, flags))
{
try
{
return InvokeWithError(binding, name, args, flags);
}
catch { }
}
return null;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Calls a method specified on the specified binding, throwing any exceptions that
/// may occur.
/// </summary>
/// ------------------------------------------------------------------------------------
public static object CallMethodWithThrow(object binding, string name, params object[] args)
{
return InvokeWithError(binding, name, args, BindingFlags.InvokeMethod);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the specified member variable or property (specified by name) on the
/// specified binding.
/// </summary>
/// ------------------------------------------------------------------------------------
private static object InvokeWithError(object binding, string name, object[] args, BindingFlags flags)
{
// If binding is a Type then assume invoke on a static method, property or field.
// Otherwise invoke on an instance method, property or field.
flags |= BindingFlags.NonPublic | BindingFlags.Public |
(binding is Type ? BindingFlags.Static : BindingFlags.Instance);
// If necessary, go up the inheritance chain until the name
// of the method, property or field is found.
Type type = binding is Type ? (Type)binding : binding.GetType();
while (type.GetMember(name, flags).Length == 0 && type.BaseType != null)
type = type.BaseType;
return type.InvokeMember(name, flags, null, binding, args);
}
///// ------------------------------------------------------------------------------------
///// <summary>
///// Gets a value indicating whether or not the specified binding contains the field,
///// property or method indicated by name and having the specified flags.
///// </summary>
///// ------------------------------------------------------------------------------------
//private static bool CanInvoke(object binding, string name, BindingFlags flags)
//{
// var srchFlags = (BindingFlags.Public | BindingFlags.NonPublic);
// Type bindingType = null;
// if (binding is Type)
// {
// bindingType = (Type)binding;
// srchFlags |= BindingFlags.Static;
// }
// else
// {
// binding.GetType();
// srchFlags |= BindingFlags.Instance;
// }
// if (((flags & BindingFlags.GetProperty) == BindingFlags.GetProperty) ||
// ((flags & BindingFlags.SetProperty) == BindingFlags.SetProperty))
// {
// return (bindingType.GetProperty(name, srchFlags) != null);
// }
// if (((flags & BindingFlags.GetField) == BindingFlags.GetField) ||
// ((flags & BindingFlags.SetField) == BindingFlags.SetField))
// {
// return (bindingType.GetField(name, srchFlags) != null);
// }
// if ((flags & BindingFlags.InvokeMethod) == BindingFlags.InvokeMethod)
// return (bindingType.GetMethod(name, srchFlags) != null);
// return false;
//}
public static string VersionNumberString
{
get
{
/* object attr = GetAssemblyAttribute(typeof (AssemblyFileVersionAttribute));
if (attr != null)
{
return ((AssemblyFileVersionAttribute) attr).Version;
}
return Application.ProductVersion;
*/
var ver = Assembly.GetEntryAssembly().GetName().Version;
return string.Format("Version {0}.{1}.{2}", ver.Major, ver.Minor, ver.Build);
}
}
public static string LongVersionNumberString
{
get
{
Assembly assembly = Assembly.GetEntryAssembly();
if (assembly != null)
{
string version = VersionNumberString;
version += " (apparent build date: ";
try
{
string path = PathHelper.StripFilePrefix(assembly.CodeBase);
version += File.GetLastWriteTimeUtc(path).ToString("dd-MMM-yyyy") + ")";
}
catch
{
version += "???";
}
#if DEBUG
version += " (Debug version)";
#endif
return version;
}
return "unknown";
}
}
public static string DirectoryOfTheApplicationExecutable
{
get
{
string path;
bool unitTesting = Assembly.GetEntryAssembly() == null;
if (unitTesting)
{
path = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath;
path = Uri.UnescapeDataString(path);
}
else
{
path = EntryAssembly.Location;
}
return Directory.GetParent(path).FullName;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.SS.Formula.Functions
{
using System;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using NUnit.Framework;
using NPOI.SS.Formula.Functions;
/**
* Tests for {@link Dec2Bin}
*
* @author cedric dot walter @ gmail dot com
*/
[TestFixture]
public class TestDec2Bin
{
private static ValueEval invokeValue(String number1)
{
ValueEval[] args = new ValueEval[] { new StringEval(number1) };
return new Dec2Bin().Evaluate(args, -1, -1);
}
private static ValueEval invokeBack(String number1)
{
ValueEval[] args = new ValueEval[] { new StringEval(number1) };
return new Bin2Dec().Evaluate(args, -1, -1);
}
private static void ConfirmValue(String msg, String number1, String expected)
{
ValueEval result = invokeValue(number1);
Assert.AreEqual(typeof(StringEval), result.GetType(), "Had: " + result.ToString());
Assert.AreEqual(expected, ((StringEval)result).StringValue, msg);
}
private static void ConfirmValueError(String msg, String number1, ErrorEval numError)
{
ValueEval result = invokeValue(number1);
Assert.AreEqual(typeof(ErrorEval), result.GetType());
Assert.AreEqual(numError, result, msg);
}
[Test]
public void TestBasic()
{
ConfirmValue("Converts binary '00101' from binary (5)", "5", "101");
ConfirmValue("Converts binary '1111111111' from binary (-1)", "-1", "1111111111");
ConfirmValue("Converts binary '1111111110' from binary (-2)", "-2", "1111111110");
ConfirmValue("Converts binary '0111111111' from binary (511)", "511", "111111111");
ConfirmValue("Converts binary '1000000000' from binary (511)", "-512", "1000000000");
}
[Test]
public void TestErrors()
{
ConfirmValueError("fails for >= 512 or < -512", "512", ErrorEval.NUM_ERROR);
ConfirmValueError("fails for >= 512 or < -512", "-513", ErrorEval.NUM_ERROR);
ConfirmValueError("not a valid decimal number", "GGGGGGG", ErrorEval.VALUE_INVALID);
ConfirmValueError("not a valid decimal number", "3.14159a", ErrorEval.VALUE_INVALID);
}
[Test]
public void TestEvalOperationEvaluationContext()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0) };
ValueEval result = new Dec2Bin().Evaluate(args, ctx);
Assert.AreEqual(typeof(StringEval), result.GetType());
Assert.AreEqual("1101", ((StringEval)result).StringValue);
}
[Test]
public void TestEvalOperationEvaluationContextFails()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ErrorEval.VALUE_INVALID };
ValueEval result = new Dec2Bin().Evaluate(args, ctx);
Assert.AreEqual(typeof(ErrorEval), result.GetType());
Assert.AreEqual(ErrorEval.VALUE_INVALID, result);
}
private OperationEvaluationContext CreateContext()
{
HSSFWorkbook wb = new HSSFWorkbook();
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
cell.SetCellValue("13.43");
cell = row.CreateCell(1);
cell.SetCellValue("8");
cell = row.CreateCell(2);
cell.SetCellValue("-8");
cell = row.CreateCell(3);
cell.SetCellValue("1");
HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.Create(wb);
WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, new IStabilityClassifier1(), null);
OperationEvaluationContext ctx = new OperationEvaluationContext(workbookEvaluator,
workbook, 0, 0, 0, null);
return ctx;
}
class IStabilityClassifier1 : IStabilityClassifier
{
public override bool IsCellFinal(int sheetIndex, int rowIndex, int columnIndex)
{
return true;
}
}
[Test]
public void TestRefs()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0) };
ValueEval result = new Dec2Bin().Evaluate(args, -1, -1);
Assert.AreEqual(result.GetType(), typeof(StringEval), "Had: " + result.ToString());
Assert.AreEqual("1101", ((StringEval)result).StringValue);
}
[Test]
public void TestWithPlacesIntInt()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0), ctx.GetRefEval(0, 1) };
ValueEval result = new Dec2Bin().Evaluate(args, -1, -1);
Assert.AreEqual(typeof(StringEval), result.GetType(), "Had: " + result.ToString());
// TODO: documentation and behavior do not match here!
Assert.AreEqual("1101", ((StringEval)result).StringValue);
}
[Test]
public void TestWithPlaces()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0), ctx.GetRefEval(0, 1) };
ValueEval result = new Dec2Bin().Evaluate(args, ctx);
Assert.AreEqual(typeof(StringEval), result.GetType(), "Had: " + result.ToString());
// TODO: documentation and behavior do not match here!
Assert.AreEqual("1101", ((StringEval)result).StringValue);
}
[Test]
public void TestWithToshortPlaces()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0), ctx.GetRefEval(0, 3) };
ValueEval result = new Dec2Bin().Evaluate(args, -1, -1);
Assert.AreEqual(typeof(ErrorEval), result.GetType());
Assert.AreEqual(ErrorEval.NUM_ERROR, result);
}
[Test]
public void TestWithTooManyParamsIntInt()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0), ctx.GetRefEval(0, 1), ctx.GetRefEval(0, 1) };
ValueEval result = new Dec2Bin().Evaluate(args, -1, -1);
Assert.AreEqual(typeof(ErrorEval), result.GetType());
Assert.AreEqual(ErrorEval.VALUE_INVALID, result);
}
[Test]
public void TestWithTooManyParams()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0), ctx.GetRefEval(0, 1), ctx.GetRefEval(0, 1) };
ValueEval result = new Dec2Bin().Evaluate(args, ctx);
Assert.AreEqual(typeof(ErrorEval), result.GetType());
Assert.AreEqual(ErrorEval.VALUE_INVALID, result);
}
[Test]
public void TestWithErrorPlaces()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0), ErrorEval.NULL_INTERSECTION };
ValueEval result = new Dec2Bin().Evaluate(args, -1, -1);
Assert.AreEqual(typeof(ErrorEval), result.GetType());
Assert.AreEqual(ErrorEval.NULL_INTERSECTION, result);
}
[Test]
public void TestWithNegativePlaces()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0), ctx.GetRefEval(0, 2) };
ValueEval result = new Dec2Bin().Evaluate(args, -1, -1);
Assert.AreEqual(typeof(ErrorEval), result.GetType());
Assert.AreEqual(ErrorEval.NUM_ERROR, result);
}
[Test]
public void TestWithZeroPlaces()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0), new NumberEval(0.0) };
ValueEval result = new Dec2Bin().Evaluate(args, -1, -1);
Assert.AreEqual(typeof(ErrorEval), result.GetType());
Assert.AreEqual(ErrorEval.NUM_ERROR, result);
}
[Test]
public void TestWithEmptyPlaces()
{
OperationEvaluationContext ctx = CreateContext();
ValueEval[] args = new ValueEval[] { ctx.GetRefEval(0, 0), ctx.GetRefEval(1, 0) };
ValueEval result = new Dec2Bin().Evaluate(args, -1, -1);
Assert.AreEqual(typeof(ErrorEval), result.GetType());
Assert.AreEqual(ErrorEval.VALUE_INVALID, result);
}
[Test]
public void TestBackAndForth()
{
for (int i = -512; i < 512; i++)
{
ValueEval result = invokeValue(i.ToString());
Assert.AreEqual(typeof(StringEval), result.GetType(), "Had: " + result.ToString());
ValueEval back = invokeBack(((StringEval)result).StringValue);
Assert.AreEqual(typeof(NumberEval), back.GetType(), "Had: " + back.ToString());
Assert.AreEqual(i.ToString(), ((NumberEval)back).StringValue);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Feedback.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using Roslyn.VisualStudio.ProjectSystem;
using VSLangProj;
using VSLangProj140;
using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
/// <summary>
/// The Workspace for running inside Visual Studio.
/// </summary>
internal abstract class VisualStudioWorkspaceImpl : VisualStudioWorkspace
{
private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1);
private const string AppCodeFolderName = "App_Code";
protected readonly IServiceProvider ServiceProvider;
private readonly IVsUIShellOpenDocument _shellOpenDocument;
private readonly IVsTextManager _textManager;
// Not readonly because it needs to be set in the derived class' constructor.
private VisualStudioProjectTracker _projectTracker;
// document worker coordinator
private ISolutionCrawlerRegistrationService _registrationService;
public VisualStudioWorkspaceImpl(
SVsServiceProvider serviceProvider,
WorkspaceBackgroundWork backgroundWork)
: base(
CreateHostServices(serviceProvider),
backgroundWork)
{
this.ServiceProvider = serviceProvider;
_textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager;
_shellOpenDocument = serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
// Ensure the options factory services are initialized on the UI thread
this.Services.GetService<IOptionService>();
var session = serviceProvider.GetService(typeof(SVsLog)) as IVsSqmMulti;
var profileService = serviceProvider.GetService(typeof(SVsFeedbackProfile)) as IVsFeedbackProfile;
// We have Watson hits where this came back null, so guard against it
if (profileService != null)
{
Sqm.LogSession(session, profileService.IsMicrosoftInternal);
}
}
internal static HostServices CreateHostServices(SVsServiceProvider serviceProvider)
{
var composition = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
return MefV1HostServices.Create(composition.DefaultExportProvider);
}
protected void InitializeStandardVisualStudioWorkspace(SVsServiceProvider serviceProvider, SaveEventsService saveEventsService)
{
var projectTracker = new VisualStudioProjectTracker(serviceProvider);
// Ensure the document tracking service is initialized on the UI thread
var documentTrackingService = this.Services.GetService<IDocumentTrackingService>();
var documentProvider = new RoslynDocumentProvider(projectTracker, serviceProvider, documentTrackingService);
projectTracker.DocumentProvider = documentProvider;
projectTracker.MetadataReferenceProvider = this.Services.GetService<VisualStudioMetadataReferenceManager>();
projectTracker.RuleSetFileProvider = this.Services.GetService<VisualStudioRuleSetManager>();
this.SetProjectTracker(projectTracker);
var workspaceHost = new VisualStudioWorkspaceHost(this);
projectTracker.RegisterWorkspaceHost(workspaceHost);
projectTracker.StartSendingEventsToWorkspaceHost(workspaceHost);
saveEventsService.StartSendingSaveEvents();
// Ensure the options factory services are initialized on the UI thread
this.Services.GetService<IOptionService>();
}
/// <summary>NOTE: Call only from derived class constructor</summary>
protected void SetProjectTracker(VisualStudioProjectTracker projectTracker)
{
_projectTracker = projectTracker;
}
internal VisualStudioProjectTracker ProjectTracker
{
get
{
return _projectTracker;
}
}
internal void ClearReferenceCache()
{
_projectTracker.MetadataReferenceProvider.ClearCache();
}
internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId)
{
var project = GetHostProject(documentId.ProjectId);
if (project != null)
{
return project.GetDocumentOrAdditionalDocument(documentId);
}
return null;
}
internal IVisualStudioHostProject GetHostProject(ProjectId projectId)
{
return this.ProjectTracker.GetProject(projectId);
}
private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project)
{
project = GetHostProject(projectId);
return project != null;
}
public override bool TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution)
{
// first make sure we can edit the document we will be updating (check them out from source control, etc)
var changedDocs = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().SelectMany(pd => pd.GetChangedDocuments()).ToList();
if (changedDocs.Count > 0)
{
this.EnsureEditableDocuments(changedDocs);
}
return base.TryApplyChanges(newSolution);
}
public override bool CanOpenDocuments
{
get
{
return true;
}
}
internal override bool CanChangeActiveContextDocument
{
get
{
return true;
}
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.AddDocument:
case ApplyChangesKind.RemoveDocument:
case ApplyChangesKind.ChangeDocument:
case ApplyChangesKind.AddMetadataReference:
case ApplyChangesKind.RemoveMetadataReference:
case ApplyChangesKind.AddProjectReference:
case ApplyChangesKind.RemoveProjectReference:
case ApplyChangesKind.AddAnalyzerReference:
case ApplyChangesKind.RemoveAnalyzerReference:
case ApplyChangesKind.AddAdditionalDocument:
case ApplyChangesKind.RemoveAdditionalDocument:
case ApplyChangesKind.ChangeAdditionalDocument:
return true;
default:
return false;
}
}
private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project)
{
hierarchy = null;
project = null;
return this.TryGetHostProject(projectId, out hostProject)
&& this.TryGetHierarchy(projectId, out hierarchy)
&& hierarchy.TryGetProject(out project);
}
internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project)
{
if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project))
{
throw new ArgumentException(string.Format(ServicesVSResources.CouldNotFindProject, projectId));
}
}
internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName)
{
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
try
{
GetProjectData(projectId, out hostProject, out hierarchy, out project);
}
catch (ArgumentException)
{
return false;
}
var vsProject = (VSProject)project.Object;
try
{
vsProject.References.Add(assemblyName);
}
catch (Exception)
{
return false;
}
return true;
}
private string GetAnalyzerPath(AnalyzerReference analyzerReference)
{
return analyzerReference.FullPath;
}
protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
{
if (projectId == null)
{
throw new ArgumentNullException("projectId");
}
if (analyzerReference == null)
{
throw new ArgumentNullException("analyzerReference");
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetAnalyzerPath(analyzerReference);
if (filePath != null)
{
VSProject3 vsProject = (VSProject3)project.Object;
vsProject.AnalyzerReferences.Add(filePath);
}
}
protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
{
if (projectId == null)
{
throw new ArgumentNullException("projectId");
}
if (analyzerReference == null)
{
throw new ArgumentNullException("analyzerReference");
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetAnalyzerPath(analyzerReference);
if (filePath != null)
{
VSProject3 vsProject = (VSProject3)project.Object;
vsProject.AnalyzerReferences.Remove(filePath);
}
}
private string GetMetadataPath(MetadataReference metadataReference)
{
var fileMetadata = metadataReference as PortableExecutableReference;
if (fileMetadata != null)
{
return fileMetadata.FilePath;
}
return null;
}
protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference)
{
if (projectId == null)
{
throw new ArgumentNullException("projectId");
}
if (metadataReference == null)
{
throw new ArgumentNullException("metadataReference");
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetMetadataPath(metadataReference);
if (filePath != null)
{
VSProject vsProject = (VSProject)project.Object;
vsProject.References.Add(filePath);
}
}
protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference)
{
if (projectId == null)
{
throw new ArgumentNullException("projectId");
}
if (metadataReference == null)
{
throw new ArgumentNullException("metadataReference");
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
string filePath = GetMetadataPath(metadataReference);
if (filePath != null)
{
VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object;
VSLangProj.Reference reference = vsProject.References.Find(filePath);
if (reference != null)
{
reference.Remove();
}
}
}
protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
{
if (projectId == null)
{
throw new ArgumentNullException("projectId");
}
if (projectReference == null)
{
throw new ArgumentNullException("projectReference");
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
IVisualStudioHostProject refHostProject;
IVsHierarchy refHierarchy;
EnvDTE.Project refProject;
GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject);
VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object;
vsProject.References.AddProject(refProject);
}
protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
{
if (projectId == null)
{
throw new ArgumentNullException("projectId");
}
if (projectReference == null)
{
throw new ArgumentNullException("projectReference");
}
IVisualStudioHostProject hostProject;
IVsHierarchy hierarchy;
EnvDTE.Project project;
GetProjectData(projectId, out hostProject, out hierarchy, out project);
IVisualStudioHostProject refHostProject;
IVsHierarchy refHierarchy;
EnvDTE.Project refProject;
GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject);
VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object;
foreach (VSLangProj.Reference reference in vsProject.References)
{
if (reference.SourceProject == refProject)
{
reference.Remove();
}
}
}
protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text)
{
AddDocumentCore(info, text, isAdditionalDocument: false);
}
protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text)
{
AddDocumentCore(info, text, isAdditionalDocument: true);
}
private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument)
{
IVsHierarchy hierarchy;
EnvDTE.Project project;
IVisualStudioHostProject hostProject;
GetProjectData(info.Id.ProjectId, out hostProject, out hierarchy, out project);
// If the first namespace name matches the name of the project, then we don't want to
// generate a folder for that. The project is implicitly a folder with that name.
var folders = info.Folders.AsEnumerable();
if (folders.FirstOrDefault() == project.Name)
{
folders = folders.Skip(1);
}
folders = FilterFolderForProjectType(project, folders);
if (IsWebsite(project))
{
AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
else if (folders.Any())
{
AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
else
{
AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument);
}
}
private bool IsWebsite(EnvDTE.Project project)
{
return project.Kind == VsWebSite.PrjKind.prjKindVenusProject;
}
private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders)
{
foreach (var folder in folders)
{
var items = GetAllItems(project.ProjectItems);
var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0);
if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile)
{
yield return folder;
}
}
}
private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems)
{
if (projectItems == null)
{
return SpecializedCollections.EmptyEnumerable<ProjectItem>();
}
var items = projectItems.OfType<ProjectItem>();
return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems)));
}
#if false
protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders)
{
IVsHierarchy hierarchy;
EnvDTE.Project project;
IVisualStudioHostProject hostProject;
GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project);
// If the first namespace name matches the name of the project, then we don't want to
// generate a folder for that. The project is implicitly a folder with that name.
if (folders.FirstOrDefault() == project.Name)
{
folders = folders.Skip(1);
}
var name = Path.GetFileName(filePath);
if (folders.Any())
{
AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath);
}
else
{
AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath);
}
}
#endif
private ProjectItem AddDocumentToProject(
IVisualStudioHostProject hostProject,
EnvDTE.Project project,
DocumentId documentId,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText = null,
string filePath = null,
bool isAdditionalDocument = false)
{
string folderPath;
if (!project.TryGetFullPath(out folderPath))
{
// TODO(cyrusn): Throw an appropriate exception here.
throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol);
}
return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument);
}
private ProjectItem AddDocumentToFolder(
IVisualStudioHostProject hostProject,
EnvDTE.Project project,
DocumentId documentId,
IEnumerable<string> folders,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText = null,
string filePath = null,
bool isAdditionalDocument = false)
{
var folder = project.FindOrCreateFolder(folders);
string folderPath;
if (!folder.TryGetFullPath(out folderPath))
{
// TODO(cyrusn): Throw an appropriate exception here.
throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol);
}
return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument);
}
private ProjectItem AddDocumentToProjectItems(
IVisualStudioHostProject hostProject,
ProjectItems projectItems,
DocumentId documentId,
string folderPath,
string documentName,
SourceCodeKind sourceCodeKind,
SourceText initialText,
string filePath,
bool isAdditionalDocument)
{
if (filePath == null)
{
var baseName = Path.GetFileNameWithoutExtension(documentName);
var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind);
var uniqueName = projectItems.GetUniqueName(baseName, extension);
filePath = Path.Combine(folderPath, uniqueName);
}
if (initialText != null)
{
using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8))
{
initialText.Write(writer);
}
}
using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId))
{
return projectItems.AddFromFile(filePath);
}
}
protected void RemoveDocumentCore(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException("documentId");
}
var document = this.GetHostDocument(documentId);
if (document != null)
{
var project = document.Project.Hierarchy as IVsProject3;
var itemId = document.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// it is no longer part of the solution
return;
}
int result;
project.RemoveItem(0, itemId, out result);
}
}
protected override void ApplyDocumentRemoved(DocumentId documentId)
{
RemoveDocumentCore(documentId);
}
protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId)
{
RemoveDocumentCore(documentId);
}
public override void OpenDocument(DocumentId documentId, bool activate = true)
{
OpenDocumentCore(documentId, activate);
}
public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true)
{
OpenDocumentCore(documentId, activate);
}
public override void CloseDocument(DocumentId documentId)
{
CloseDocumentCore(documentId);
}
public override void CloseAdditionalDocument(DocumentId documentId)
{
CloseDocumentCore(documentId);
}
public bool TryGetInfoBarData(DocumentId documentId, out IVsWindowFrame frame, out IVsInfoBarUIFactory factory)
{
if (documentId == null)
{
frame = null;
factory = null;
return false;
}
var document = this.GetHostDocument(documentId);
if (TryGetFrame(document, out frame))
{
factory = ServiceProvider.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory;
return frame != null && factory != null;
}
frame = null;
factory = null;
return false;
}
public void OpenDocumentCore(DocumentId documentId, bool activate = true)
{
if (documentId == null)
{
throw new ArgumentNullException("documentId");
}
var document = this.GetHostDocument(documentId);
if (document != null && document.Project != null)
{
IVsWindowFrame frame;
if (TryGetFrame(document, out frame))
{
if (activate)
{
frame.Show();
}
else
{
frame.ShowNoActivate();
}
}
}
}
private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame)
{
frame = null;
var itemId = document.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// If the ItemId is Nil, then then IVsProject would not be able to open the
// document using its ItemId. Thus, we must use OpenDocumentViaProject, which only
// depends on the file path.
uint itemid;
IVsUIHierarchy uiHierarchy;
OLEServiceProvider oleServiceProvider;
return ErrorHandler.Succeeded(_shellOpenDocument.OpenDocumentViaProject(
document.FilePath,
VSConstants.LOGVIEWID.TextView_guid,
out oleServiceProvider,
out uiHierarchy,
out itemid,
out frame));
}
else
{
// If the ItemId is not Nil, then we should not call IVsUIShellDocument
// .OpenDocumentViaProject here because that simply takes a file path and opens the
// file within the context of the first project it finds. That would cause problems
// if the document we're trying to open is actually a linked file in another
// project. So, we get the project's hierarchy and open the document using its item
// ID.
// It's conceivable that IVsHierarchy might not implement IVsProject. However,
// OpenDocumentViaProject itself relies upon this QI working, so it should be OK to
// use here.
var vsProject = document.Project.Hierarchy as IVsProject;
return vsProject != null &&
ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame));
}
}
public void CloseDocumentCore(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException("documentId");
}
if (this.IsDocumentOpen(documentId))
{
var document = this.GetHostDocument(documentId);
if (document != null)
{
IVsUIHierarchy uiHierarchy;
IVsWindowFrame frame;
int isOpen;
if (ErrorHandler.Succeeded(_shellOpenDocument.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out uiHierarchy, null, out frame, out isOpen)))
{
// TODO: do we need save argument for CloseDocument?
frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
}
}
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
{
EnsureEditableDocuments(documentId);
var hostDocument = GetHostDocument(documentId);
hostDocument.UpdateText(newText);
}
protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText)
{
EnsureEditableDocuments(documentId);
var hostDocument = GetHostDocument(documentId);
hostDocument.UpdateText(newText);
}
private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind)
{
// No extension was provided. Pick a good one based on the type of host project.
switch (hostProject.Language)
{
case LanguageNames.CSharp:
return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx";
case LanguageNames.VisualBasic:
return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx";
default:
throw new InvalidOperationException();
}
}
public override IVsHierarchy GetHierarchy(ProjectId projectId)
{
var project = this.GetHostProject(projectId);
if (project == null)
{
return null;
}
return project.Hierarchy;
}
internal override void SetDocumentContext(DocumentId documentId)
{
var hostDocument = GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var hierarchy = hostDocument.Project.Hierarchy;
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId);
if (sharedHierarchy != null)
{
if (sharedHierarchy.SetProperty(
(uint)VSConstants.VSITEMID.Root,
(int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext,
ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK)
{
// The ASP.NET 5 intellisense project is now updated.
return;
}
else
{
// Universal Project shared files
// Change the SharedItemContextHierarchy of the project's parent hierarchy, then
// hierarchy events will trigger the workspace to update.
var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy);
}
}
else
{
// Regular linked files
// Transfer the item (open buffer) to the new hierarchy, and then hierarchy events
// will trigger the workspace to update.
var vsproj = hierarchy as IVsProject3;
var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null);
}
}
internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId)
{
// TODO: This is a very roundabout way to update the context
// The sharedHierarchy passed in has a new context, but we don't know what it is.
// The documentId passed in is associated with this sharedHierarchy, and this method
// will be called once for each such documentId. During this process, one of these
// documentIds will actually belong to the new SharedItemContextHierarchy. Once we
// find that one, we can map back to the open buffer and set its active context to
// the appropriate project.
var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker);
if (hostProject.Hierarchy == sharedHierarchy)
{
// How?
return;
}
if (hostProject.Id != documentId.ProjectId)
{
// While this documentId is associated with one of the head projects for this
// sharedHierarchy, it is not associated with the new context hierarchy. Another
// documentId will be passed to this method and update the context.
return;
}
// This documentId belongs to the new SharedItemContextHierarchy. Update the associated
// buffer.
OnDocumentContextUpdated(documentId);
}
/// <summary>
/// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that
/// is in the current context. For regular files (non-shared and non-linked) and closed
/// linked files, this is always the provided <see cref="DocumentId"/>. For open linked
/// files and open shared files, the active context is already tracked by the
/// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the
/// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/>
/// is preferred.
/// </summary>
internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId)
{
// If the document is open, then the Workspace knows the current context for both
// linked and shared files
if (IsDocumentOpen(documentId))
{
return base.GetDocumentIdInCurrentContext(documentId);
}
var hostDocument = GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// An itemid is required to determine whether the file belongs to a Shared Project
return base.GetDocumentIdInCurrentContext(documentId);
}
// If this is a regular document or a closed linked (non-shared) document, then use the
// default logic for determining current context.
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);
if (sharedHierarchy == null)
{
return base.GetDocumentIdInCurrentContext(documentId);
}
// This is a closed shared document, so we must determine the correct context.
var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker);
var matchingProject = CurrentSolution.GetProject(hostProject.Id);
if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy)
{
return base.GetDocumentIdInCurrentContext(documentId);
}
if (matchingProject.ContainsDocument(documentId))
{
// The provided documentId is in the current context project
return documentId;
}
// The current context document is from another project.
var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds();
var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id);
return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId);
}
private bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy)
{
hierarchy = this.GetHierarchy(projectId);
return hierarchy != null;
}
public override string GetFilePath(DocumentId documentId)
{
var document = this.GetHostDocument(documentId);
if (document == null)
{
return null;
}
else
{
return document.FilePath;
}
}
internal void StartSolutionCrawler()
{
if (_registrationService == null)
{
lock (this)
{
if (_registrationService == null)
{
_registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>();
_registrationService.Register(this);
}
}
}
}
internal void StopSolutionCrawler()
{
if (_registrationService != null)
{
lock (this)
{
if (_registrationService != null)
{
_registrationService.Unregister(this, blockingShutdown: true);
_registrationService = null;
}
}
}
}
protected override void Dispose(bool finalize)
{
// workspace is going away. unregister this workspace from work coordinator
StopSolutionCrawler();
base.Dispose(finalize);
}
public void EnsureEditableDocuments(IEnumerable<DocumentId> documents)
{
var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GetService(typeof(SVsQueryEditQuerySave));
var fileNames = documents.Select(GetFilePath).ToArray();
uint editVerdict;
uint editResultFlags;
// TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn
int result = queryEdit.QueryEditFiles(
rgfQueryEdit: 0,
cFiles: fileNames.Length,
rgpszMkDocuments: fileNames,
rgrgf: new uint[fileNames.Length],
rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length],
pfEditVerdict: out editVerdict,
prgfMoreInfo: out editResultFlags);
if (ErrorHandler.Failed(result) ||
editVerdict != (uint)tagVSQueryEditResult.QER_EditOK)
{
throw new Exception("Unable to check out the files from source control.");
}
if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0)
{
throw new Exception("A file was reloaded during the source control checkout.");
}
}
public void EnsureEditableDocuments(params DocumentId[] documents)
{
this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents);
}
internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId)
{
var vsDoc = this.GetHostDocument(documentId);
this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader);
}
internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId)
{
var vsDoc = this.GetHostDocument(documentId);
this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader);
}
public TInterface GetVsService<TService, TInterface>()
where TService : class
where TInterface : class
{
return this.ServiceProvider.GetService(typeof(TService)) as TInterface;
}
/// <summary>
/// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just
/// forwards the calls down to the underlying Workspace.
/// </summary>
protected class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkingFolder
{
private readonly VisualStudioWorkspaceImpl _workspace;
private Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>();
public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace)
{
_workspace = workspace;
}
void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions)
{
_workspace.OnCompilationOptionsChanged(projectId, compilationOptions);
_workspace.OnParseOptionsChanged(projectId, parseOptions);
}
void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo)
{
_workspace.OnDocumentAdded(documentInfo);
}
void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext)
{
// TODO: Move this out to DocumentProvider. As is, this depends on being able to
// access the host document which will already be deleted in some cases, causing
// a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a
// Mercury shared document is closed.
// UnsubscribeFromSharedHierarchyEvents(documentId);
using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed"))
{
_workspace.OnDocumentClosed(documentId, loader, updateActiveContext);
}
}
void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext)
{
SubscribeToSharedHierarchyEvents(documentId);
_workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext);
}
private void SubscribeToSharedHierarchyEvents(DocumentId documentId)
{
// Todo: maybe avoid double alerts.
var hostDocument = _workspace.GetHostDocument(documentId);
if (hostDocument == null)
{
return;
}
var hierarchy = hostDocument.Project.Hierarchy;
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId);
if (sharedHierarchy != null)
{
uint cookie;
var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId);
var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out cookie);
if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId))
{
_documentIdToHierarchyEventsCookieMap.Add(documentId, cookie);
}
}
}
private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId)
{
var hostDocument = _workspace.GetHostDocument(documentId);
var itemId = hostDocument.GetItemId();
if (itemId == (uint)VSConstants.VSITEMID.Nil)
{
// the document has been removed from the solution
return;
}
var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId);
if (sharedHierarchy != null)
{
uint cookie;
if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out cookie))
{
var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie);
_documentIdToHierarchyEventsCookieMap.Remove(documentId);
}
}
}
private void RegisterPrimarySolutionForPersistentStorage(SolutionId solutionId)
{
var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService;
if (service == null)
{
return;
}
service.RegisterPrimarySolution(solutionId);
}
private void UnregisterPrimarySolutionForPersistentStorage(SolutionId solutionId, bool synchronousShutdown)
{
var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService;
if (service == null)
{
return;
}
service.UnregisterPrimarySolution(solutionId, synchronousShutdown);
}
void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId)
{
_workspace.OnDocumentRemoved(documentId);
}
void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference)
{
_workspace.OnMetadataReferenceAdded(projectId, metadataReference);
}
void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference)
{
_workspace.OnMetadataReferenceRemoved(projectId, metadataReference);
}
void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo)
{
using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project"))
{
_workspace.OnProjectAdded(projectInfo);
}
}
void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
{
_workspace.OnProjectReferenceAdded(projectId, projectReference);
}
void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
{
_workspace.OnProjectReferenceRemoved(projectId, projectReference);
}
void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId)
{
using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project"))
{
_workspace.OnProjectRemoved(projectId);
}
}
void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo)
{
RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id);
_workspace.OnSolutionAdded(solutionInfo);
}
void IVisualStudioWorkspaceHost.OnSolutionRemoved()
{
var solutionId = _workspace.CurrentSolution.Id;
_workspace.OnSolutionRemoved();
_workspace.ClearReferenceCache();
UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false);
}
void IVisualStudioWorkspaceHost.ClearSolution()
{
_workspace.ClearSolution();
_workspace.ClearReferenceCache();
}
void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id)
{
_workspace.OnDocumentTextUpdatedOnDisk(id);
}
void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName)
{
_workspace.OnAssemblyNameChanged(id, assemblyName);
}
void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath)
{
_workspace.OnOutputFilePathChanged(id, outputFilePath);
}
void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath)
{
_workspace.OnProjectNameChanged(projectId, name, filePath);
}
void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
{
_workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference);
}
void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
{
_workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo additionalDocumentInfo)
{
_workspace.OnAdditionalDocumentAdded(additionalDocumentInfo);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId additionalDocumentId)
{
_workspace.OnAdditionalDocumentRemoved(additionalDocumentId);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext)
{
_workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader)
{
_workspace.OnAdditionalDocumentClosed(documentId, loader);
}
void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id)
{
_workspace.OnAdditionalDocumentTextUpdatedOnDisk(id);
}
void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange()
{
UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true);
}
void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange()
{
var solutionId = _workspace.CurrentSolution.Id;
_workspace.ProjectTracker.UpdateSolutionProperties(solutionId);
RegisterPrimarySolutionForPersistentStorage(solutionId);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents an expression that applies a delegate or lambda expression to a list of argument expressions.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.InvocationExpressionProxy))]
public class InvocationExpression : Expression, IArgumentProvider
{
private readonly Expression _lambda;
private readonly Type _returnType;
internal InvocationExpression(Expression lambda, Type returnType)
{
_lambda = lambda;
_returnType = returnType;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents.
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type
{
get { return _returnType; }
}
/// <summary>
/// Returns the node type of this Expression. Extension nodes should return
/// ExpressionType.Extension when overriding this method.
/// </summary>
/// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Invoke; }
}
/// <summary>
/// Gets the delegate or lambda expression to be applied.
/// </summary>
public Expression Expression
{
get { return _lambda; }
}
/// <summary>
/// Gets the arguments that the delegate or lambda expression is applied to.
/// </summary>
public ReadOnlyCollection<Expression> Arguments
{
get { return GetOrMakeArguments(); }
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="expression">The <see cref="Expression" /> property of the result.</param>
/// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public InvocationExpression Update(Expression expression, IEnumerable<Expression> arguments)
{
if (expression == Expression && arguments == Arguments)
{
return this;
}
return Expression.Invoke(expression, arguments);
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual ReadOnlyCollection<Expression> GetOrMakeArguments()
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
public virtual Expression GetArgument(int index)
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
public virtual int ArgumentCount
{
get
{
throw ContractUtils.Unreachable;
}
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitInvocation(this);
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
throw ContractUtils.Unreachable;
}
internal LambdaExpression LambdaOperand
{
get
{
return (_lambda.NodeType == ExpressionType.Quote)
? (LambdaExpression)((UnaryExpression)_lambda).Operand
: (_lambda as LambdaExpression);
}
}
}
#region Specialized Subclasses
internal class InvocationExpressionN : InvocationExpression
{
private IList<Expression> _arguments;
public InvocationExpressionN(Expression lambda, IList<Expression> arguments, Type returnType)
: base(lambda, returnType)
{
_arguments = arguments;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(ref _arguments);
}
public override Expression GetArgument(int index)
{
return _arguments[index];
}
public override int ArgumentCount
{
get
{
return _arguments.Count;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == _arguments.Count);
return Expression.Invoke(lambda, arguments ?? _arguments);
}
}
internal class InvocationExpression0 : InvocationExpression
{
public InvocationExpression0(Expression lambda, Type returnType)
: base(lambda, returnType)
{
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return EmptyReadOnlyCollection<Expression>.Instance;
}
public override Expression GetArgument(int index)
{
throw new InvalidOperationException();
}
public override int ArgumentCount
{
get
{
return 0;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 0);
return Expression.Invoke(lambda);
}
}
internal class InvocationExpression1 : InvocationExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
public InvocationExpression1(Expression lambda, Type returnType, Expression arg0)
: base(lambda, returnType)
{
_arg0 = arg0;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 1;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 1);
if (arguments != null)
{
return Expression.Invoke(lambda, arguments[0]);
}
return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0));
}
}
internal class InvocationExpression2 : InvocationExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd arg
public InvocationExpression2(Expression lambda, Type returnType, Expression arg0, Expression arg1)
: base(lambda, returnType)
{
_arg0 = arg0;
_arg1 = arg1;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 2;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 2);
if (arguments != null)
{
return Expression.Invoke(lambda, arguments[0], arguments[1]);
}
return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1);
}
}
internal class InvocationExpression3 : InvocationExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd arg
private readonly Expression _arg2; // storage for the 3rd arg
public InvocationExpression3(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2)
: base(lambda, returnType)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 3;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 3);
if (arguments != null)
{
return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2]);
}
return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1, _arg2);
}
}
internal class InvocationExpression4 : InvocationExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd arg
private readonly Expression _arg2; // storage for the 3rd arg
private readonly Expression _arg3; // storage for the 4th arg
public InvocationExpression4(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2, Expression arg3)
: base(lambda, returnType)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 4;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 4);
if (arguments != null)
{
return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2], arguments[3]);
}
return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3);
}
}
internal class InvocationExpression5 : InvocationExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd arg
private readonly Expression _arg2; // storage for the 3rd arg
private readonly Expression _arg3; // storage for the 4th arg
private readonly Expression _arg4; // storage for the 5th arg
public InvocationExpression5(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
: base(lambda, returnType)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
_arg4 = arg4;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
case 4: return _arg4;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 5;
}
}
internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments)
{
Debug.Assert(lambda != null);
Debug.Assert(arguments == null || arguments.Length == 5);
if (arguments != null)
{
return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
}
return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3, _arg4);
}
}
#endregion
public partial class Expression
{
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression with no arguments.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression)
{
// COMPAT: This method is marked as non-public to avoid a gap between a 0-ary and 2-ary overload (see remark for the unary case below).
RequiresCanRead(expression, nameof(expression));
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 0, pis);
return new InvocationExpression0(expression, method.ReturnType);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to one argument expression.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arg0">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an argument expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression, Expression arg0)
{
// COMPAT: This method is marked as non-public to ensure compile-time compatibility for Expression.Invoke(e, null).
RequiresCanRead(expression, nameof(expression));
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 1, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]);
return new InvocationExpression1(expression, method.ReturnType, arg0);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to two argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arg0">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument.
///</param>
///<param name="arg1">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an argument expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1)
{
// NB: This method is marked as non-public to avoid public API additions at this point.
RequiresCanRead(expression, nameof(expression));
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 2, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]);
return new InvocationExpression2(expression, method.ReturnType, arg0, arg1);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to three argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arg0">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument.
///</param>
///<param name="arg1">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument.
///</param>
///<param name="arg2">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the third argument.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an argument expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2)
{
// NB: This method is marked as non-public to avoid public API additions at this point.
RequiresCanRead(expression, nameof(expression));
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 3, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]);
arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2]);
return new InvocationExpression3(expression, method.ReturnType, arg0, arg1, arg2);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to four argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arg0">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument.
///</param>
///<param name="arg1">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument.
///</param>
///<param name="arg2">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the third argument.
///</param>
///<param name="arg3">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the fourth argument.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an argument expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2, Expression arg3)
{
// NB: This method is marked as non-public to avoid public API additions at this point.
RequiresCanRead(expression, nameof(expression));
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 4, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]);
arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2]);
arg3 = ValidateOneArgument(method, ExpressionType.Invoke, arg3, pis[3]);
return new InvocationExpression4(expression, method.ReturnType, arg0, arg1, arg2, arg3);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to five argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arg0">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument.
///</param>
///<param name="arg1">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument.
///</param>
///<param name="arg2">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the third argument.
///</param>
///<param name="arg3">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the fourth argument.
///</param>
///<param name="arg4">
///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the fifth argument.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an argument expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception>
internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
{
// NB: This method is marked as non-public to avoid public API additions at this point.
RequiresCanRead(expression, nameof(expression));
var method = GetInvokeMethod(expression);
var pis = GetParametersForValidation(method, ExpressionType.Invoke);
ValidateArgumentCount(method, ExpressionType.Invoke, 5, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]);
arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2]);
arg3 = ValidateOneArgument(method, ExpressionType.Invoke, arg3, pis[3]);
arg4 = ValidateOneArgument(method, ExpressionType.Invoke, arg4, pis[4]);
return new InvocationExpression5(expression, method.ReturnType, arg0, arg1, arg2, arg3, arg4);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to a list of argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arguments">
///An array of <see cref="T:System.Linq.Expressions.Expression" /> objects
///that represent the arguments that the delegate or lambda expression is applied to.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an element of <paramref name="arguments" /> is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///<paramref name="arguments" /> does not contain the same number of elements as the list of parameters for the delegate represented by <paramref name="expression" />.</exception>
public static InvocationExpression Invoke(Expression expression, params Expression[] arguments)
{
return Invoke(expression, (IEnumerable<Expression>)arguments);
}
///<summary>
///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies a delegate or lambda expression to a list of argument expressions.
///</summary>
///<returns>
///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that
///applies the specified delegate or lambda expression to the provided arguments.
///</returns>
///<param name="expression">
///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate
///or lambda expression to be applied.
///</param>
///<param name="arguments">
///An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Linq.Expressions.Expression" /> objects
///that represent the arguments that the delegate or lambda expression is applied to.
///</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="expression" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an element of <paramref name="arguments" /> is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception>
///<exception cref="T:System.InvalidOperationException">
///<paramref name="arguments" /> does not contain the same number of elements as the list of parameters for the delegate represented by <paramref name="expression" />.</exception>
public static InvocationExpression Invoke(Expression expression, IEnumerable<Expression> arguments)
{
var argumentList = arguments as IReadOnlyList<Expression> ?? arguments.ToReadOnly();
switch (argumentList.Count)
{
case 0:
return Invoke(expression);
case 1:
return Invoke(expression, argumentList[0]);
case 2:
return Invoke(expression, argumentList[0], argumentList[1]);
case 3:
return Invoke(expression, argumentList[0], argumentList[1], argumentList[2]);
case 4:
return Invoke(expression, argumentList[0], argumentList[1], argumentList[2], argumentList[3]);
case 5:
return Invoke(expression, argumentList[0], argumentList[1], argumentList[2], argumentList[3], argumentList[4]);
}
RequiresCanRead(expression, nameof(expression));
var args = argumentList.ToReadOnly(); // Ensure is TrueReadOnlyCollection when count > 5. Returns fast if it already is.
var mi = GetInvokeMethod(expression);
ValidateArgumentTypes(mi, ExpressionType.Invoke, ref args);
return new InvocationExpressionN(expression, args, mi.ReturnType);
}
/// <summary>
/// Gets the delegate's Invoke method; used by InvocationExpression.
/// </summary>
/// <param name="expression">The expression to be invoked.</param>
internal static MethodInfo GetInvokeMethod(Expression expression)
{
Type delegateType = expression.Type;
if (!expression.Type.IsSubclassOf(typeof(MulticastDelegate)))
{
Type exprType = TypeUtils.FindGenericType(typeof(Expression<>), expression.Type);
if (exprType == null)
{
throw Error.ExpressionTypeNotInvocable(expression.Type);
}
delegateType = exprType.GetGenericArguments()[0];
}
return delegateType.GetMethod("Invoke");
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="NUnit2Report.cs" company="Juan Pablo Olmos Lara (Jupaol)">
//
// NUnit2ReportTask.cs
//
// Author:
// Gilles Bayon (gilles.bayon@laposte.net)
// Updated Author:
// Thang Chung (email: thangchung@ymail.com, website: weblogs.asp.net/thangchung)
// Juan Pablo Olmos (email: jupaol@hotmail.com, website: http://jupaol.blogspot.com/)
//
// Copyright (C) 2010 ThangChung
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// </copyright>
// -----------------------------------------------------------------------
namespace NUnit2Report.Console
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using CuttingEdge.Conditions;
/// <summary>
/// Creates NUnit reports using XSL files. The reports can be created using Frames or without frames
/// </summary>
public class NUnit2Report
{
/// <summary>
/// Default output file name to be used if <see cref="OutputFilename"/> is nto specified
/// </summary>
private const string DefaultOutputFileName = "index.htm";
/// <summary>
/// Default directory name to be used if <see cref="OutputDirectory"/> is not specified
/// </summary>
private const string DefaultOutputDirectoryName = ".\\DefaultReport";
/// <summary>
/// XSL Frame definition file name
/// </summary>
private const string XslFrameDefinitionFileName = "NUnit-Frame.xsl";
/// <summary>
/// Xsl NoFrame definition file name
/// </summary>
private const string XslNoFrameDefinitionFileName = "NUnit-NoFrame.xsl";
/// <summary>
/// XSL Globalization definition file name
/// </summary>
/// <remarks>
/// Used to load the translations from the "Traductions.xml"
/// </remarks>
private const string XslGlobalizationDefinitionFileName = "i18n.xsl";
/// <summary>
/// Represents the XML summary document to be used in all transformations
/// </summary>
private XmlDocument xmlSummaryDocument;
/// <summary>
/// Represents the XSL Globalization definitions file path
/// </summary>
private string xslGlobalizationDefinitionFilePath;
/// <summary>
/// Rrepresents the common XSLT arguments sued in all transformations
/// </summary>
private XsltArgumentList commonXsltArguments;
/// <summary>
/// Represents the tool path - the current executing assembly path
/// </summary>
private string toolPath;
/// <summary>
/// Represents the Xsl Frames definiton file path (Full path)
/// </summary>
private string xslFrameDefintionFilePath;
/// <summary>
/// Rrepresents the Xsl NoFrames definition file path (full path)
/// </summary>
private string xslNoFrameDefinitionFilePath;
/// <summary>
/// Initializes a new instance of the <see cref="NUnit2Report"/> class.
/// </summary>
/// <param name="xmlNUnitResultFiles">The XML N unit result files.</param>
public NUnit2Report(IEnumerable<string> xmlNUnitResultFiles)
{
Condition.Requires(xmlNUnitResultFiles).IsNotNull().IsNotEmpty();
this.Format = ReportFormat.NoFrames;
this.Language = ReportLanguage.English;
this.XmlNUnitResultFiles = xmlNUnitResultFiles;
this.OpenDescription = false;
this.toolPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
this.xslGlobalizationDefinitionFilePath = Path.Combine(this.toolPath, "xsl\\" + XslGlobalizationDefinitionFileName);
}
/// <summary>
/// Gets or sets the format of the generated report.
/// Default to "noframes".
/// </summary>
public ReportFormat Format { get; set; }
/// <summary>
/// Gets or sets the output language.
/// </summary>
public ReportLanguage Language { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the description in the transformed html files will be opened.
/// </summary>
/// <value>
/// <c>true</c> if the description in the transformed html files will be opened; otherwise, <c>false</c>.
/// </value>
public bool OpenDescription { get; set; }
/// <summary>
/// Gets or sets the directory where the files resulting from the transformation should be written to.
/// </summary>
public string OutputDirectory { get; set; }
/// <summary>
/// Gets or sets the index of the Output HTML file(s).
/// Default to "index.htm".
/// </summary>
public string OutputFilename { get; set; }
/// <summary>
/// Gets the NUnit XML result files to use as input
/// </summary>
public IEnumerable<string> XmlNUnitResultFiles { get; private set; }
/// <summary>
/// This is where the work is done
/// </summary>
public void Execute()
{
this.ConfigureOptionslSettings();
this.CreateOutputDirectory();
this.commonXsltArguments = this.GetCommonXsltProperties();
this.xmlSummaryDocument = this.CreateSummaryXmlDoc();
switch (this.Format)
{
case ReportFormat.Frames:
this.CreateFramesReport();
break;
case ReportFormat.NoFrames:
this.CreateNoFramesReport();
break;
}
}
/// <summary>
/// Creates the frames report.
/// </summary>
private void CreateFramesReport()
{
#if ECHO_MODE
Console.WriteLine ("Initializing execution ...");
#endif
// create the index.html
var stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" +
"<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" +
"<xsl:include href=\"" + this.xslFrameDefintionFilePath + "\"/>" +
"<xsl:template match=\"test-results\">" +
" <xsl:call-template name=\"index.html\"/>" +
" </xsl:template>" +
" </xsl:stylesheet>");
this.Write(stream, Path.Combine(this.OutputDirectory, this.OutputFilename));
// create the stylesheet.css
stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" +
"<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" +
"<xsl:include href=\"" + this.xslFrameDefintionFilePath + "\"/>" +
"<xsl:template match=\"test-results\">" +
" <xsl:call-template name=\"stylesheet.css\"/>" +
" </xsl:template>" +
" </xsl:stylesheet>");
this.Write(stream, Path.Combine(this.OutputDirectory, "stylesheet.css"));
// create the overview-summary.html at the root
stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" +
"<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" +
"<xsl:include href=\"" + this.xslFrameDefintionFilePath + "\"/>" +
"<xsl:template match=\"test-results\">" +
" <xsl:call-template name=\"overview.packages\"/>" +
" </xsl:template>" +
" </xsl:stylesheet>");
this.Write(stream, Path.Combine(this.OutputDirectory, "overview-summary.html"));
// create the allclasses-frame.html at the root
stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" +
"<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" +
"<xsl:include href=\"" + this.xslFrameDefintionFilePath + "\"/>" +
"<xsl:template match=\"test-results\">" +
" <xsl:call-template name=\"all.classes\"/>" +
" </xsl:template>" +
" </xsl:stylesheet>");
this.Write(stream, Path.Combine(this.OutputDirectory, "allclasses-frame.html"));
// create the overview-frame.html at the root
stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" +
"<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" +
"<xsl:include href=\"" + this.xslFrameDefintionFilePath + "\"/>" +
"<xsl:template match=\"test-results\">" +
" <xsl:call-template name=\"all.packages\"/>" +
" </xsl:template>" +
" </xsl:stylesheet>");
this.Write(stream, Path.Combine(this.OutputDirectory, "overview-frame.html"));
// Create directory
string path;
// --- Change 11/02/2003 -- remove
////XmlDocument doc = new XmlDocument();
////doc.Load("result.xml"); _FileSetSummary
// ---
////doc.CreateNavigator();
var xpathNavigator = this.xmlSummaryDocument.CreateNavigator();
// Get All the test suite containing test-case.
if (xpathNavigator != null)
{
var expr = xpathNavigator.Compile("//test-suite[(child::results/test-case)]");
var iterator = xpathNavigator.Select(expr);
string directory;
while (iterator.MoveNext())
{
var xpathNavigator2 = iterator.Current;
var testSuiteName = iterator.Current.GetAttribute("name", string.Empty);
// Get get the path for the current test-suite.
var iterator2 = xpathNavigator2.SelectAncestors(string.Empty, string.Empty, true);
path = string.Empty;
var parent = string.Empty;
var parentIndex = -1;
while (iterator2.MoveNext())
{
directory = iterator2.Current.GetAttribute("name", string.Empty);
if (directory != string.Empty && directory.IndexOf(".dll") < 0)
{
path = directory + "/" + path;
}
if (parentIndex == 1)
{
parent = directory;
}
parentIndex++;
}
// path = xx/yy/zz
Directory.CreateDirectory(Path.Combine(this.OutputDirectory, path));
// Build the "testSuiteName".html file
// Correct MockError duplicate testName !
// test-suite[@name='MockTestFixture' and ancestor::test-suite[@name='Assemblies'][position()=last()]]
stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" +
"<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" +
"<xsl:include href=\"" + this.xslFrameDefintionFilePath + "\"/>" +
"<xsl:template match=\"/\">" +
" <xsl:for-each select=\"//test-suite[@name='" + testSuiteName + "' and ancestor::test-suite[@name='" + parent + "'][position()=last()]]\">" +
" <xsl:call-template name=\"test-case\">" +
" <xsl:with-param name=\"dir.test\">" + string.Join(".", path.Split('/')) + "</xsl:with-param>" +
" </xsl:call-template>" +
" </xsl:for-each>" +
" </xsl:template>" +
" </xsl:stylesheet>");
this.Write(stream, Path.Combine(Path.Combine(this.OutputDirectory, path), testSuiteName + ".html"));
}
}
}
/// <summary>
/// Configures the optional settings.
/// </summary>
private void ConfigureOptionslSettings()
{
this.OutputFilename = string.IsNullOrWhiteSpace(this.OutputFilename) ? DefaultOutputFileName : this.OutputFilename;
this.OutputDirectory = string.IsNullOrWhiteSpace(this.OutputDirectory) ? DefaultOutputDirectoryName : this.OutputDirectory;
switch (this.Format)
{
case ReportFormat.NoFrames:
this.xslNoFrameDefinitionFilePath = Path.Combine(this.toolPath, "xsl\\" + XslNoFrameDefinitionFileName);
break;
case ReportFormat.Frames:
this.xslFrameDefintionFilePath = Path.Combine(this.toolPath, "xsl\\" + XslFrameDefinitionFileName);
break;
}
}
/// <summary>
/// Creates the output directory.
/// </summary>
private void CreateOutputDirectory()
{
if (!Directory.Exists(this.OutputDirectory))
{
Directory.CreateDirectory(this.OutputDirectory);
}
}
/// <summary>
/// Initializes the XmlDocument instance
/// used to summarize the test results
/// </summary>
/// <returns>
/// The Xml representing the Sumamry to be used in all transformations
/// </returns>
private XmlDocument CreateSummaryXmlDoc()
{
var doc = new XmlDocument();
var root = doc.CreateElement("testsummary");
root.SetAttribute("created", DateTime.Now.ToString());
doc.AppendChild(root);
foreach (var file in this.XmlNUnitResultFiles)
{
var source = new XmlDocument();
source.Load(file);
if (source.DocumentElement == null)
{
continue;
}
var node = doc.ImportNode(source.DocumentElement, true);
if (doc.DocumentElement != null)
{
doc.DocumentElement.AppendChild(node);
}
}
return doc;
}
/// <summary>
/// Builds an XsltArgumentList with all
/// the properties defined in the
/// current project as XSLT parameters.
/// </summary>
/// <returns>
/// The <c>XsltArgumentList</c> containing the common Xslt arguments
/// </returns>
private XsltArgumentList GetCommonXsltProperties()
{
var args = new XsltArgumentList();
args.AddParam("sys.os", string.Empty, Environment.OSVersion.ToString());
args.AddParam("sys.clr.version", string.Empty, Environment.Version.ToString());
args.AddParam("sys.machine.name", string.Empty, Environment.MachineName);
args.AddParam("sys.username", string.Empty, Environment.UserName);
// Add argument to the C# XML comment file
args.AddParam("summary.xml", string.Empty, string.Empty);
// Add open.description argument
args.AddParam("open.description", string.Empty, this.OpenDescription ? "yes" : "no");
return args;
}
/// <summary>
/// Creates the no frames report.
/// </summary>
private void CreateNoFramesReport()
{
var xslTransform = new XslCompiledTransform();
xslTransform.Load(this.xslNoFrameDefinitionFilePath, new XsltSettings(true, true), new XmlUrlResolver());
// tmpFirstTransformPath hold the first transformation
var tmpFirstTransformPath = Path.GetTempFileName();
var firstTransformationStream = new XmlTextWriter(tmpFirstTransformPath, System.Text.ASCIIEncoding.UTF8);
xslTransform.Transform(new XmlNodeReader(this.xmlSummaryDocument), this.commonXsltArguments, firstTransformationStream);
firstTransformationStream.Flush();
firstTransformationStream.Close();
// ---------- i18n --------------------------
var xsltI18NArgs = new XsltArgumentList();
xsltI18NArgs.AddParam("lang", string.Empty, this.Language.GetLanguageString());
var xslt = new XslCompiledTransform();
xslt.Load(this.xslGlobalizationDefinitionFilePath, new XsltSettings(true, true), new XmlUrlResolver());
var xmlDoc = new XPathDocument(tmpFirstTransformPath);
var writerFinal = new XmlTextWriter(Path.Combine(this.OutputDirectory, this.OutputFilename), System.Text.Encoding.GetEncoding("ISO-8859-1"));
// Apply the second transform to xmlReader to final ouput
xslt.Transform(xmlDoc, xsltI18NArgs, writerFinal);
writerFinal.Close();
}
/// <summary>
/// Writes the specified stream containing the Xslt fragment of code.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="fileName">Name of the file.</param>
private void Write(TextReader stream, string fileName)
{
// Load the XmlTextReader from the stream
var reader = new XmlTextReader(stream);
var xslTransform = new XslCompiledTransform();
// Load the stylesheet from the stream.
xslTransform.Load(reader, new XsltSettings(true, true), new XmlUrlResolver());
// xmlDoc = new XPathDocument("result.xml");
// tmpFirstTransformPath hold the first transformation
var tmpFirstTransformPath = Path.GetTempFileName();
var firstTransformationStream = new XmlTextWriter(tmpFirstTransformPath, System.Text.ASCIIEncoding.UTF8);
xslTransform.Transform(new XmlNodeReader(this.xmlSummaryDocument), this.commonXsltArguments, firstTransformationStream);
firstTransformationStream.Flush();
firstTransformationStream.Close();
if (fileName.EndsWith(".css"))
{
File.Copy(tmpFirstTransformPath, fileName, true);
return;
}
// ---------- i18n --------------------------
var xsltI18NArgs = new XsltArgumentList();
xsltI18NArgs.AddParam("lang", string.Empty, this.Language.GetLanguageString());
var xslt = new XslCompiledTransform();
// Load the stylesheet.
xslt.Load(this.xslGlobalizationDefinitionFilePath, new XsltSettings(true, true), new XmlUrlResolver());
var xmlDoc = new XPathDocument(tmpFirstTransformPath);
var writerFinal = new XmlTextWriter(fileName, System.Text.Encoding.GetEncoding("ISO-8859-1"));
// Apply the second transform to xmlReader to final ouput
xslt.Transform(xmlDoc, xsltI18NArgs, writerFinal);
writerFinal.Close();
}
} // class NUnit2ReportTask
} // namespace NAnt.NUnit2ReportTasks
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Globalization;
namespace System.Net
{
internal class StreamFramer
{
private Stream _transport;
private bool _eof;
private FrameHeader _writeHeader = new FrameHeader();
private FrameHeader _curReadHeader = new FrameHeader();
private FrameHeader _readVerifier = new FrameHeader(
FrameHeader.IgnoreValue,
FrameHeader.IgnoreValue,
FrameHeader.IgnoreValue);
private byte[] _readHeaderBuffer;
private byte[] _writeHeaderBuffer;
private readonly AsyncCallback _readFrameCallback;
private readonly AsyncCallback _beginWriteCallback;
public StreamFramer(Stream Transport)
{
if (Transport == null || Transport == Stream.Null)
{
throw new ArgumentNullException(nameof(Transport));
}
_transport = Transport;
_readHeaderBuffer = new byte[_curReadHeader.Size];
_writeHeaderBuffer = new byte[_writeHeader.Size];
_readFrameCallback = new AsyncCallback(ReadFrameCallback);
_beginWriteCallback = new AsyncCallback(BeginWriteCallback);
}
public FrameHeader ReadHeader
{
get
{
return _curReadHeader;
}
}
public FrameHeader WriteHeader
{
get
{
return _writeHeader;
}
}
public Stream Transport
{
get
{
return _transport;
}
}
public byte[] ReadMessage()
{
if (_eof)
{
return null;
}
int offset = 0;
byte[] buffer = _readHeaderBuffer;
int bytesRead;
while (offset < buffer.Length)
{
bytesRead = Transport.Read(buffer, offset, buffer.Length - offset);
if (bytesRead == 0)
{
if (offset == 0)
{
// m_Eof, return null
_eof = true;
return null;
}
else
{
throw new IOException(SR.Format(SR.net_io_readfailure, SR.Format(SR.net_io_connectionclosed)));
}
}
offset += bytesRead;
}
_curReadHeader.CopyFrom(buffer, 0, _readVerifier);
if (_curReadHeader.PayloadSize > _curReadHeader.MaxMessageSize)
{
throw new InvalidOperationException(SR.Format(SR.net_frame_size,
_curReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo),
_curReadHeader.PayloadSize.ToString(NumberFormatInfo.InvariantInfo)));
}
buffer = new byte[_curReadHeader.PayloadSize];
offset = 0;
while (offset < buffer.Length)
{
bytesRead = Transport.Read(buffer, offset, buffer.Length - offset);
if (bytesRead == 0)
{
throw new IOException(SR.Format(SR.net_io_readfailure, SR.Format(SR.net_io_connectionclosed)));
}
offset += bytesRead;
}
return buffer;
}
public IAsyncResult BeginReadMessage(AsyncCallback asyncCallback, object stateObject)
{
WorkerAsyncResult workerResult;
if (_eof)
{
workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, null, 0, 0);
workerResult.InvokeCallback(-1);
return workerResult;
}
workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback,
_readHeaderBuffer, 0,
_readHeaderBuffer.Length);
IAsyncResult result = _transport.BeginRead(_readHeaderBuffer, 0, _readHeaderBuffer.Length,
_readFrameCallback, workerResult);
if (result.CompletedSynchronously)
{
ReadFrameComplete(result);
}
return workerResult;
}
private void ReadFrameCallback(IAsyncResult transportResult)
{
if (!(transportResult.AsyncState is WorkerAsyncResult))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
}
Debug.Fail("StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:" + transportResult.GetType().FullName + ".");
}
if (transportResult.CompletedSynchronously)
{
return;
}
WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;
try
{
ReadFrameComplete(transportResult);
}
catch (Exception e)
{
if (e is OutOfMemoryException)
{
throw;
}
if (!(e is IOException))
{
e = new System.IO.IOException(SR.Format(SR.net_io_readfailure, e.Message), e);
}
workerResult.InvokeCallback(e);
}
}
// IO COMPLETION CALLBACK
//
// This callback is responsible for getting the complete protocol frame.
// 1. it reads the header.
// 2. it determines the frame size.
// 3. loops while not all frame received or an error.
//
private void ReadFrameComplete(IAsyncResult transportResult)
{
do
{
if (!(transportResult.AsyncState is WorkerAsyncResult))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
}
Debug.Fail("StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:" + transportResult.GetType().FullName + ".");
}
WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;
int bytesRead = _transport.EndRead(transportResult);
workerResult.Offset += bytesRead;
if (!(workerResult.Offset <= workerResult.End))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("StreamFramer::ReadFrameCallback|WRONG: offset - end = {0}", workerResult.Offset - workerResult.End);
}
Debug.Fail("StreamFramer::ReadFrameCallback|WRONG: offset - end = " + (workerResult.Offset - workerResult.End));
}
if (bytesRead <= 0)
{
// (by design) This indicates the stream has receives EOF
// If we are in the middle of a Frame - fail, otherwise - produce EOF
object result = null;
if (!workerResult.HeaderDone && workerResult.Offset == 0)
{
result = (object)-1;
}
else
{
result = new System.IO.IOException(SR.net_frame_read_io);
}
workerResult.InvokeCallback(result);
return;
}
if (workerResult.Offset >= workerResult.End)
{
if (!workerResult.HeaderDone)
{
workerResult.HeaderDone = true;
// This indicates the header has been read successfully
_curReadHeader.CopyFrom(workerResult.Buffer, 0, _readVerifier);
int payloadSize = _curReadHeader.PayloadSize;
if (payloadSize < 0)
{
// Let's call user callback and he call us back and we will throw
workerResult.InvokeCallback(new System.IO.IOException(SR.Format(SR.net_frame_read_size)));
}
if (payloadSize == 0)
{
// report empty frame (NOT eof!) to the caller, he might be interested in
workerResult.InvokeCallback(0);
return;
}
if (payloadSize > _curReadHeader.MaxMessageSize)
{
throw new InvalidOperationException(SR.Format(SR.net_frame_size,
_curReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo),
payloadSize.ToString(NumberFormatInfo.InvariantInfo)));
}
// Start reading the remaining frame data (note header does not count).
byte[] frame = new byte[payloadSize];
// Save the ref of the data block
workerResult.Buffer = frame;
workerResult.End = frame.Length;
workerResult.Offset = 0;
// Transport.BeginRead below will pickup those changes.
}
else
{
workerResult.HeaderDone = false; // Reset for optional object reuse.
workerResult.InvokeCallback(workerResult.End);
return;
}
}
// This means we need more data to complete the data block.
transportResult = _transport.BeginRead(workerResult.Buffer, workerResult.Offset, workerResult.End - workerResult.Offset,
_readFrameCallback, workerResult);
} while (transportResult.CompletedSynchronously);
}
//
// User code will call this when workerResult gets signaled.
//
// On BeginRead, the user always gets back our WorkerAsyncResult.
// The Result property represents either a number of bytes read or an
// exception put by our async state machine.
//
public byte[] EndReadMessage(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult;
if (workerResult == null)
{
throw new ArgumentException(SR.Format(SR.net_io_async_result, typeof(WorkerAsyncResult).FullName), nameof(asyncResult));
}
if (!workerResult.InternalPeekCompleted)
{
workerResult.InternalWaitForCompletion();
}
if (workerResult.Result is Exception)
{
throw (Exception)(workerResult.Result);
}
int size = (int)workerResult.Result;
if (size == -1)
{
_eof = true;
return null;
}
else if (size == 0)
{
// Empty frame.
return Array.Empty<byte>();
}
return workerResult.Buffer;
}
public void WriteMessage(byte[] message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
_writeHeader.PayloadSize = message.Length;
_writeHeader.CopyTo(_writeHeaderBuffer, 0);
Transport.Write(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length);
if (message.Length == 0)
{
return;
}
Transport.Write(message, 0, message.Length);
}
public IAsyncResult BeginWriteMessage(byte[] message, AsyncCallback asyncCallback, object stateObject)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
_writeHeader.PayloadSize = message.Length;
_writeHeader.CopyTo(_writeHeaderBuffer, 0);
if (message.Length == 0)
{
return _transport.BeginWrite(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length,
asyncCallback, stateObject);
}
// Will need two async writes. Prepare the second:
WorkerAsyncResult workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback,
message, 0, message.Length);
// Charge the first:
IAsyncResult result = _transport.BeginWrite(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length,
_beginWriteCallback, workerResult);
if (result.CompletedSynchronously)
{
BeginWriteComplete(result);
}
return workerResult;
}
private void BeginWriteCallback(IAsyncResult transportResult)
{
if (!(transportResult.AsyncState is WorkerAsyncResult))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("StreamFramer::BeginWriteCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.AsyncState.GetType().FullName);
}
Debug.Fail("StreamFramer::BeginWriteCallback|The state expected to be WorkerAsyncResult, received:" + transportResult.AsyncState.GetType().FullName + ".");
}
if (transportResult.CompletedSynchronously)
{
return;
}
var workerResult = (WorkerAsyncResult)transportResult.AsyncState;
try
{
BeginWriteComplete(transportResult);
}
catch (Exception e)
{
if (e is OutOfMemoryException)
{
throw;
}
workerResult.InvokeCallback(e);
}
}
// IO COMPLETION CALLBACK
//
// Called when user IO request was wrapped to do several underlined IO.
//
private void BeginWriteComplete(IAsyncResult transportResult)
{
do
{
WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;
// First, complete the previous portion write.
_transport.EndWrite(transportResult);
// Check on exit criterion.
if (workerResult.Offset == workerResult.End)
{
workerResult.InvokeCallback();
return;
}
// Setup exit criterion.
workerResult.Offset = workerResult.End;
// Write next portion (frame body) using Async IO.
transportResult = _transport.BeginWrite(workerResult.Buffer, 0, workerResult.End,
_beginWriteCallback, workerResult);
}
while (transportResult.CompletedSynchronously);
}
public void EndWriteMessage(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult;
if (workerResult != null)
{
if (!workerResult.InternalPeekCompleted)
{
workerResult.InternalWaitForCompletion();
}
if (workerResult.Result is Exception)
{
throw (Exception)(workerResult.Result);
}
}
else
{
_transport.EndWrite(asyncResult);
}
}
}
//
// This class wraps an Async IO request. It is based on our internal LazyAsyncResult helper.
// - If ParentResult is not null then the base class (LazyAsyncResult) methods must not be used.
// - If ParentResult == null, then real user IO request is wrapped.
//
internal class WorkerAsyncResult : LazyAsyncResult
{
public byte[] Buffer;
public int Offset;
public int End;
public bool HeaderDone; // This might be reworked so we read both header and frame in one chunk.
public WorkerAsyncResult(object asyncObject, object asyncState,
AsyncCallback savedAsyncCallback,
byte[] buffer, int offset, int end)
: base(asyncObject, asyncState, savedAsyncCallback)
{
Buffer = buffer;
Offset = offset;
End = end;
}
}
// Describes the header used in framing of the stream data.
internal class FrameHeader
{
public const int IgnoreValue = -1;
public const int HandshakeDoneId = 20;
public const int HandshakeErrId = 21;
public const int HandshakeId = 22;
public const int DefaultMajorV = 1;
public const int DefaultMinorV = 0;
private int _MessageId;
private int _MajorV;
private int _MinorV;
private int _PayloadSize;
public FrameHeader()
{
_MessageId = HandshakeId;
_MajorV = DefaultMajorV;
_MinorV = DefaultMinorV;
_PayloadSize = -1;
}
public FrameHeader(int messageId, int majorV, int minorV)
{
_MessageId = messageId;
_MajorV = majorV;
_MinorV = minorV;
_PayloadSize = -1;
}
public int Size
{
get
{
return 5;
}
}
public int MaxMessageSize
{
get
{
return 0xFFFF;
}
}
public int MessageId
{
get
{
return _MessageId;
}
set
{
_MessageId = value;
}
}
public int MajorV
{
get
{
return _MajorV;
}
}
public int MinorV
{
get
{
return _MinorV;
}
}
public int PayloadSize
{
get
{
return _PayloadSize;
}
set
{
if (value > MaxMessageSize)
{
throw new ArgumentException(SR.Format(SR.net_frame_max_size,
MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo),
value.ToString(NumberFormatInfo.InvariantInfo)), "PayloadSize");
}
_PayloadSize = value;
}
}
public void CopyTo(byte[] dest, int start)
{
dest[start++] = (byte)_MessageId;
dest[start++] = (byte)_MajorV;
dest[start++] = (byte)_MinorV;
dest[start++] = (byte)((_PayloadSize >> 8) & 0xFF);
dest[start] = (byte)(_PayloadSize & 0xFF);
}
public void CopyFrom(byte[] bytes, int start, FrameHeader verifier)
{
_MessageId = bytes[start++];
_MajorV = bytes[start++];
_MinorV = bytes[start++];
_PayloadSize = (int)((bytes[start++] << 8) | bytes[start]);
if (verifier.MessageId != FrameHeader.IgnoreValue && MessageId != verifier.MessageId)
{
throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MessageId", MessageId, verifier.MessageId));
}
if (verifier.MajorV != FrameHeader.IgnoreValue && MajorV != verifier.MajorV)
{
throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MajorV", MajorV, verifier.MajorV));
}
if (verifier.MinorV != FrameHeader.IgnoreValue && MinorV != verifier.MinorV)
{
throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MinorV", MinorV, verifier.MinorV));
}
}
}
}
| |
using System;
using System.Text;
using ServiceStack.Common;
using ServiceStack.Logging;
using ServiceStack.Service;
using ServiceStack.ServiceClient.Web;
using ServiceStack.Text;
using StringExtensions = ServiceStack.Common.StringExtensions;
namespace ServiceStack.Messaging
{
/// <summary>
/// Processes all messages in a Normal and Priority Queue.
/// Expects to be called in 1 thread. i.e. Non Thread-Safe.
/// </summary>
/// <typeparam name="T"></typeparam>
public class MessageHandler<T>
: IMessageHandler, IDisposable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(MessageHandler<T>));
public const int DefaultRetryCount = 2; //Will be a total of 3 attempts
private readonly IMessageService messageService;
private readonly Func<IMessage<T>, object> processMessageFn;
private readonly Action<IMessage<T>, Exception> processInExceptionFn;
public Func<string, IOneWayClient> ReplyClientFactory { get; set; }
private readonly int retryCount;
public int TotalMessagesProcessed { get; private set; }
public int TotalMessagesFailed { get; private set; }
public int TotalRetries { get; private set; }
public int TotalNormalMessagesReceived { get; private set; }
public int TotalPriorityMessagesReceived { get; private set; }
public int TotalOutMessagesReceived { get; private set; }
public DateTime? LastMessageProcessed { get; private set; }
public string[] ProcessQueueNames { get; set; }
public MessageHandler(IMessageService messageService,
Func<IMessage<T>, object> processMessageFn)
: this(messageService, processMessageFn, null, DefaultRetryCount) {}
private IMessageQueueClient MqClient { get; set; }
public MessageHandler(IMessageService messageService,
Func<IMessage<T>, object> processMessageFn,
Action<IMessage<T>, Exception> processInExceptionFn,
int retryCount)
{
if (messageService == null)
throw new ArgumentNullException("messageService");
if (processMessageFn == null)
throw new ArgumentNullException("processMessageFn");
this.messageService = messageService;
this.processMessageFn = processMessageFn;
this.processInExceptionFn = processInExceptionFn ?? DefaultInExceptionHandler;
this.retryCount = retryCount;
this.ReplyClientFactory = ClientFactory.Create;
this.ProcessQueueNames = new[] { QueueNames<T>.Priority, QueueNames<T>.In };
}
public Type MessageType
{
get { return typeof(T); }
}
public void Process(IMessageQueueClient mqClient)
{
foreach (var processQueueName in ProcessQueueNames)
{
ProcessQueue(mqClient, processQueueName);
}
}
public int ProcessQueue(IMessageQueueClient mqClient, string queueName, Func<bool> doNext = null)
{
var msgsProcessed = 0;
try
{
byte[] messageBytes;
while ((messageBytes = mqClient.GetAsync(queueName)) != null)
{
var message = messageBytes.ToMessage<T>();
ProcessMessage(mqClient, message);
this.TotalNormalMessagesReceived++;
msgsProcessed++;
LastMessageProcessed = DateTime.UtcNow;
if (doNext != null && !doNext()) return msgsProcessed;
}
}
catch (Exception ex)
{
var lastEx = ex;
Log.Error("Error serializing message from mq server: " + lastEx.Message, ex);
}
return msgsProcessed;
}
public IMessageHandlerStats GetStats()
{
return new MessageHandlerStats(typeof(T).Name,
TotalMessagesProcessed, TotalMessagesFailed, TotalRetries,
TotalNormalMessagesReceived, TotalPriorityMessagesReceived, LastMessageProcessed);
}
private void DefaultInExceptionHandler(IMessage<T> message, Exception ex)
{
Log.Error("Message exception handler threw an error", ex);
if (!(ex is UnRetryableMessagingException))
{
if (message.RetryAttempts < retryCount)
{
message.RetryAttempts++;
this.TotalRetries++;
message.Error = new MessagingException(ex.Message, ex).ToMessageError();
MqClient.Publish(QueueNames<T>.In, message.ToBytes());
return;
}
}
MqClient.Publish(QueueNames<T>.Dlq, message.ToBytes());
}
public void ProcessMessage(IMessageQueueClient mqClient, Message<T> message)
{
this.MqClient = mqClient;
try
{
var response = processMessageFn(message);
var responseEx = response as Exception;
if (responseEx != null)
throw responseEx;
this.TotalMessagesProcessed++;
//If there's no response publish the request message to its OutQ
if (response == null)
{
var messageOptions = (MessageOption)message.Options;
if (messageOptions.Has(MessageOption.NotifyOneWay))
{
mqClient.Notify(QueueNames<T>.Out, message.ToBytes());
}
}
else
{
//If there is a response send it to the typed response OutQ
var mqReplyTo = message.ReplyTo;
if (mqReplyTo == null)
{
var responseType = response.GetType();
// Leave as-is to work around a Mono 2.6.7 compiler bug
if (!StringExtensions.IsUserType(responseType)) return;
mqReplyTo = new QueueNames(responseType).In;
}
var replyClient = ReplyClientFactory(mqReplyTo);
if (replyClient != null)
{
try
{
replyClient.SendOneWay(mqReplyTo, response);
return;
}
catch (Exception ex)
{
Log.Error("Could not send response to '{0}' with client '{1}'"
.Fmt(mqReplyTo, replyClient.GetType().Name), ex);
var responseType = response.GetType();
// Leave as-is to work around a Mono 2.6.7 compiler bug
if (!StringExtensions.IsUserType(responseType)) return;
mqReplyTo = new QueueNames(responseType).In;
}
}
//Otherwise send to our trusty response Queue (inc if replyClient fails)
var responseMessage = MessageFactory.Create(response);
responseMessage.ReplyId = message.Id;
mqClient.Publish(mqReplyTo, responseMessage.ToBytes());
}
}
catch (Exception ex)
{
try
{
TotalMessagesFailed++;
processInExceptionFn(message, ex);
}
catch (Exception exHandlerEx)
{
Log.Error("Message exception handler threw an error", exHandlerEx);
}
}
}
public void Dispose()
{
var shouldDispose = messageService as IMessageHandlerDisposer;
if (shouldDispose != null)
shouldDispose.DisposeMessageHandler(this);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Xml.Tests
{
public class DocumentElement_InsertBeforeTests
{
[Fact]
public static void NodeWithOneChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a><b/></a>");
var firstChild = xmlDocument.DocumentElement.FirstChild;
var newNode = xmlDocument.CreateElement("newElem");
var returned = xmlDocument.DocumentElement.InsertBefore(newNode, firstChild);
Assert.Same(newNode, returned);
Assert.Same(xmlDocument.DocumentElement.ChildNodes[0], newNode);
Assert.Same(xmlDocument.DocumentElement.ChildNodes[1], firstChild);
}
[Fact]
public static void NodeWithNoChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a></a>");
var root = xmlDocument.DocumentElement;
Assert.False(root.HasChildNodes);
var newNode = xmlDocument.CreateElement("elem");
var result = root.InsertBefore(newNode, null);
Assert.Same(newNode, result);
Assert.Equal(1, root.ChildNodes.Count);
Assert.Same(result, root.ChildNodes[0]);
}
[Fact]
public static void RemoveAndInsert()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a><b/></a>");
var root = xmlDocument.DocumentElement;
root.RemoveChild(root.FirstChild);
Assert.False(root.HasChildNodes);
var newNode = xmlDocument.CreateElement("elem");
var result = root.InsertBefore(newNode, null);
Assert.Same(newNode, result);
Assert.Equal(1, root.ChildNodes.Count);
Assert.Same(result, root.ChildNodes[0]);
}
[Fact]
public static void InsertNewNodeToElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a><b/></a>");
var root = xmlDocument.DocumentElement;
var newNode = xmlDocument.CreateProcessingInstruction("PI", "pi data");
root.InsertBefore(newNode, root.FirstChild);
Assert.Equal(2, root.ChildNodes.Count);
}
[Fact]
public static void InsertCDataNodeToDocumentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a/>");
var cDataSection = xmlDocument.CreateCDataSection("data");
Assert.Throws<InvalidOperationException>(() => xmlDocument.InsertBefore(cDataSection, null));
}
[Fact]
public static void InsertCDataNodeToDocumentFragment()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a/>");
var docFragment = xmlDocument.CreateDocumentFragment();
var cDataSection = xmlDocument.CreateCDataSection("data");
Assert.Equal(0, docFragment.ChildNodes.Count);
docFragment.InsertBefore(cDataSection, null);
Assert.Equal(1, docFragment.ChildNodes.Count);
}
[Fact]
public static void InsertCDataNodeToAnAttributeNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a attr='test' />");
var attribute = xmlDocument.DocumentElement.Attributes[0];
var cDataSection = xmlDocument.CreateCDataSection("data");
Assert.Equal(1, attribute.ChildNodes.Count);
Assert.Throws<InvalidOperationException>(() => attribute.InsertBefore(cDataSection, null));
Assert.Equal(1, attribute.ChildNodes.Count);
}
[Fact]
public static void InsertCDataToElementNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a><b/></a>");
var node = xmlDocument.DocumentElement.FirstChild;
var cDataSection = xmlDocument.CreateCDataSection("data");
Assert.Equal(0, node.ChildNodes.Count);
Assert.Same(cDataSection, node.InsertBefore(cDataSection, null));
Assert.Equal(1, node.ChildNodes.Count);
}
[Fact]
public static void InsertChildNodeToItself()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a><b/></a>");
var node = xmlDocument.DocumentElement.FirstChild;
var outerXmlBefore = xmlDocument.OuterXml;
var result = xmlDocument.DocumentElement.InsertBefore(node, node);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Same(node, result);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(outerXmlBefore, xmlDocument.OuterXml);
}
[Fact]
public static void InsertCommentNodeToDocumentFragment()
{
var xmlDocument = new XmlDocument();
var documentFragment = xmlDocument.CreateDocumentFragment();
var node = xmlDocument.CreateComment("some comment");
Assert.Equal(0, documentFragment.ChildNodes.Count);
var result = documentFragment.InsertBefore(node, null);
Assert.Same(node, result);
Assert.Equal(1, documentFragment.ChildNodes.Count);
}
[Fact]
public static void InsertCommentNodeToDocument()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/>");
var node = xmlDocument.CreateComment("some comment");
Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count);
var result = xmlDocument.DocumentElement.InsertBefore(node, null);
Assert.Same(node, result);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
}
[Fact]
public static void InsertDocFragmentToDocFragment()
{
var xmlDocument = new XmlDocument();
var root = xmlDocument.CreateElement("root");
var docFrag1 = xmlDocument.CreateDocumentFragment();
var docFrag2 = xmlDocument.CreateDocumentFragment();
docFrag1.AppendChild(root);
docFrag2.InsertBefore(docFrag1, null);
Assert.Equal(1, docFrag2.ChildNodes.Count);
}
[Fact]
public static void InsertTextNodeToCommentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><!-- comment here--></root>");
var commentNode = xmlDocument.DocumentElement.FirstChild;
var textNode = xmlDocument.CreateTextNode("text node");
Assert.Equal(XmlNodeType.Comment, commentNode.NodeType);
Assert.Throws<InvalidOperationException>(() => commentNode.InsertBefore(textNode, null));
}
[Fact]
public static void InsertTextNodeToProcessingInstructionNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><?PI pi instructions ?></root>");
var processingNode = xmlDocument.DocumentElement.FirstChild;
var textNode = xmlDocument.CreateTextNode("text node");
Assert.Equal(XmlNodeType.ProcessingInstruction, processingNode.NodeType);
Assert.Throws<InvalidOperationException>(() => processingNode.InsertBefore(textNode, null));
}
[Fact]
public static void InsertTextNodeToTextNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>text node</root>");
var textNode = xmlDocument.DocumentElement.FirstChild;
var newTextNode = xmlDocument.CreateTextNode("text node");
Assert.Equal(XmlNodeType.Text, textNode.NodeType);
Assert.Throws<InvalidOperationException>(() => textNode.InsertBefore(newTextNode, null));
}
[Fact]
public static void InsertTextNodeToElementNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><elem/></root>");
var node = xmlDocument.DocumentElement.FirstChild;
var newTextNode = xmlDocument.CreateTextNode("text node");
Assert.Equal(XmlNodeType.Element, node.NodeType);
var result = node.InsertBefore(newTextNode, null);
Assert.Equal(1, node.ChildNodes.Count);
Assert.Equal(result, node.ChildNodes[0]);
}
[Fact]
public static void InsertTextNodeToDocumentFragment()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/>");
var node = xmlDocument.CreateTextNode("some comment");
var result = xmlDocument.DocumentElement.InsertBefore(node, null);
Assert.Same(node, result);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
}
[Fact]
public static void InsertAttributeNodeToDocumentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/>");
var attribute = xmlDocument.CreateAttribute("attr");
Assert.Throws<InvalidOperationException>(() => xmlDocument.InsertBefore(attribute, null));
}
[Fact]
public static void InsertAttributeNodeToAttributeNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr='value'/>");
var attribute = xmlDocument.CreateAttribute("attr");
Assert.Throws<InvalidOperationException>(() => xmlDocument.InsertBefore(attribute, 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 Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass001.regclass001;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass
{
public string Property_string
{
set;
get;
}
public MyClass Property_MyClass
{
get;
set;
}
public MyStruct Property_MyStruct
{
set;
get;
}
public MyEnum Property_MyEnum
{
set;
private get;
}
public short Property_short
{
set;
protected get;
}
public ulong Property_ulong
{
set;
protected internal get;
}
public char Property_char
{
private set;
get;
}
public bool Property_bool
{
protected set;
get;
}
public decimal Property_decimal
{
protected internal set;
get;
}
public MyStruct? Property_MyStructNull
{
set;
get;
}
public MyEnum? Property_MyEnumNull
{
set;
private get;
}
public short? Property_shortNull
{
set;
get;
}
public ulong? Property_ulongNull
{
set;
protected internal get;
}
public char? Property_charNull
{
private set;
get;
}
public bool? Property_boolNull
{
protected set;
get;
}
public decimal? Property_decimalNull
{
protected internal set;
get;
}
public string[] Property_stringArr
{
set;
get;
}
public MyClass[] Property_MyClassArr
{
set;
get;
}
public MyStruct[] Property_MyStructArr
{
get;
set;
}
public MyEnum[] Property_MyEnumArr
{
set;
private get;
}
public short[] Property_shortArr
{
set;
protected get;
}
public ulong[] Property_ulongArr
{
set;
protected internal get;
}
public char[] Property_charArr
{
private set;
get;
}
public bool[] Property_boolArr
{
protected set;
get;
}
public decimal[] Property_decimalArr
{
protected internal set;
get;
}
public MyStruct?[] Property_MyStructNullArr
{
set;
get;
}
public MyEnum?[] Property_MyEnumNullArr
{
set;
private get;
}
public short?[] Property_shortNullArr
{
set;
protected get;
}
public ulong?[] Property_ulongNullArr
{
set;
protected internal get;
}
public char?[] Property_charNullArr
{
private set;
get;
}
public bool?[] Property_boolNullArr
{
protected set;
get;
}
public decimal?[] Property_decimalNullArr
{
protected internal set;
get;
}
public float Property_Float
{
get;
set;
}
public float?[] Property_FloatNullArr
{
get;
set;
}
public dynamic Property_Dynamic
{
get;
set;
}
public static string Property_stringStatic
{
set;
get;
}
// Move declarations to the call site
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass001.regclass001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass001.regclass001;
// <Title> Tests regular class auto property used in generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t1 = new Test();
return t1.TestGetMethod<long>(1, new MemberClass()) + t1.TestSetMethod<Test, string>(string.Empty, new MemberClass()) == 0 ? 0 : 1;
}
public int TestGetMethod<T>(T t, MemberClass mc)
{
mc.Property_string = "Test";
dynamic dy = mc;
if ((string)dy.Property_string != "Test")
return 1;
else
return 0;
}
public int TestSetMethod<U, V>(V v, MemberClass mc)
{
dynamic dy = mc;
dy.Property_string = "Test";
mc = dy; //because we might change the property on a boxed version of it if MemberClass is a struct
if (mc.Property_string != "Test")
return 1;
else
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass003.regclass003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass003.regclass003;
// <Title> Tests regular class auto property used in variable initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
string[] bas = new string[]
{
"Test", string.Empty, null
}
;
MemberClass mc = new MemberClass();
mc.Property_stringArr = bas;
dynamic dy = mc;
string[] loc = dy.Property_stringArr;
if (ReferenceEquals(bas, loc) && loc[0] == "Test" && loc[1] == string.Empty && loc[2] == null)
{
return 0;
}
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass004.regclass004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass004.regclass004;
// <Title> Tests regular class auto property used in implicitly-typed array initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc1 = new MemberClass();
MemberClass mc2 = new MemberClass();
mc1.Property_MyStructNull = null;
mc2.Property_MyStructNull = new MyStruct()
{
Number = 1
}
;
dynamic dy1 = mc1;
dynamic dy2 = mc2;
var loc = new MyStruct?[]
{
(MyStruct? )dy1.Property_MyStructNull, (MyStruct? )dy2.Property_MyStructNull
}
;
if (loc.Length == 2 && loc[0] == null && loc[1].Value.Number == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass005.regclass005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass005.regclass005;
// <Title> Tests regular class auto property used in operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc1 = new MemberClass();
MemberClass mc2 = new MemberClass();
mc1.Property_string = "a";
mc2.Property_string = "b";
dynamic dy1 = mc1;
dynamic dy2 = mc2;
string s = (string)dy1.Property_string + (string)dy2.Property_string;
if (s == "ab")
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass006.regclass006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass006.regclass006;
// <Title> Tests regular class auto property used in null coalescing operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.Property_MyStructArr = new MyStruct[]
{
new MyStruct()
{
Number = 0
}
, new MyStruct()
{
Number = 1
}
}
;
dynamic dy = mc;
string s1 = ((string)dy.Property_string) ?? string.Empty;
mc.Property_string = "Test";
dy = mc;
MyStruct[] b1 = ((MyStruct[])dy.Property_MyStructArr) ?? (new MyStruct[1]);
MyStruct[] b2 = ((MyStruct[])dy.Property_MyStructArr) ?? (new MyStruct[1]);
string s2 = ((string)dy.Property_string) ?? string.Empty;
if (b1.Length == 2 && s1 == string.Empty && b2.Length == 2 && s2 == "Test")
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass007.regclass007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass007.regclass007;
// <Title> Tests regular class auto property used in destructor.</Title>
// <Description>
// On IA64 the GC.WaitForPendingFinalizers() does not actually work...
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Runtime.CompilerServices;
public class Test
{
private static string s_field;
public static object locker = new object();
~Test()
{
lock (locker)
{
MemberClass mc = new MemberClass();
mc.Property_string = "Test";
dynamic dy = mc;
s_field = dy.Property_string;
}
}
public void Foo()
{
}
private static int Verify()
{
lock (Test.locker)
{
if (Test.s_field != "Test")
{
return 1;
}
}
return 0;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void RequireLifetimesEnded()
{
Test t = new Test();
Test.s_field = "Field";
t.Foo();
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
RequireLifetimesEnded();
GC.Collect();
GC.WaitForPendingFinalizers();
// If move the code in Verify() to here, the finalizer will only be executed after exited Main
return Verify();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass008.regclass008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass008.regclass008;
// <Title> Tests regular class auto property used in extension method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int a1 = 10;
MyStruct ms1 = a1.TestSetMyStruct();
MyStruct ms2 = a1.TestGetMyStruct();
if (ms1.Number == 10 && ms2.Number == 10)
return 0;
return 1;
}
}
static public class Extension
{
public static MyStruct TestSetMyStruct(this int i)
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_MyStruct = new MyStruct()
{
Number = i
}
;
mc = dy; //because MC might be a struct
return mc.Property_MyStruct;
}
public static MyStruct TestGetMyStruct(this int i)
{
MemberClass mc = new MemberClass();
mc.Property_MyStruct = new MyStruct()
{
Number = i
}
;
dynamic dy = mc;
return (MyStruct)dy.Property_MyStruct;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass009.regclass009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass009.regclass009;
// <Title> Tests regular class auto property used in variable initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
char value = (char)dy.Property_char;
if (value == default(char))
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass010.regclass010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass010.regclass010;
// <Title> Tests regular class auto property used in array initializer list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
bool[] array = new bool[]
{
(bool)dy.Property_bool, true
}
;
if (array.Length == 2 && array[0] == false && array[1] == true)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass014.regclass014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass014.regclass014;
// <Title> Tests regular class auto property used in for loop body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic mc = new MemberClass();
ulong[] array = new ulong[]
{
1L, 2L, 3L, ulong.MinValue, ulong.MaxValue
}
;
for (int i = 0; i < array.Length; i++)
{
mc.Property_ulong = array[i];
}
ulong x = (ulong)mc.Property_ulong;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass015.regclass015
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass015.regclass015;
// <Title> Tests regular class auto property used in foreach expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.Property_MyClassArr = new MyClass[]
{
null, new MyClass()
{
Field = -1
}
}
;
dynamic dy = mc;
List<MyClass> list = new List<MyClass>();
foreach (MyClass myclass in dy.Property_MyClassArr)
{
list.Add(myclass);
}
if (list.Count == 2 && list[0] == null && list[1].Field == -1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass016.regclass016
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass016.regclass016;
// <Title> Tests regular class auto property used in while body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test : MemberClass
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test mc = new Test();
dynamic dy = mc;
short a = 0;
short v = 0;
while (a < 10)
{
v = a;
dy.Property_shortNull = a;
a = (short)((short)dy.Property_shortNull + 1);
if (a != v + 1)
return 1;
}
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass018.regclass018
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass018.regclass018;
// <Title> Tests regular class auto property used in uncheck expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
ulong result = 1;
dy.Property_ulongNull = ulong.MaxValue;
result = unchecked(dy.Property_ulongNull + 1); //0
return (int)result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass019.regclass019
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass019.regclass019;
// <Title> Tests regular class auto property used in static constructor.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static char? s_charValue = 'a';
static Test()
{
dynamic dy = new MemberClass();
s_charValue = dy.Property_charNull;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (Test.s_charValue == null)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass020.regclass020
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass020.regclass020;
// <Title> Tests regular class auto property used in variable named dynamic.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dynamic = new MemberClass();
if (dynamic.Property_boolNull == null)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass022.regclass022
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass022.regclass022;
// <Title> Tests regular class auto property used in field initailizer outside of constructor.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static dynamic s_dy = new MemberClass();
private char[] _result = s_dy.Property_charArr;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
if (t._result == null)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass023.regclass023
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass023.regclass023;
// <Title> Tests regular class auto property used in static generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return TestMethod<Test>();
}
private static int TestMethod<T>()
{
dynamic dy = new MemberClass();
dy.Property_MyEnumArr = new MyEnum[0];
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass024.regclass024
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass024.regclass024;
// <Title> Tests regular class auto property used in static generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return TestMethod<int>();
}
private static int TestMethod<T>()
{
dynamic dy = new MemberClass();
dy.Property_shortArr = new short[2];
try
{
short[] result = dy.Property_shortArr; // protected
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_shortArr"))
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass025.regclass025
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass025.regclass025;
// <Title> Tests regular class auto property used in inside#if, #else block.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass();
ulong[] array = null;
dy.Property_ulongArr = new ulong[]
{
0, 1
}
;
#if MS
array = new ulong[] { (ulong)dy.Property_ulong };
#else
try
{
array = dy.Property_ulongArr;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_ulongArr"))
return 0;
else
{
System.Console.WriteLine(e);
return 1;
}
}
#endif
// different case actually
if (array.Length == 2 && array[0] == 0 && array[1] == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass026.regclass026
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass026.regclass026;
// <Title> Tests regular class auto property used in regular method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (new Test().TestMethod())
return 0;
return 1;
}
private bool TestMethod()
{
dynamic dy = new MemberClass();
bool[] result = dy.Property_boolArr;
return result == null;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass027.regclass027
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass027.regclass027;
// <Title> Tests regular class auto property used in using block.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.IO;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
mc.Property_decimalArr = new decimal[]
{
1M, 1.1M
}
;
dynamic dy = mc;
using (MemoryStream ms = new MemoryStream())
{
if (((decimal[])dy.Property_decimalArr)[0] != 1M && ((decimal[])dy.Property_decimalArr)[1] != 1.1M)
return 1;
}
using (MemoryStream ms = new MemoryStream())
{
dy.Property_decimalArr = new decimal[]
{
10M
}
;
((decimal[])dy.Property_decimalArr)[0] = 10.01M;
}
if (mc.Property_decimalArr.Length == 1 && mc.Property_decimalArr[0] == 10.01M)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass028.regclass028
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass028.regclass028;
// <Title> Tests regular class auto property used in ternary operator expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
return t.TestGet() + t.TestSet();
}
public int TestGet()
{
MemberClass mc = new MemberClass();
mc.Property_MyStructNullArr = new MyStruct?[]
{
null, new MyStruct()
{
Number = 10
}
}
;
dynamic dy = mc;
return (int)dy.Property_MyStructNullArr.Length == 2 ? 0 : 1;
}
public int TestSet()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_MyStructNullArr = new MyStruct?[]
{
null, new MyStruct()
{
Number = 10
}
}
;
mc = dy;
return (int)dy.Property_MyStructNullArr.Length == 2 ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass029.regclass029
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass029.regclass029;
// <Title> Tests regular class auto property used in null coalescing operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass();
try
{
MyEnum?[] result = dy.Property_MyEnumNullArr ?? new MyEnum?[1]; //private, should have exception
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_MyEnumNullArr"))
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass030.regclass030
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass030.regclass030;
// <Title> Tests regular class auto property used in constructor.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static int Return;
public Test()
{
dynamic dy = new MemberClass();
try
{
// public for struct
short?[] result = dy.Property_shortNullArr; //protected, should have exception
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_shortNullArr"))
Test.Return = 0;
else
Test.Return = 1;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
return Test.Return;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass031.regclass031
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass031.regclass031;
// <Title> Tests regular class auto property used in null coalescing operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
ulong?[] result1 = dy.Property_ulongNullArr ?? new ulong?[1];
if (result1.Length != 1 || dy.Property_ulongNullArr != null)
return 1;
dy.Property_ulongNullArr = dy.Property_ulongNullArr ?? new ulong?[0];
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass032.regclass032
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass032.regclass032;
// <Title> Tests regular class auto property used in static variable.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static dynamic s_dy = new MemberClass();
private static char?[] s_result = s_dy.Property_charNullArr;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (s_result == null)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass034.regclass034
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass034.regclass034;
// <Title> Tests regular class auto property used in switch section statement.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
int result = int.MaxValue;
try
{
dy.Property_decimalNullArr = new decimal?[]
{
int.MinValue
}
;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "MemberClass.Property_decimalNullArr"))
result = int.MaxValue;
}
switch (result)
{
case int.MaxValue:
try
{
result = (int)((decimal?[])dy.Property_decimalNullArr)[0];
}
catch (System.NullReferenceException)
{
result = int.MinValue;
}
break;
default:
break;
}
if (result == int.MinValue)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass035.regclass035
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass035.regclass035;
// <Title> Tests regular class auto property used in switch default section statement.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
int result = 4;
dy.Property_Float = 4;
switch (result)
{
case 4:
dy.Property_Float = float.NaN;
break;
default:
result = (int)dy.Property_Float;
break;
}
if (result == 4)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass036.regclass036
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass036.regclass036;
// <Title> Tests regular class auto property used in foreach body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass mc = new MemberClass();
dynamic dy = mc;
dy.Property_FloatNullArr = new float?[]
{
float.Epsilon, float.MaxValue, float.MinValue, float.NaN, float.NegativeInfinity, float.PositiveInfinity
}
;
if (dy.Property_FloatNullArr.Length == 6 && dy.Property_FloatNullArr[0] == float.Epsilon && dy.Property_FloatNullArr[1] == float.MaxValue && dy.Property_FloatNullArr[2] == float.MinValue && float.IsNaN((float)dy.Property_FloatNullArr[3]) && float.IsNegativeInfinity((float)dy.Property_FloatNullArr[4]) && float.IsPositiveInfinity((float)dy.Property_FloatNullArr[5]))
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass037.regclass037
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass037.regclass037;
// <Title> Tests regular class auto property used in static method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass.Property_stringStatic = "Test";
dynamic dynamic = MemberClass.Property_stringStatic;
if ((string)dynamic == "Test")
return 0;
return 1;
}
}
//</Code>
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class JoinTests : EnumerableTests
{
public struct CustomerRec
{
public string name;
public int custID;
}
public struct OrderRec
{
public int orderID;
public int custID;
public int total;
}
public struct AnagramRec
{
public string name;
public int orderID;
public int total;
}
public struct JoinRec
{
public string name;
public int orderID;
public int total;
}
public static JoinRec createJoinRec(CustomerRec cr, OrderRec or)
{
return new JoinRec { name = cr.name, orderID = or.orderID, total = or.total };
}
public static JoinRec createJoinRec(CustomerRec cr, AnagramRec or)
{
return new JoinRec { name = cr.name, orderID = or.orderID, total = or.total };
}
[Fact]
public void OuterEmptyInnerNonEmpty()
{
CustomerRec[] outer = { };
OrderRec[] inner = new []
{
new OrderRec{ orderID = 45321, custID = 98022, total = 50 },
new OrderRec{ orderID = 97865, custID = 32103, total = 25 }
};
Assert.Empty(outer.Join(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void FirstOuterMatchesLastInnerLastOuterMatchesFirstInnerSameNumberElements()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
OrderRec[] inner = new []
{
new OrderRec{ orderID = 45321, custID = 99022, total = 50 },
new OrderRec{ orderID = 43421, custID = 29022, total = 20 },
new OrderRec{ orderID = 95421, custID = 98022, total = 9 }
};
JoinRec[] expected = new []
{
new JoinRec{ name = "Prakash", orderID = 95421, total = 9 },
new JoinRec{ name = "Robert", orderID = 45321, total = 50 }
};
Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void NullComparer()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
AnagramRec[] inner = new []
{
new AnagramRec{ name = "miT", orderID = 43455, total = 10 },
new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 }
};
JoinRec[] expected = new [] { new JoinRec{ name = "Prakash", orderID = 323232, total = 9 } };
Assert.Equal(expected, outer.Join(inner, e => e.name, e => e.name, createJoinRec, null));
}
[Fact]
public void CustomComparer()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
AnagramRec[] inner = new []
{
new AnagramRec{ name = "miT", orderID = 43455, total = 10 },
new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 }
};
JoinRec[] expected = new []
{
new JoinRec{ name = "Prakash", orderID = 323232, total = 9 },
new JoinRec{ name = "Tim", orderID = 43455, total = 10 }
};
Assert.Equal(expected, outer.Join(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer()));
}
[Fact]
public void OuterNull()
{
CustomerRec[] outer = null;
AnagramRec[] inner = new []
{
new AnagramRec{ name = "miT", orderID = 43455, total = 10 },
new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 }
};
Assert.Throws<ArgumentNullException>("outer", () => outer.Join(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer()));
}
[Fact]
public void InnerNull()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
AnagramRec[] inner = null;
Assert.Throws<ArgumentNullException>("inner", () => outer.Join(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer()));
}
[Fact]
public void OuterKeySelectorNull()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
AnagramRec[] inner = new []
{
new AnagramRec{ name = "miT", orderID = 43455, total = 10 },
new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 }
};
Assert.Throws<ArgumentNullException>("outerKeySelector", () => outer.Join(inner, null, e => e.name, createJoinRec, new AnagramEqualityComparer()));
}
[Fact]
public void InnerKeySelectorNull()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
AnagramRec[] inner = new []
{
new AnagramRec{ name = "miT", orderID = 43455, total = 10 },
new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 }
};
Assert.Throws<ArgumentNullException>("innerKeySelector", () => outer.Join(inner, e => e.name, null, createJoinRec, new AnagramEqualityComparer()));
}
[Fact]
public void ResultSelectorNull()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
AnagramRec[] inner = new []
{
new AnagramRec{ name = "miT", orderID = 43455, total = 10 },
new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 }
};
Assert.Throws<ArgumentNullException>("resultSelector", () => outer.Join(inner, e => e.name, e => e.name, (Func<CustomerRec, AnagramRec, JoinRec>)null, new AnagramEqualityComparer()));
}
[Fact]
public void OuterNullNoComparer()
{
CustomerRec[] outer = null;
AnagramRec[] inner = new[]
{
new AnagramRec{ name = "miT", orderID = 43455, total = 10 },
new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 }
};
Assert.Throws<ArgumentNullException>("outer", () => outer.Join(inner, e => e.name, e => e.name, createJoinRec));
}
[Fact]
public void InnerNullNoComparer()
{
CustomerRec[] outer = new[]
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
AnagramRec[] inner = null;
Assert.Throws<ArgumentNullException>("inner", () => outer.Join(inner, e => e.name, e => e.name, createJoinRec));
}
[Fact]
public void OuterKeySelectorNullNoComparer()
{
CustomerRec[] outer = new[]
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
AnagramRec[] inner = new[]
{
new AnagramRec{ name = "miT", orderID = 43455, total = 10 },
new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 }
};
Assert.Throws<ArgumentNullException>("outerKeySelector", () => outer.Join(inner, null, e => e.name, createJoinRec));
}
[Fact]
public void InnerKeySelectorNullNoComparer()
{
CustomerRec[] outer = new[]
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
AnagramRec[] inner = new[]
{
new AnagramRec{ name = "miT", orderID = 43455, total = 10 },
new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 }
};
Assert.Throws<ArgumentNullException>("innerKeySelector", () => outer.Join(inner, e => e.name, null, createJoinRec));
}
[Fact]
public void ResultSelectorNullNoComparer()
{
CustomerRec[] outer = new[]
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
AnagramRec[] inner = new[]
{
new AnagramRec{ name = "miT", orderID = 43455, total = 10 },
new AnagramRec{ name = "Prakash", orderID = 323232, total = 9 }
};
Assert.Throws<ArgumentNullException>("resultSelector", () => outer.Join(inner, e => e.name, e => e.name, (Func<CustomerRec, AnagramRec, JoinRec>)null));
}
[Fact]
public void SkipsNullElements()
{
string[] outer = new [] { null, string.Empty };
string[] inner = new [] { null, string.Empty };
string[] expected = new [] { string.Empty };
Assert.Equal(expected, outer.Join(inner, e => e, e => e, (x, y) => y, EqualityComparer<string>.Default));
}
[Fact]
public void OuterNonEmptyInnerEmpty()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Tim", custID = 43434 },
new CustomerRec{ name = "Bob", custID = 34093 }
};
OrderRec[] inner = { };
Assert.Empty(outer.Join(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void SingleElementEachAndMatches()
{
CustomerRec[] outer = new [] { new CustomerRec { name = "Prakash", custID = 98022 } };
OrderRec[] inner = new [] { new OrderRec { orderID = 45321, custID = 98022, total = 50 } };
JoinRec[] expected = new [] { new JoinRec { name = "Prakash", orderID = 45321, total = 50 } };
Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void SingleElementEachAndDoesntMatch()
{
CustomerRec[] outer = new [] { new CustomerRec { name = "Prakash", custID = 98922 } };
OrderRec[] inner = new [] { new OrderRec { orderID = 45321, custID = 98022, total = 50 } };
Assert.Empty(outer.Join(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void SelectorsReturnNull()
{
int?[] inner = { null, null, null };
int?[] outer = { null, null };
Assert.Empty(outer.Join(inner, e => e, e => e, (x, y) => x));
}
[Fact]
public void InnerSameKeyMoreThanOneElementAndMatches()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
OrderRec[] inner = new []
{
new OrderRec{ orderID = 45321, custID = 98022, total = 50 },
new OrderRec{ orderID = 45421, custID = 98022, total = 10 },
new OrderRec{ orderID = 43421, custID = 99022, total = 20 },
new OrderRec{ orderID = 85421, custID = 98022, total = 18 },
new OrderRec{ orderID = 95421, custID = 99021, total = 9 }
};
JoinRec[] expected = new []
{
new JoinRec{ name = "Prakash", orderID = 45321, total = 50 },
new JoinRec{ name = "Prakash", orderID = 45421, total = 10 },
new JoinRec{ name = "Prakash", orderID = 85421, total = 18 },
new JoinRec{ name = "Tim", orderID = 95421, total = 9 },
new JoinRec{ name = "Robert", orderID = 43421, total = 20 }
};
Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void OuterSameKeyMoreThanOneElementAndMatches()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Bob", custID = 99022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
OrderRec[] inner = new []
{
new OrderRec{ orderID = 45321, custID = 98022, total = 50 },
new OrderRec{ orderID = 43421, custID = 99022, total = 20 },
new OrderRec{ orderID = 95421, custID = 99021, total = 9 }
};
JoinRec[] expected = new []
{
new JoinRec{ name = "Prakash", orderID = 45321, total = 50 },
new JoinRec{ name = "Bob", orderID = 43421, total = 20 },
new JoinRec{ name = "Tim", orderID = 95421, total = 9 },
new JoinRec{ name = "Robert", orderID = 43421, total = 20 }
};
Assert.Equal(expected, outer.Join(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void NoMatches()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Prakash", custID = 98022 },
new CustomerRec{ name = "Bob", custID = 99022 },
new CustomerRec{ name = "Tim", custID = 99021 },
new CustomerRec{ name = "Robert", custID = 99022 }
};
OrderRec[] inner = new []
{
new OrderRec{ orderID = 45321, custID = 18022, total = 50 },
new OrderRec{ orderID = 43421, custID = 29022, total = 20 },
new OrderRec{ orderID = 95421, custID = 39021, total = 9 }
};
Assert.Empty(outer.Join(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Join(Enumerable.Empty<int>(), i => i, i => i, (o, i) => i);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="BasicViewGenerator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Mapping.ViewGeneration
{
using System.Collections.Generic;
using System.Data.Common.Utils;
using System.Data.Entity;
using System.Data.Mapping.ViewGeneration.QueryRewriting;
using System.Data.Mapping.ViewGeneration.Structures;
using System.Data.Mapping.ViewGeneration.Utils;
using System.Data.Mapping.ViewGeneration.Validation;
using System.Data.Metadata.Edm;
using System.Diagnostics;
using System.Linq;
using System.Text;
// This class generates a view for an extent that may contain self-joins
// and self-unions -- this can be later simplified or optimized
// Output: A cell tree with LeftCellWrappers as nodes connected by Union, IJ,
// LOJ, FOJs
internal class BasicViewGenerator : InternalBase
{
#region Constructor
// effects: Creates a view generator object that can be used to generate views
// based on usedCells (projectedSlotMap are useful for deciphering the fields)
internal BasicViewGenerator(MemberProjectionIndex projectedSlotMap, List<LeftCellWrapper> usedCells, FragmentQuery activeDomain,
ViewgenContext context, MemberDomainMap domainMap, ErrorLog errorLog, ConfigViewGenerator config)
{
Debug.Assert(usedCells.Count > 0, "No used cells");
m_projectedSlotMap = projectedSlotMap;
m_usedCells = usedCells;
m_viewgenContext = context;
m_activeDomain = activeDomain;
m_errorLog = errorLog;
m_config = config;
m_domainMap = domainMap;
}
#endregion
#region Fields
private MemberProjectionIndex m_projectedSlotMap;
private List<LeftCellWrapper> m_usedCells;
// Active domain comprises all multiconstants that need to be reconstructed
private FragmentQuery m_activeDomain;
// these two are temporarily needed for checking containment
private ViewgenContext m_viewgenContext;
private ErrorLog m_errorLog;
private ConfigViewGenerator m_config;
private MemberDomainMap m_domainMap;
#endregion
#region Properties
private FragmentQueryProcessor LeftQP
{
get { return m_viewgenContext.LeftFragmentQP; }
}
#endregion
#region Exposed Methods
// effects: Given the set of used cells for an extent, returns a
// view to generate that extent
internal CellTreeNode CreateViewExpression()
{
// Create an initial FOJ group with all the used cells as children
OpCellTreeNode fojNode = new OpCellTreeNode(m_viewgenContext, CellTreeOpType.FOJ);
// Add all the used cells as children to fojNode. This is a valid
// view for the extent. We later try to optimize it
foreach (LeftCellWrapper cell in m_usedCells)
{
LeafCellTreeNode cellNode = new LeafCellTreeNode(m_viewgenContext, cell);
fojNode.Add(cellNode);
}
//rootNode = GroupByNesting(rootNode);
// Group cells by the "right" extent (recall that we are
// generating the view for the left extent) so that cells of the
// same extent are in the same subtree
CellTreeNode rootNode = GroupByRightExtent(fojNode);
// Change some of the FOJs to Unions, IJs and LOJs
rootNode = IsolateUnions(rootNode);
// The isolation with Union is different from IsolateUnions --
// the above isolation finds collections of chidren in a
// node and connects them by union. The below one only considers
// two children at a time
rootNode = IsolateByOperator(rootNode, CellTreeOpType.Union);
rootNode = IsolateByOperator(rootNode, CellTreeOpType.IJ);
rootNode = IsolateByOperator(rootNode, CellTreeOpType.LOJ);
if (m_viewgenContext.ViewTarget == ViewTarget.QueryView)
{
rootNode = ConvertUnionsToNormalizedLOJs(rootNode);
}
return rootNode;
}
#endregion
#region Private Methods
// requires: The tree rooted at cellTreeNode is an FOJ tree of
// LeafCellTreeNodes only, i.e., there is an FOJ node with the
// children being LeafCellTreeNodes
//
// effects: Given a tree rooted at rootNode, ensures that cells
// of the same right extent are placed in their own subtree below
// cellTreeNode. That is, if there are 3 cells of extent A and 2 of
// extent B (i.e., 5 cells with an FOJ on it), the resulting tree has
// an FOJ node with two children -- FOJ nodes. These FOJ nodes have 2
// and 3 children
internal CellTreeNode GroupByRightExtent(CellTreeNode rootNode)
{
// A dictionary that maps an extent to the nodes are from that extent
// We want a ref comparer here
KeyToListMap<EntitySetBase, LeafCellTreeNode> extentMap =
new KeyToListMap<EntitySetBase, LeafCellTreeNode>(EqualityComparer<EntitySetBase>.Default);
// CR_Meek_Low: method can be simplified (Map<Extent, OpCellTreeNode>, populate as you go)
// (becomes self-documenting)
// For each leaf child, find the extent of the child and place it
// in extentMap
foreach (LeafCellTreeNode childNode in rootNode.Children)
{
// A cell may contain P, P.PA -- we return P
// CHANGE_[....]_FEATURE_COMPOSITION Need to fix for composition!!
EntitySetBase extent = childNode.LeftCellWrapper.RightCellQuery.Extent; // relation or extent to group by
Debug.Assert(extent != null, "Each cell must have a right extent");
// Add the childNode as a child of the FOJ tree for "extent"
extentMap.Add(extent, childNode);
}
// Now go through the extent map and create FOJ nodes for each extent
// Place the nodes for that extent in the newly-created FOJ subtree
// Also add the op node for every node as a child of the final result
OpCellTreeNode result = new OpCellTreeNode(m_viewgenContext, CellTreeOpType.FOJ);
foreach (EntitySetBase extent in extentMap.Keys)
{
OpCellTreeNode extentFojNode = new OpCellTreeNode(m_viewgenContext, CellTreeOpType.FOJ);
foreach (LeafCellTreeNode childNode in extentMap.ListForKey(extent))
{
extentFojNode.Add(childNode);
}
result.Add(extentFojNode);
}
// We call Flatten to remove any unnecessary nestings
// where an OpNode has only 1 child.
return result.Flatten();
}
// requires: cellTreeNode has a tree such that all its intermediate nodes
// are FOJ nodes only
// effects: Converts the tree rooted at rootNode (recursively) in
// following way and returns a new rootNode -- it partitions
// rootNode's children such that no two different partitions have
// any overlapping constants. These partitions are connected by Union
// nodes (since there is no overlapping).
// Note: Method may modify rootNode's contents and children
private CellTreeNode IsolateUnions(CellTreeNode rootNode)
{
if (rootNode.Children.Count <= 1)
{
// No partitioning of children needs to be done
return rootNode;
}
Debug.Assert(rootNode.OpType == CellTreeOpType.FOJ, "So far, we have FOJs only");
// Recursively, transform the subtrees rooted at cellTreeNode's children
for (int i = 0; i < rootNode.Children.Count; i++)
{
// Method modifies input as well
rootNode.Children[i] = IsolateUnions(rootNode.Children[i]);
}
// Different children groups are connected by a Union
// node -- the secltion domain of one group is disjoint from
// another group's selection domain, i.e., group A1 contributes
// tuples to the extent which are disjoint from the tuples by
// A2. So we can connect these groups by union alls.
// Inside each group, we continue to connect children of the same
// group using FOJ
OpCellTreeNode unionNode = new OpCellTreeNode(m_viewgenContext, CellTreeOpType.Union);
// childrenSet keeps track of the children that need to be procesed/partitioned
ModifiableIteratorCollection<CellTreeNode> childrenSet = new ModifiableIteratorCollection<CellTreeNode>(rootNode.Children);
while (false == childrenSet.IsEmpty)
{
// Start a new group
// Make an FOJ node to connect children of the same group
OpCellTreeNode fojNode = new OpCellTreeNode(m_viewgenContext, CellTreeOpType.FOJ);
// Add one of the root's children as a child to the foj node
CellTreeNode someChild = childrenSet.RemoveOneElement();
fojNode.Add(someChild);
// We now want a transitive closure of the overlap between the
// the children node. We keep checking each child with the
// fojNode and add it as a child of fojNode if there is an
// overlap. Note that when a node is added to the fojNode,
// its constants are propagated to the fojNode -- so we do
// get transitive closure in terms of intersection
foreach (CellTreeNode child in childrenSet.Elements())
{
if (!IsDisjoint(fojNode, child))
{
fojNode.Add(child);
childrenSet.RemoveCurrentOfIterator();
// To ensure that we get all overlapping node, we
// need to restart checking all the children
childrenSet.ResetIterator();
}
}
// Now we have a group of children nodes rooted at
// fojNode. Add this fojNode to the union
unionNode.Add(fojNode);
}
// The union node as the root of the view
CellTreeNode result = unionNode.Flatten();
return result;
}
/// <summary>
/// Traverse the tree and perform the following rewrites:
/// 1. Flatten unions contained as left children of LOJs: LOJ(A, Union(B, C)) -> LOJ(A, B, C).
/// 2. Rewrite flat LOJs into nested LOJs. The nesting is determined by FKs between right cell table PKs.
/// Example: if we have an LOJ(A, B, C, D) and we know there are FKs from C.PK and D.PK to B.PK,
/// we want to rewrite into this - LOJ(A, LOJ(B, C, D)).
/// 3. As a special case we also look into LOJ driving node (left most child in LOJ) and if it is an IJ,
/// then we consider attaching LOJ children to nodes inside IJ based on the same principle as above.
/// Example: LOJ(IJ(A, B, C), D, E, F) -> LOJ(IJ(LOJ(A, D), B, LOJ(C, E)), F) iff D has FK to A and E has FK to C.
///
/// This normalization enables FK-based join elimination in plan compiler, so for a query such as
/// "select e.ID from ABCDSet" we want plan compiler to produce "select a.ID from A" instead of
/// "select a.ID from A LOJ B LOJ C LOJ D".
/// </summary>
private CellTreeNode ConvertUnionsToNormalizedLOJs(CellTreeNode rootNode)
{
// Recursively, transform the subtrees rooted at rootNode's children.
for (int i = 0; i < rootNode.Children.Count; i++)
{
// Method modifies input as well.
rootNode.Children[i] = ConvertUnionsToNormalizedLOJs(rootNode.Children[i]);
}
// We rewrite only LOJs.
if (rootNode.OpType != CellTreeOpType.LOJ || rootNode.Children.Count < 2)
{
return rootNode;
}
// Create the resulting LOJ node.
var result = new OpCellTreeNode(m_viewgenContext, rootNode.OpType);
// Create working collection for the LOJ children.
var children = new List<CellTreeNode>();
// If rootNode looks something like ((V0 IJ V1) LOJ V2 LOJ V3),
// and it turns out that there are FK associations from V2 or V3 pointing, let's say at V0,
// then we want to rewrite the result as (V1 IJ (V0 LOJ V2 LOJ V3)).
// If we don't do this, then plan compiler won't have a chance to eliminate LOJ V2 LOJ V3.
// Hence, flatten the first child or rootNode if it's IJ, but remember that its parts are driving nodes for the LOJ,
// so that we don't accidentally nest them.
OpCellTreeNode resultIJDriver = null;
HashSet<CellTreeNode> resultIJDriverChildren = null;
if (rootNode.Children[0].OpType == CellTreeOpType.IJ)
{
// Create empty resultIJDriver node and add it as the first child (driving) into the LOJ result.
resultIJDriver = new OpCellTreeNode(m_viewgenContext, rootNode.Children[0].OpType);
result.Add(resultIJDriver);
children.AddRange(rootNode.Children[0].Children);
resultIJDriverChildren = new HashSet<CellTreeNode>(rootNode.Children[0].Children);
}
else
{
result.Add(rootNode.Children[0]);
}
// Flatten unions in non-driving nodes: (V0 LOJ (V1 Union V2 Union V3)) -> (V0 LOJ V1 LOJ V2 LOJ V3)
foreach (var child in rootNode.Children.Skip(1))
{
var opNode = child as OpCellTreeNode;
if (opNode != null && opNode.OpType == CellTreeOpType.Union)
{
children.AddRange(opNode.Children);
}
else
{
children.Add(child);
}
}
// A dictionary that maps an extent to the nodes that are from that extent.
// We want a ref comparer here.
var extentMap = new KeyToListMap<EntitySet, LeafCellTreeNode>(EqualityComparer<EntitySet>.Default);
// Note that we skip non-leaf nodes (non-leaf nodes don't have FKs) and attach them directly to the result.
foreach (var child in children)
{
var leaf = child as LeafCellTreeNode;
if (leaf != null)
{
EntitySetBase extent = GetLeafNodeTable(leaf);
if (extent != null)
{
extentMap.Add((EntitySet)extent, leaf);
}
}
else
{
if (resultIJDriverChildren != null && resultIJDriverChildren.Contains(child))
{
resultIJDriver.Add(child);
}
else
{
result.Add(child);
}
}
}
// We only deal with simple cases - one node per extent, remove the rest from children and attach directly to result.
var nonTrivial = extentMap.KeyValuePairs.Where(m => m.Value.Count > 1).ToArray();
foreach (var m in nonTrivial)
{
extentMap.RemoveKey(m.Key);
foreach (var n in m.Value)
{
if (resultIJDriverChildren != null && resultIJDriverChildren.Contains(n))
{
resultIJDriver.Add(n);
}
else
{
result.Add(n);
}
}
}
Debug.Assert(extentMap.KeyValuePairs.All(m => m.Value.Count == 1), "extentMap must map to single nodes only.");
// Walk the extents in extentMap and for each extent build PK -> FK1(PK1), FK2(PK2), ... map
// where PK is the primary key of the left extent, and FKn(PKn) is an FK of a right extent that
// points to the PK of the left extent and is based on the PK columns of the right extent.
// Example:
// table tBaseType(Id int, c1 int), PK = (tBaseType.Id)
// table tDerivedType1(Id int, c2 int), PK1 = (tDerivedType1.Id), FK1 = (tDerivedType1.Id -> tBaseType.Id)
// table tDerivedType2(Id int, c3 int), PK2 = (tDerivedType2.Id), FK2 = (tDerivedType2.Id -> tBaseType.Id)
// Will produce:
// (tBaseType) -> (tDerivedType1, tDerivedType2)
var pkFkMap = new KeyToListMap<EntitySet, EntitySet>(EqualityComparer<EntitySet>.Default);
// Also for each extent in extentMap, build another map (extent) -> (LOJ node).
// It will be used to construct the nesting in the next step.
var extentLOJs = new Dictionary<EntitySet, OpCellTreeNode>(EqualityComparer<EntitySet>.Default);
foreach (var extentInfo in extentMap.KeyValuePairs)
{
var principalExtent = extentInfo.Key;
foreach (var fkExtent in GetFKOverPKDependents(principalExtent))
{
// Only track fkExtents that are in extentMap.
System.Collections.ObjectModel.ReadOnlyCollection<LeafCellTreeNode> nodes;
if (extentMap.TryGetListForKey(fkExtent, out nodes))
{
// Make sure that we are not adding resultIJDriverChildren as FK dependents - we do not want them to get nested.
if (resultIJDriverChildren == null || !resultIJDriverChildren.Contains(nodes.Single()))
{
pkFkMap.Add(principalExtent, fkExtent);
}
}
}
var extentLojNode = new OpCellTreeNode(m_viewgenContext, CellTreeOpType.LOJ);
extentLojNode.Add(extentInfo.Value.Single());
extentLOJs.Add(principalExtent, extentLojNode);
}
// Construct LOJ nesting inside extentLOJs based on the information in pkFkMap.
// Also, track nested extents using nestedExtents.
// Example:
// We start with nestedExtents empty extentLOJs as such:
// tBaseType -> LOJ(BaseTypeNode)
// tDerivedType1 -> LOJ(DerivedType1Node)*
// tDerivedType2 -> LOJ(DerivedType2Node)**
// Note that * and ** represent object references. So each time something is nested,
// we don't clone, but nest the original LOJ. When we get to processing the extent of that LOJ,
// we might add other children to that nested LOJ.
// As we walk pkFkMap, we end up with this:
// tBaseType -> LOJ(BaseTypeNode, LOJ(DerivedType1Node)*, LOJ(DerivedType2Node)**)
// tDerivedType1 -> LOJ(DerivedType1Node)*
// tDerivedType2 -> LOJ(DerivedType2Node)**
// nestedExtens = (tDerivedType1, tDerivedType2)
var nestedExtents = new Dictionary<EntitySet, EntitySet>(EqualityComparer<EntitySet>.Default);
foreach (var m in pkFkMap.KeyValuePairs)
{
var principalExtent = m.Key;
foreach (var fkExtent in m.Value)
{
OpCellTreeNode fkExtentLOJ;
if (extentLOJs.TryGetValue(fkExtent, out fkExtentLOJ) &&
// make sure we don't nest twice and we don't create a cycle.
!nestedExtents.ContainsKey(fkExtent) && !CheckLOJCycle(fkExtent, principalExtent, nestedExtents))
{
extentLOJs[m.Key].Add(fkExtentLOJ);
nestedExtents.Add(fkExtent, principalExtent);
}
}
}
// Now we need to grab the LOJs that have not been nested and add them to the result.
// All LOJs that have been nested must be somewhere inside the LOJs that have not been nested,
// so they as well end up in the result as part of the unnested ones.
foreach (var m in extentLOJs)
{
if (!nestedExtents.ContainsKey(m.Key))
{
// extentLOJ represents (Vx LOJ Vy LOJ(Vm LOJ Vn)) where Vx is the original node from rootNode.Children or resultIJDriverChildren.
var extentLOJ = m.Value;
if (resultIJDriverChildren != null && resultIJDriverChildren.Contains(extentLOJ.Children[0]))
{
resultIJDriver.Add(extentLOJ);
}
else
{
result.Add(extentLOJ);
}
}
}
return result.Flatten();
}
private static IEnumerable<EntitySet> GetFKOverPKDependents(EntitySet principal)
{
foreach (var pkFkInfo in principal.ForeignKeyPrincipals)
{
// If principal has a related extent with FK pointing to principal and the FK is based on PK columns of the related extent,
// then add it.
var pkColumns = pkFkInfo.Item2.ToRole.GetEntityType().KeyMembers;
var fkColumns = pkFkInfo.Item2.ToProperties;
if (pkColumns.Count == fkColumns.Count)
{
// Compare PK to FK columns, order is important (otherwise it's not an FK over PK).
int i = 0;
for (; i < pkColumns.Count && pkColumns[i].EdmEquals(fkColumns[i]); ++i);
if (i == pkColumns.Count)
{
yield return pkFkInfo.Item1.AssociationSetEnds.Where(ase => ase.Name == pkFkInfo.Item2.ToRole.Name).Single().EntitySet;
}
}
}
}
private static EntitySet GetLeafNodeTable(LeafCellTreeNode leaf)
{
return leaf.LeftCellWrapper.RightCellQuery.Extent as EntitySet;
}
private static bool CheckLOJCycle(EntitySet child, EntitySet parent, Dictionary<EntitySet, EntitySet> nestedExtents)
{
do
{
if (EqualityComparer<EntitySet>.Default.Equals(parent, child))
{
return true;
}
}
while (nestedExtents.TryGetValue(parent, out parent));
return false;
}
// requires: opTypeToIsolate must be LOJ, IJ, or Union
// effects: Given a tree rooted at rootNode, determines if there
// are any FOJs that can be replaced by opTypeToIsolate. If so,
// does that and a returns a new tree with the replaced operators
// Note: Method may modify rootNode's contents and children
internal CellTreeNode IsolateByOperator(CellTreeNode rootNode, CellTreeOpType opTypeToIsolate)
{
Debug.Assert(opTypeToIsolate == CellTreeOpType.IJ || opTypeToIsolate == CellTreeOpType.LOJ
|| opTypeToIsolate == CellTreeOpType.Union,
"IsolateJoins can only be called for IJs, LOJs, and Unions");
List<CellTreeNode> children = rootNode.Children;
if (children.Count <= 1)
{
// No child or one child - do nothing
return rootNode;
}
// Replace the FOJs with IJs/LOJs/Unions in the children's subtrees first
for (int i = 0; i < children.Count; i++)
{
// Method modifies input as well
children[i] = IsolateByOperator(children[i], opTypeToIsolate);
}
// Only FOJs and LOJs can be coverted (to IJs, Unions, LOJs) --
// so if the node is not that, we can ignore it (or if the node is already of
// the same type that we want)
if (rootNode.OpType != CellTreeOpType.FOJ && rootNode.OpType != CellTreeOpType.LOJ ||
rootNode.OpType == opTypeToIsolate)
{
return rootNode;
}
// Create a new node with the same type as the input cell node type
OpCellTreeNode newRootNode = new OpCellTreeNode(m_viewgenContext, rootNode.OpType);
// We start a new "group" with one of the children X - we create
// a newChildNode with type "opTypeToIsolate". Then we
// determine if any of the remaining children should be in the
// same group as X.
// childrenSet keeps track of the children that need to be procesed/partitioned
ModifiableIteratorCollection<CellTreeNode> childrenSet = new ModifiableIteratorCollection<CellTreeNode>(children);
// Find groups with same or subsumed constants and create a join
// or union node for them. We do this so that some of the FOJs
// can be replaced by union and join nodes
//
while (false == childrenSet.IsEmpty)
{
// Start a new "group" with some child node (for the opTypeToIsolate node type)
OpCellTreeNode groupNode = new OpCellTreeNode(m_viewgenContext, opTypeToIsolate);
CellTreeNode someChild = childrenSet.RemoveOneElement();
groupNode.Add(someChild);
// Go through the remaining children and determine if their
// constants are subsets/equal/disjoint w.r.t the joinNode
// constants.
foreach (CellTreeNode child in childrenSet.Elements())
{
// Check if we can add the child as part of this
// groupNode (with opTypeToIsolate being LOJ, IJ, or Union)
if (TryAddChildToGroup(opTypeToIsolate, child, groupNode))
{
childrenSet.RemoveCurrentOfIterator();
// For LOJ, suppose that child A did not subsume B or
// vice-versa. But child C subsumes both. To ensure
// that we can get A, B, C in the same group, we
// reset the iterator so that when C is added in B's
// loop, we can reconsider A.
//
// For IJ, adding a child to groupNode does not change the range of it,
// so there is no need to reconsider previously skipped children.
//
// For Union, adding a child to groupNode increases the range of the groupNode,
// hence previously skipped (because they weren't disjoint with groupNode) children will continue
// being ignored because they would still have an overlap with one of the nodes inside groupNode.
if (opTypeToIsolate == CellTreeOpType.LOJ)
{
childrenSet.ResetIterator();
}
}
}
// The new Union/LOJ/IJ node needs to be connected to the root
newRootNode.Add(groupNode);
}
return newRootNode.Flatten();
}
// effects: Determines if the childNode can be added as a child of the
// groupNode using te operation "opTypeToIsolate". E.g., if
// opTypeToIsolate is inner join, we can add child to group node if
// childNode and groupNode have the same multiconstantsets, i.e., they have
// the same selection condition
// Modifies groupNode to contain groupNode at the appropriate
// position (for LOJs, the child could be added to the beginning)
private bool TryAddChildToGroup(CellTreeOpType opTypeToIsolate, CellTreeNode childNode,
OpCellTreeNode groupNode)
{
switch (opTypeToIsolate)
{
case CellTreeOpType.IJ:
// For Inner join, the constants of the node and
// the child must be the same, i.e., if the cells
// are producing exactly same tuples (same selection)
if (IsEquivalentTo(childNode, groupNode))
{
groupNode.Add(childNode);
return true;
}
break;
case CellTreeOpType.LOJ:
// If one cell's selection condition subsumes
// another, we can use LOJ. We need to check for
// "subsumes" on both sides
if (IsContainedIn(childNode, groupNode))
{
groupNode.Add(childNode);
return true;
}
else if (IsContainedIn(groupNode, childNode))
{
// child subsumes the whole group -- add it first
groupNode.AddFirst(childNode);
return true;
}
break;
case CellTreeOpType.Union:
// If the selection conditions are disjoint, we can use UNION ALL
// We cannot use active domain here; disjointness is guaranteed only
// if we check the entire selection domain
if (IsDisjoint(childNode, groupNode))
{
groupNode.Add(childNode);
return true;
}
break;
}
return false;
}
private bool IsDisjoint(CellTreeNode n1, CellTreeNode n2)
{
bool isQueryView = (m_viewgenContext.ViewTarget == ViewTarget.QueryView);
bool isDisjointLeft = LeftQP.IsDisjointFrom(n1.LeftFragmentQuery, n2.LeftFragmentQuery);
if (isDisjointLeft && m_viewgenContext.ViewTarget == ViewTarget.QueryView)
{
return true;
}
CellTreeNode n = new OpCellTreeNode(m_viewgenContext, CellTreeOpType.IJ, n1, n2);
bool isDisjointRight = n.IsEmptyRightFragmentQuery;
if (m_viewgenContext.ViewTarget == ViewTarget.UpdateView &&
isDisjointLeft && !isDisjointRight)
{
if (ErrorPatternMatcher.FindMappingErrors(m_viewgenContext, m_domainMap, m_errorLog))
{
return false;
}
StringBuilder builder = new StringBuilder(Strings.Viewgen_RightSideNotDisjoint(m_viewgenContext.Extent.ToString()));
builder.AppendLine();
//Retrieve the offending state
FragmentQuery intersection = LeftQP.Intersect(n1.RightFragmentQuery, n2.RightFragmentQuery);
if (LeftQP.IsSatisfiable(intersection))
{
intersection.Condition.ExpensiveSimplify();
RewritingValidator.EntityConfigurationToUserString(intersection.Condition, builder);
}
//Add Error
m_errorLog.AddEntry(new ErrorLog.Record(true, ViewGenErrorCode.DisjointConstraintViolation,
builder.ToString(), m_viewgenContext.AllWrappersForExtent, String.Empty));
ExceptionHelpers.ThrowMappingException(m_errorLog, m_config);
return false;
}
return (isDisjointLeft || isDisjointRight);
}
private bool IsContainedIn(CellTreeNode n1, CellTreeNode n2)
{
// Decide whether to IJ or LOJ using the domains that are filtered by the active domain
// The net effect is that some unneeded multiconstants will be pruned away in IJ/LOJ
// It is desirable to do so since we are only interested in the active domain
FragmentQuery n1Active = LeftQP.Intersect(n1.LeftFragmentQuery, m_activeDomain);
FragmentQuery n2Active = LeftQP.Intersect(n2.LeftFragmentQuery, m_activeDomain);
bool isContainedLeft = LeftQP.IsContainedIn(n1Active, n2Active);
if (isContainedLeft)
{
return true;
}
CellTreeNode n = new OpCellTreeNode(m_viewgenContext, CellTreeOpType.LASJ, n1, n2);
bool isContainedRight = n.IsEmptyRightFragmentQuery;
return isContainedRight;
}
private bool IsEquivalentTo(CellTreeNode n1, CellTreeNode n2)
{
return IsContainedIn(n1, n2) && IsContainedIn(n2, n1);
}
#endregion
#region String methods
internal override void ToCompactString(StringBuilder builder)
{
// We just print the slotmap for now
m_projectedSlotMap.ToCompactString(builder);
}
#endregion
}
}
| |
using Sanford.Multimedia.Midi;
namespace SequencerDemo
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.stopButton = new System.Windows.Forms.Button();
this.startButton = new System.Windows.Forms.Button();
this.continueButton = new System.Windows.Forms.Button();
this.positionHScrollBar = new System.Windows.Forms.HScrollBar();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mIDIToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.outputDeviceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openMidiFileDialog = new System.Windows.Forms.OpenFileDialog();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.pianoControl1 = new Sanford.Multimedia.Midi.UI.PianoControl();
this.sequence1 = new Sanford.Multimedia.Midi.Sequence();
this.sequencer1 = new Sanford.Multimedia.Midi.Sequencer();
this.menuStrip1.SuspendLayout();
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
//
// stopButton
//
this.stopButton.Location = new System.Drawing.Point(86, 79);
this.stopButton.Name = "stopButton";
this.stopButton.Size = new System.Drawing.Size(75, 23);
this.stopButton.TabIndex = 0;
this.stopButton.Text = "Stop";
this.stopButton.UseVisualStyleBackColor = true;
this.stopButton.Click += new System.EventHandler(this.stopButton_Click);
//
// startButton
//
this.startButton.Location = new System.Drawing.Point(185, 79);
this.startButton.Name = "startButton";
this.startButton.Size = new System.Drawing.Size(75, 23);
this.startButton.TabIndex = 1;
this.startButton.Text = "Start";
this.startButton.UseVisualStyleBackColor = true;
this.startButton.Click += new System.EventHandler(this.startButton_Click);
//
// continueButton
//
this.continueButton.Location = new System.Drawing.Point(286, 79);
this.continueButton.Name = "continueButton";
this.continueButton.Size = new System.Drawing.Size(75, 23);
this.continueButton.TabIndex = 2;
this.continueButton.Text = "Continue";
this.continueButton.UseVisualStyleBackColor = true;
this.continueButton.Click += new System.EventHandler(this.continueButton_Click);
//
// positionHScrollBar
//
this.positionHScrollBar.Location = new System.Drawing.Point(12, 46);
this.positionHScrollBar.Name = "positionHScrollBar";
this.positionHScrollBar.Size = new System.Drawing.Size(424, 17);
this.positionHScrollBar.TabIndex = 3;
this.positionHScrollBar.Scroll += new System.Windows.Forms.ScrollEventHandler(this.positionHScrollBar_Scroll);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.mIDIToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(695, 24);
this.menuStrip1.TabIndex = 4;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(112, 22);
this.openToolStripMenuItem.Text = "&Open...";
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(109, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(112, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// mIDIToolStripMenuItem
//
this.mIDIToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.outputDeviceToolStripMenuItem});
this.mIDIToolStripMenuItem.Name = "mIDIToolStripMenuItem";
this.mIDIToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.mIDIToolStripMenuItem.Text = "&MIDI";
//
// outputDeviceToolStripMenuItem
//
this.outputDeviceToolStripMenuItem.Name = "outputDeviceToolStripMenuItem";
this.outputDeviceToolStripMenuItem.Size = new System.Drawing.Size(159, 22);
this.outputDeviceToolStripMenuItem.Text = "Output Device...";
this.outputDeviceToolStripMenuItem.Click += new System.EventHandler(this.outputDeviceToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "&Help";
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(116, 22);
this.aboutToolStripMenuItem.Text = "&About...";
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// openMidiFileDialog
//
this.openMidiFileDialog.DefaultExt = "mid";
this.openMidiFileDialog.Filter = "MIDI files|*.mid|All files|*.*";
this.openMidiFileDialog.Title = "Open MIDI file";
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripProgressBar1});
this.statusStrip1.Location = new System.Drawing.Point(0, 360);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(695, 22);
this.statusStrip1.TabIndex = 6;
this.statusStrip1.Text = "statusStrip1";
//
// toolStripProgressBar1
//
this.toolStripProgressBar1.Name = "toolStripProgressBar1";
this.toolStripProgressBar1.Size = new System.Drawing.Size(100, 16);
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// pianoControl1
//
this.pianoControl1.BackColor = System.Drawing.SystemColors.Control;
this.pianoControl1.HighNoteID = 109;
this.pianoControl1.Location = new System.Drawing.Point(12, 315);
this.pianoControl1.LowNoteID = 21;
this.pianoControl1.Name = "pianoControl1";
this.pianoControl1.NoteOnColor = System.Drawing.Color.SkyBlue;
this.pianoControl1.Size = new System.Drawing.Size(424, 42);
this.pianoControl1.TabIndex = 5;
this.pianoControl1.Text = "pianoControl1";
this.pianoControl1.PianoKeyDown += new System.EventHandler<Sanford.Multimedia.Midi.UI.PianoKeyEventArgs>(this.pianoControl1_PianoKeyDown);
this.pianoControl1.PianoKeyUp += new System.EventHandler<Sanford.Multimedia.Midi.UI.PianoKeyEventArgs>(this.pianoControl1_PianoKeyUp);
//
// sequence1
//
this.sequence1.Format = 1;
//
// sequencer1
//
this.sequencer1.Position = 0;
this.sequencer1.Sequence = this.sequence1;
this.sequencer1.PlayingCompleted += new System.EventHandler(this.HandlePlayingCompleted);
this.sequencer1.ChannelMessagePlayed += new System.EventHandler<Sanford.Multimedia.Midi.ChannelMessageEventArgs>(this.HandleChannelMessagePlayed);
this.sequencer1.SysExMessagePlayed += new System.EventHandler<Sanford.Multimedia.Midi.SysExMessageEventArgs>(this.HandleSysExMessagePlayed);
this.sequencer1.Chased += new System.EventHandler<Sanford.Multimedia.Midi.ChasedEventArgs>(this.HandleChased);
this.sequencer1.Stopped += new System.EventHandler<Sanford.Multimedia.Midi.StoppedEventArgs>(this.HandleStopped);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(695, 382);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.pianoControl1);
this.Controls.Add(this.positionHScrollBar);
this.Controls.Add(this.continueButton);
this.Controls.Add(this.startButton);
this.Controls.Add(this.stopButton);
this.Controls.Add(this.menuStrip1);
this.KeyPreview = true;
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "Sequencer Demo";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button stopButton;
private System.Windows.Forms.Button startButton;
private System.Windows.Forms.Button continueButton;
private System.Windows.Forms.HScrollBar positionHScrollBar;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openMidiFileDialog;
private Sanford.Multimedia.Midi.UI.PianoControl pianoControl1;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar1;
private System.Windows.Forms.ToolStripMenuItem mIDIToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem outputDeviceToolStripMenuItem;
private Sequence sequence1;
private Sequencer sequencer1;
private System.Windows.Forms.Timer timer1;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq.Expressions;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Primitives
{
/// <summary>
/// Represents an import required by a <see cref="ComposablePart"/> object.
/// </summary>
public class ImportDefinition
{
internal static readonly string EmptyContractName = string.Empty;
private readonly Expression<Func<ExportDefinition, bool>> _constraint;
private readonly ImportCardinality _cardinality = ImportCardinality.ExactlyOne;
private readonly string _contractName = EmptyContractName;
private readonly bool _isRecomposable;
private readonly bool _isPrerequisite = true;
private Func<ExportDefinition, bool> _compiledConstraint;
private readonly IDictionary<string, object> _metadata = MetadataServices.EmptyMetadata;
/// <summary>
/// Initializes a new instance of the <see cref="ImportDefinition"/> class.
/// </summary>
/// <remarks>
/// <note type="inheritinfo">
/// Derived types calling this constructor must override the <see cref="Constraint"/>
/// property, and optionally, the <see cref="Cardinality"/>, <see cref="IsPrerequisite"/>
/// and <see cref="IsRecomposable"/>
/// properties.
/// </note>
/// </remarks>
protected ImportDefinition()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ImportDefinition"/> class
/// with the specified constraint, cardinality, value indicating if the import
/// definition is recomposable and a value indicating if the import definition
/// is a prerequisite.
/// </summary>
/// <param name="constraint">
/// A <see cref="Expression{TDelegate}"/> containing a <see cref="Func{T, TResult}"/>
/// that defines the conditions that must be matched for the <see cref="ImportDefinition"/>
/// to be satisfied by an <see cref="Export"/>.
/// </param>
/// <param name="contractName">
/// The contract name of the export that this import is interested in. The contract name
/// property is used as guidance and not automatically enforced in the constraint. If
/// the contract name is a required in the constraint then it should be added to the constraint
/// by the caller of this constructor.
/// </param>
/// <param name="cardinality">
/// One of the <see cref="ImportCardinality"/> values indicating the
/// cardinality of the <see cref="Export"/> objects required by the
/// <see cref="ImportDefinition"/>.
/// </param>
/// <param name="isRecomposable">
/// <see langword="true"/> if the <see cref="ImportDefinition"/> can be satisfied
/// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise,
/// <see langword="false"/>.
/// </param>
/// <param name="isPrerequisite">
/// <see langword="true"/> if the <see cref="ImportDefinition"/> is required to be
/// satisfied before a <see cref="ComposablePart"/> can start producing exported
/// objects; otherwise, <see langword="false"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="constraint"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="cardinality"/> is not one of the <see cref="ImportCardinality"/>
/// values.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite)
: this(contractName, cardinality, isRecomposable, isPrerequisite, MetadataServices.EmptyMetadata)
{
Requires.NotNull(constraint, nameof(constraint));
_constraint = constraint;
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object> metadata)
: this(contractName, cardinality, isRecomposable, isPrerequisite, metadata)
{
Requires.NotNull(constraint, nameof(constraint));
_constraint = constraint;
}
internal ImportDefinition(string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object> metadata)
{
if (
(cardinality != ImportCardinality.ExactlyOne) &&
(cardinality != ImportCardinality.ZeroOrMore) &&
(cardinality != ImportCardinality.ZeroOrOne)
)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_InvalidEnum, "cardinality", cardinality, typeof(ImportCardinality).Name), "cardinality");
}
_contractName = contractName ?? EmptyContractName;
_cardinality = cardinality;
_isRecomposable = isRecomposable;
_isPrerequisite = isPrerequisite;
//Metadata on imports was added in 4.5, prior to that it was ignored.
if (metadata != null)
{
_metadata = metadata;
}
}
/// <summary>
/// Gets the contract name of the export required by the import definition.
/// </summary>
/// <value>
/// A <see cref="String"/> containing the contract name of the <see cref="Export"/>
/// required by the <see cref="ContractBasedImportDefinition"/>. This property should
/// return <see cref="String.Empty"/> for imports that do not require a specific
/// contract name.
/// </value>
public virtual string ContractName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return _contractName;
}
}
/// <summary>
/// Gets the metadata of the import definition.
/// </summary>
/// <value>
/// An <see cref="IDictionary{TKey, TValue}"/> containing the metadata of the
/// <see cref="ExportDefinition"/>. The default is an empty, read-only
/// <see cref="IDictionary{TKey, TValue}"/>.
/// </value>
/// <remarks>
/// <para>
/// <note type="inheritinfo">
/// Overriders of this property should return a read-only
/// <see cref="IDictionary{TKey, TValue}"/> object with a case-sensitive,
/// non-linguistic comparer, such as <see cref="StringComparer.Ordinal"/>,
/// and should never return <see langword="null"/>.
/// If the <see cref="ImportDefinition"/> does not contain metadata
/// return an empty <see cref="IDictionary{TKey, TValue}"/> instead.
/// </note>
/// </para>
/// </remarks>
public virtual IDictionary<string, object> Metadata
{
get
{
Contract.Ensures(Contract.Result<IDictionary<string, object>>() != null);
return _metadata;
}
}
/// <summary>
/// Gets the cardinality of the exports required by the import definition.
/// </summary>
/// <value>
/// One of the <see cref="ImportCardinality"/> values indicating the
/// cardinality of the <see cref="Export"/> objects required by the
/// <see cref="ImportDefinition"/>. The default is
/// <see cref="ImportCardinality.ExactlyOne"/>
/// </value>
public virtual ImportCardinality Cardinality
{
get { return _cardinality; }
}
/// <summary>
/// Gets an expression that defines conditions that must be matched for the import
/// described by the import definition to be satisfied.
/// </summary>
/// <returns>
/// A <see cref="Expression{TDelegate}"/> containing a <see cref="Func{T, TResult}"/>
/// that defines the conditions that must be matched for the
/// <see cref="ImportDefinition"/> to be satisfied by an <see cref="Export"/>.
/// </returns>
/// <exception cref="NotImplementedException">
/// The property was not overridden by a derived class.
/// </exception>
/// <remarks>
/// <note type="inheritinfo">
/// Overriders of this property should never return <see langword="null"/>.
/// </note>
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public virtual Expression<Func<ExportDefinition, bool>> Constraint
{
get
{
Contract.Ensures(Contract.Result<Expression<Func<ExportDefinition, bool>>>() != null);
if (_constraint != null)
{
return _constraint;
}
throw ExceptionBuilder.CreateNotOverriddenByDerived("Constraint");
}
}
/// <summary>
/// Gets a value indicating whether the import definition is required to be
/// satisfied before a part can start producing exported values.
/// </summary>
/// <value>
/// <see langword="true"/> if the <see cref="ImportDefinition"/> is required to be
/// satisfied before a <see cref="ComposablePart"/> can start producing exported
/// objects; otherwise, <see langword="false"/>. The default is <see langword="true"/>.
/// </value>
public virtual bool IsPrerequisite
{
get { return _isPrerequisite; }
}
/// <summary>
/// Gets a value indicating whether the import definition can be satisfied multiple times.
/// </summary>
/// <value>
/// <see langword="true"/> if the <see cref="ImportDefinition"/> can be satisfied
/// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise,
/// <see langword="false"/>. The default is <see langword="false"/>.
/// </value>
public virtual bool IsRecomposable
{
get { return _isRecomposable; }
}
/// <summary>
/// Executes of the constraint provided by the <see cref="Constraint"/> property
/// against a given <see cref="ExportDefinition"/> to determine if this
/// <see cref="ImportDefinition"/> can be satisfied by the given <see cref="Export"/>.
/// </summary>
/// <param name="exportDefinition">
/// A definition for a <see cref="Export"/> used to determine if it satisfies the
/// requirements for this <see cref="ImportDefinition"/>.
/// </param>
/// <returns>
/// <see langword="True"/> if the <see cref="Export"/> satisfies the requirements for
/// this <see cref="ImportDefinition"/>, otherwise returns <see langword="False"/>.
/// </returns>
/// <remarks>
/// <note type="inheritinfo">
/// Overrides of this method can provide a more optimized execution of the
/// <see cref="Constraint"/> property but the result should remain consistent.
/// </note>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="exportDefinition"/> is <see langword="null"/>.
/// </exception>
public virtual bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition)
{
Requires.NotNull(exportDefinition, nameof(exportDefinition));
if (_compiledConstraint == null)
{
_compiledConstraint = Constraint.Compile();
}
return _compiledConstraint.Invoke(exportDefinition);
}
/// <summary>
/// Returns a string representation of the import definition.
/// </summary>
/// <returns>
/// A <see cref="String"/> containing the value of the <see cref="Constraint"/> property.
/// </returns>
public override string ToString()
{
return Constraint.Body.ToString();
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2007 Roger Hill
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;
namespace DAL.Standard
{
public sealed class Database : IDatabase
{
private const string EMPTY_QUERY_STRING = "Query string is null or empty";
private const string EMPTY_CONNECTION_STRING = "Connection string is null or empty";
private const string NULL_PROCESSOR_METHOD = "Processor method is null";
private const string DEFAULT_CONNECTION_STRING = "Data Source=Localhost;Initial Catalog=Master;Integrated Security=SSPI;Connect Timeout=1;";
private const string EXCEPTION_SQL_PREFIX = "Sql.Parameter";
private const string EXCEPTION_KEY_QUERY = "Sql.Query";
private const string EXCEPTION_KEY_CONNECTION = "Sql.ConnectionString";
private readonly string _Connection;
private readonly bool _LogConnection;
private readonly bool _LogParameters;
private readonly bool _ThrowUnmappedFieldsError;
public Database() : this(DEFAULT_CONNECTION_STRING) { }
/// <summary>
/// CTOR for Database object
/// </summary>
/// <param name="connection">A sql connection string.</param>
/// <param name="logConnection">Allow connection string to be included in thrown exceptions. Defaults to false.</param>
/// <param name="logParameters">Allow query parameters to be included in thrown exceptions. Defaults to false.</param>
public Database(string connection, bool logConnection = false, bool logParameters = false, bool throwUnmappedFieldsError = true)
{
if (string.IsNullOrWhiteSpace(connection))
throw new ArgumentNullException(EMPTY_CONNECTION_STRING);
_Connection = connection;
_LogConnection = logConnection;
_LogParameters = logParameters;
_ThrowUnmappedFieldsError = throwUnmappedFieldsError;
}
public DataTable ExecuteQuery(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteQuery(sqlQuery, parameters, _Connection, false);
}
public DataTable ExecuteQuerySp(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteQuery(sqlQuery, parameters, _Connection, true);
}
public List<T> ExecuteQuery<T>(string sqlQuery, IList<SqlParameter> parameters) where T : class, new()
{
return ExecuteQuery<T>(sqlQuery, parameters, _Connection, false);
}
public T ExecuteQuery<T>(string sqlQuery, IList<SqlParameter> parameters, Func<SqlDataReader, T> processor)
{
return ExecuteQuery<T>(sqlQuery, parameters, _Connection, false, processor);
}
public List<T> ExecuteQuerySp<T>(string sqlQuery, IList<SqlParameter> parameters) where T : class, new()
{
return ExecuteQuery<T>(sqlQuery, parameters, _Connection, true);
}
public T ExecuteQuerySp<T>(string sqlQuery, IList<SqlParameter> parameters, Func<SqlDataReader, T> processor)
{
return ExecuteQuery<T>(sqlQuery, parameters, _Connection, true, processor);
}
public int ExecuteNonQuery(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteNonQuery(sqlQuery, parameters, _Connection, false);
}
public int ExecuteNonQuerySp(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteNonQuery(sqlQuery, parameters, _Connection, true);
}
public T ExecuteScalar<T>(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteScalar<T>(sqlQuery, parameters, _Connection, false);
}
public T ExecuteScalarSp<T>(string sqlQuery, IList<SqlParameter> parameters)
{
return ExecuteScalar<T>(sqlQuery, parameters, _Connection, true);
}
public DataTable GetSchema()
{
using (SqlConnection conn = new SqlConnection(_Connection))
{
DataTable dt = null;
conn.Open();
dt = conn.GetSchema("Databases");
conn.Close();
return dt;
}
}
private DataTable ExecuteQuery(string sqlQuery, IList<SqlParameter> parameters, string connection, bool storedProcedure)
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
try
{
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
cmd.CommandType = (storedProcedure) ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
cmd.Parameters.Add(parameter);
}
#if (DEBUG)
string SqlDebugString = GenerateSqlDebugString(sqlQuery, parameters);
#endif
var dt = new DataTable();
conn.Open();
adapter.SelectCommand = cmd;
adapter.Fill(dt);
conn.Close();
if (parameters != null)
{
for (int i = 0; i < cmd.Parameters.Count; i++)
parameters[i].Value = cmd.Parameters[i].Value;
}
return dt;
}
}
}
}
catch (Exception ex)
{
ex.Data.Add(EXCEPTION_KEY_QUERY, sqlQuery);
if (_LogConnection)
ex.Data.Add(EXCEPTION_KEY_CONNECTION, connection);
if (_LogParameters && parameters != null)
{
for (int i = 0; i < parameters.Count; i++)
ex.Data.Add($"{EXCEPTION_SQL_PREFIX}{i + 1}", $"{parameters[i].ParameterName} = {parameters[i].Value}");
}
throw ex;
}
}
private List<T> ExecuteQuery<T>(string sqlQuery, IList<SqlParameter> parameters, string connection, bool storedProcedure) where T : class, new()
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
try
{
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
cmd.CommandType = (storedProcedure) ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
cmd.Parameters.Add(parameter);
}
#if (DEBUG)
string SqlDebugString = GenerateSqlDebugString(sqlQuery, parameters);
#endif
conn.Open();
using (SqlDataReader data_reader = cmd.ExecuteReader())
{
var output = ParseDatareaderResult<T>(data_reader, _ThrowUnmappedFieldsError);
if (parameters != null)
{
for (int i = 0; i < cmd.Parameters.Count; i++)
parameters[i].Value = cmd.Parameters[i].Value;
}
data_reader.Close();
conn.Close();
return output;
}
}
}
}
catch (Exception ex)
{
ex.Data.Add(EXCEPTION_KEY_QUERY, sqlQuery);
if (_LogConnection)
ex.Data.Add(EXCEPTION_KEY_CONNECTION, connection);
if (_LogParameters && parameters != null)
{
for (int i = 0; i < parameters.Count; i++)
ex.Data.Add($"{EXCEPTION_SQL_PREFIX}{i + 1}", $"{parameters[i].ParameterName} = {parameters[i].Value}");
}
throw ex;
}
}
private T ExecuteQuery<T>(string sqlQuery, IList<SqlParameter> parameters, string connection, bool storedProcedure, Func<SqlDataReader, T> processor)
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
if (processor == null)
throw new ArgumentNullException(NULL_PROCESSOR_METHOD);
try
{
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
cmd.CommandType = (storedProcedure) ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
cmd.Parameters.Add(parameter);
}
#if (DEBUG)
string SqlDebugString = GenerateSqlDebugString(sqlQuery, parameters);
#endif
conn.Open();
using (SqlDataReader data_reader = cmd.ExecuteReader())
{
var output = processor.Invoke(data_reader);
if (parameters != null)
{
for (int i = 0; i < cmd.Parameters.Count; i++)
parameters[i].Value = cmd.Parameters[i].Value;
}
data_reader.Close();
conn.Close();
return output;
}
}
}
}
catch (Exception ex)
{
ex.Data.Add(EXCEPTION_KEY_QUERY, sqlQuery);
if (_LogConnection)
ex.Data.Add(EXCEPTION_KEY_CONNECTION, connection);
if (_LogParameters && parameters != null)
{
for (int i = 0; i < parameters.Count; i++)
ex.Data.Add($"{EXCEPTION_SQL_PREFIX}{i + 1}", $"{parameters[i].ParameterName} = {parameters[i].Value}");
}
throw ex;
}
}
private int ExecuteNonQuery(string sqlQuery, IList<SqlParameter> parameters, string connection, bool storedProcedure)
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
if (string.IsNullOrWhiteSpace(connection))
throw new ArgumentNullException(EMPTY_CONNECTION_STRING);
try
{
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
cmd.CommandType = (storedProcedure) ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
cmd.Parameters.Add(parameter);
}
#if (DEBUG)
string SqlDebugString = GenerateSqlDebugString(sqlQuery, parameters);
#endif
conn.Open();
int results = cmd.ExecuteNonQuery();
conn.Close();
if (parameters != null)
{
for (int i = 0; i < cmd.Parameters.Count; i++)
parameters[i].Value = cmd.Parameters[i].Value;
}
return results;
}
}
}
catch (Exception ex)
{
ex.Data.Add(EXCEPTION_KEY_QUERY, sqlQuery);
if (_LogConnection)
ex.Data.Add(EXCEPTION_KEY_CONNECTION, connection);
if (_LogParameters && parameters != null)
{
for (int i = 0; i < parameters.Count; i++)
ex.Data.Add($"{EXCEPTION_SQL_PREFIX}{i + 1}", $"{parameters[i].ParameterName} = {parameters[i].Value}");
}
throw ex;
}
}
private T ExecuteScalar<T>(string sqlQuery, IList<SqlParameter> parameters, string connection, bool storedProcedure)
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
try
{
using (var conn = new SqlConnection(connection))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
T results = default;
cmd.CommandType = (storedProcedure) ? CommandType.StoredProcedure : CommandType.Text;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
cmd.Parameters.Add(parameter);
}
#if (DEBUG)
string SqlDebugString = GenerateSqlDebugString(sqlQuery, parameters);
#endif
conn.Open();
object buffer = cmd.ExecuteScalar();
if (buffer == null)
{
results = default;
}
else
{
if (buffer.GetType() == typeof(DBNull))
results = default;
else if (buffer is T t)
return t;
else
return (T)Convert.ChangeType(buffer, typeof(T));
}
conn.Close();
if (parameters != null)
{
for (int i = 0; i < cmd.Parameters.Count; i++)
parameters[i].Value = cmd.Parameters[i].Value;
}
return results;
}
}
}
catch (Exception ex)
{
ex.Data.Add(EXCEPTION_KEY_QUERY, sqlQuery);
if (_LogConnection)
ex.Data.Add(EXCEPTION_KEY_CONNECTION, connection);
if (_LogParameters && parameters != null)
{
for (int i = 0; i < parameters.Count; i++)
ex.Data.Add($"{EXCEPTION_SQL_PREFIX}{i + 1}", $"{parameters[i].ParameterName} = {parameters[i].Value}");
}
throw ex;
}
}
/// <summary>
/// Converts a list of IEnumerable objects to a string of comma delimited items. If a quote_character
/// is defined, this will wrap each item with the character(s) passed.
/// </summary>
public static string GenericListToStringList<T>(IEnumerable<T> list, string quoteCharacter = null, string quoteEscapeCharacter = null)
{
if (list == null)
throw new ArgumentNullException("Cannot convert a null IEnumerable object");
var sb = new StringBuilder();
bool firstFlag = true;
foreach (T item in list)
{
if (firstFlag)
firstFlag = false;
else
sb.Append(",");
if (item == null)
{
sb.Append("null");
}
else
{
string buffer = item.ToString();
if (!string.IsNullOrWhiteSpace(quoteEscapeCharacter))
buffer = buffer.Replace(quoteCharacter, quoteEscapeCharacter);
if (!string.IsNullOrWhiteSpace(quoteCharacter))
sb.Append(quoteCharacter + buffer + quoteCharacter);
else
sb.Append(buffer);
}
}
return sb.ToString();
}
/// <summary>
/// Method creates sql debugging strings with parameterized argument lists
/// </summary>
private string GenerateSqlDebugString(string sqlQuery, IList<SqlParameter> parameterList)
{
if (string.IsNullOrWhiteSpace(sqlQuery))
throw new ArgumentNullException(EMPTY_QUERY_STRING);
if (parameterList == null || parameterList.Count == 0)
return sqlQuery;
var value_list = new List<string>();
foreach (var item in parameterList)
{
if (item.Direction == ParameterDirection.ReturnValue)
continue;
if (item.IsNullable)
{
value_list.Add($"{item.ParameterName} = null");
}
else
{
switch (item.SqlDbType)
{
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.Text:
case SqlDbType.NText:
case SqlDbType.NVarChar:
case SqlDbType.VarChar:
case SqlDbType.UniqueIdentifier:
case SqlDbType.DateTime:
case SqlDbType.Date:
case SqlDbType.Time:
case SqlDbType.DateTime2:
value_list.Add($"{item.ParameterName} = '{item.Value}'");
break;
default:
value_list.Add($"{item.ParameterName} = {item.Value}");
break;
}
}
}
return $"{sqlQuery} {GenericListToStringList(value_list, null, null)}";
}
/// <summary>
/// This method performs automatic mapping between a data reader and a POCO object, mapping any values that
/// have properties names that match column names. It can be configured to throw exceptions if there isn't a 1:1 mapping.
/// </summary>
/// <returns></returns>
private List<T> ParseDatareaderResult<T>(SqlDataReader reader, bool throwUnmappedFieldsError) where T : class, new()
{
var outputType = typeof(T);
var results = new List<T>();
var propertyLookup = new Dictionary<string, PropertyInfo>();
foreach (var propertyInfo in outputType.GetProperties())
propertyLookup.Add(propertyInfo.Name, propertyInfo);
T new_object;
object fieldValue;
while (reader.Read())
{
new_object = new T();
for (int i = 0; i < reader.FieldCount; i++)
{
string columnName = reader.GetName(i);
if (propertyLookup.TryGetValue(columnName, out PropertyInfo propertyInfo))
{
Type propertyType = propertyInfo.PropertyType;
string propertyName = propertyInfo.PropertyType.FullName;
// in the event that we are looking at a nullable type, we need to look at the underlying type.
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyName = Nullable.GetUnderlyingType(propertyType).ToString();
propertyType = Nullable.GetUnderlyingType(propertyType);
}
switch (propertyName)
{
case "System.Int32":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as int? ?? null;
else
fieldValue = (int)reader[columnName];
break;
case "System.String":
if (reader[i] == DBNull.Value)
fieldValue = null;
else
fieldValue = (string)reader[columnName];
break;
case "System.Double":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as double? ?? null;
else
fieldValue = (double)reader[columnName];
break;
case "System.Float":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as float? ?? null;
else
fieldValue = (float)reader[columnName];
break;
case "System.Boolean":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as bool? ?? null;
else
fieldValue = (bool)reader[columnName];
break;
case "System.Boolean[]":
if (reader[i] == DBNull.Value)
{
fieldValue = null;
}
else
{
// inline conversion, blech. improve later.
var byteArray = (byte[])reader[i];
var boolArray = new bool[byteArray.Length];
for (int index = 0; index < byteArray.Length; index++)
boolArray[index] = Convert.ToBoolean(byteArray[index]);
fieldValue = boolArray;
}
break;
case "System.DateTime":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as DateTime? ?? null;
else
fieldValue = DateTime.Parse(reader[columnName].ToString());
break;
case "System.Guid":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as Guid? ?? null;
else
fieldValue = (Guid)reader[columnName];
break;
case "System.Single":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as float? ?? null;
else
fieldValue = float.Parse(reader[columnName].ToString());
break;
case "System.Decimal":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as decimal? ?? null;
else
fieldValue = (decimal)reader[columnName];
break;
case "System.Byte":
if (reader[i] == DBNull.Value)
fieldValue = null;
else
fieldValue = (byte)reader[columnName];
break;
case "System.Byte[]":
if (reader[i] == DBNull.Value)
{
fieldValue = null;
}
else
{
string byteArray = reader[columnName].ToString();
byte[] bytes = new byte[byteArray.Length * sizeof(char)];
Buffer.BlockCopy(byteArray.ToCharArray(), 0, bytes, 0, bytes.Length);
fieldValue = bytes;
}
break;
case "System.SByte":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as sbyte? ?? null;
else
fieldValue = (sbyte)reader[columnName];
break;
case "System.Char":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as char? ?? null;
else
fieldValue = (char)reader[columnName];
break;
case "System.UInt32":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as uint? ?? null;
else
fieldValue = (uint)reader[columnName];
break;
case "System.Int64":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as long? ?? null;
else
fieldValue = (long)reader[columnName];
break;
case "System.UInt64":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as ulong? ?? null;
else
fieldValue = (ulong)reader[columnName];
break;
case "System.Object":
if (reader[i] == DBNull.Value)
fieldValue = null;
else
fieldValue = reader[columnName];
break;
case "System.Int16":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as short? ?? null;
else
fieldValue = (short)reader[columnName];
break;
case "System.UInt16":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as ushort? ?? null;
else
fieldValue = (ushort)reader[columnName];
break;
case "System.Udt":
// no idea how to handle a custom type
throw new NotImplementedException("System.Udt is an unsupported datatype");
case "Microsoft.SqlServer.Types.SqlGeometry":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as Microsoft.SqlServer.Types.SqlGeometry ?? null;
else
fieldValue = (Microsoft.SqlServer.Types.SqlGeometry)reader[columnName];
break;
case "Microsoft.SqlServer.Types.SqlGeography":
if (reader[i] == DBNull.Value)
fieldValue = reader[columnName] as Microsoft.SqlServer.Types.SqlGeography ?? null;
else
fieldValue = (Microsoft.SqlServer.Types.SqlGeography)reader[columnName];
break;
default:
if (propertyType.IsEnum)
{
// enums are common, but don't fit into the above buckets.
if (reader[i] == DBNull.Value)
fieldValue = null;
else
fieldValue = Enum.ToObject(propertyType, reader[columnName]);
break;
}
else
{
throw new Exception($"Column '{propertyLookup[columnName]}' has an unknown data type: '{propertyLookup[columnName].PropertyType.FullName}'.");
}
}
propertyLookup[columnName].SetValue(new_object, fieldValue, null);
}
else
{
// found a row in data reader that cannot be mapped to a property in object.
// might be an error, but it is dependent on the specific use case.
if (throwUnmappedFieldsError)
{
throw new Exception($"Cannot map datareader field '{columnName}' to object property on object '{outputType}'");
}
}
}
results.Add(new_object);
}
return results;
}
private DataTable ConvertObjectToDataTable<T>(IEnumerable<T> input)
{
var dt = new DataTable();
var outputType = typeof(T);
var object_properties = outputType.GetProperties();
foreach (var propertyInfo in object_properties)
dt.Columns.Add(propertyInfo.Name);
foreach (var item in input)
{
var dr = dt.NewRow();
foreach (var property in object_properties)
dr[property.Name] = outputType.GetProperty(property.Name).GetValue(item, null);
dt.Rows.Add(dr);
}
return dt;
}
/// <summary>
/// Generates a SqlParameter object from a generic object list. This allows you to pass in a list of N
/// objects into a stored procedure as a single argument. The sqlTypeName type needs to exist in the db
/// however, and be of the correct type.
///
/// Sample: ConvertObjectCollectionToParameter("@Foo", "dbo.SomeUserType", a_generic_object_collection);
/// </summary>
public SqlParameter ConvertObjectCollectionToParameter<T>(string parameterName, string sqlTypeName, IEnumerable<T> input)
{
DataTable dt = ConvertObjectToDataTable(input);
var sql_parameter = new SqlParameter(parameterName, dt)
{
SqlDbType = SqlDbType.Structured,
TypeName = sqlTypeName
};
return sql_parameter;
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Reflection;
using csUnit;
using csUnit.Core;
using csUnit.Interfaces;
using Gallio.Common.Collections;
using Gallio.CSUnitAdapter.Properties;
using Gallio.Model;
using Gallio.Common.Reflection;
using Gallio.Model.Helpers;
using Gallio.Model.Tree;
using System.IO;
namespace Gallio.CSUnitAdapter.Model
{
internal class CSUnitTestExplorer : TestExplorer
{
internal const string AssemblyKind = "csUnit Assembly";
private const string CSUnitAssemblyDisplayName = @"csUnit";
private readonly Dictionary<IAssemblyInfo, Test> assemblyTests;
public CSUnitTestExplorer()
{
assemblyTests = new Dictionary<IAssemblyInfo, Test>();
}
protected override void ExploreImpl(IReflectionPolicy reflectionPolicy, ICodeElementInfo codeElement)
{
IAssemblyInfo assembly = ReflectionUtils.GetAssembly(codeElement);
if (assembly != null)
{
Version frameworkVersion = GetFrameworkVersion(assembly);
if (frameworkVersion != null)
{
GetAssemblyTest(assembly, TestModel.RootTest, frameworkVersion);
}
}
}
private static Version GetFrameworkVersion(IAssemblyInfo assembly)
{
if (assembly != null)
{
AssemblyName frameworkAssemblyName = ReflectionUtils.FindAssemblyReference(assembly, CSUnitAssemblyDisplayName);
if (frameworkAssemblyName != null)
{
return frameworkAssemblyName.Version;
}
}
return null;
}
private Test GetAssemblyTest(IAssemblyInfo assembly, Test parentTest, Version frameworkVersion)
{
Test assemblyTest;
if (assemblyTests.TryGetValue(assembly, out assemblyTest))
return assemblyTest;
try
{
Assembly loadedAssembly = assembly.Resolve(false);
if (Reflector.IsUnresolved(loadedAssembly))
assemblyTest = BuildAssemblyTest_Reflective(assembly);
else
assemblyTest = BuildAssemblyTest_Native(assembly, loadedAssembly.Location);
string frameworkName = String.Format(Resources.CSUnitTestExplorer_FrameworkNameWithVersionFormat, frameworkVersion);
assemblyTest.Metadata.SetValue(MetadataKeys.Framework, frameworkName);
assemblyTest.Metadata.SetValue(MetadataKeys.File, assembly.Path);
assemblyTest.Kind = AssemblyKind;
}
catch (Exception ex)
{
TestModel.AddAnnotation(new Annotation(AnnotationType.Error, assembly,
"An exception was thrown while exploring a csUnit test assembly.", ex));
return null;
}
if (assemblyTest != null)
{
parentTest.AddChild(assemblyTest);
assemblyTests.Add(assembly, assemblyTest);
}
return assemblyTest;
}
private Test BuildAssemblyTest_Native(IAssemblyInfo assembly, string location)
{
if (String.IsNullOrEmpty(location))
throw new ArgumentNullException("location");
// If csUnit.Core is not in the GAC then it must be in the assembly path due to a
// bug in csUnit setting up the AppDomain. It sets the AppDomain's base directory
// to the assembly directory and sets its PrivateBinPath to the csUnit directory
// which is incorrect (PrivateBinPath only specifies directories relative to the app base)
// so it does actually not ensure that csUnit.Core can be loaded as desired.
Assembly csUnitCoreAssembly = typeof(csUnit.Core.Loader).Assembly;
if (!csUnitCoreAssembly.GlobalAssemblyCache)
{
string csUnitAppBase = Path.GetDirectoryName(location);
string csUnitCoreAssemblyPathExpected = Path.Combine(csUnitAppBase, "csUnit.Core.dll");
if (!File.Exists(csUnitCoreAssemblyPathExpected))
{
return CreateAssemblyTest(assembly, location, delegate(Test assemblyTest)
{
TestModel.AddAnnotation(new Annotation(AnnotationType.Error, null,
string.Format("Cannot load csUnit tests from '{0}'. "
+ "'csUnit.Core.dll' and related DLLs must either be copied to the same directory as the test assembly or must be installed in the GAC.",
location)));
});
}
}
// Load the assembly using the native CSUnit loader.
using (Loader loader = new Loader(location))
{
// Construct the test tree
return CreateAssemblyTest(assembly, location, delegate(Test assemblyTest)
{
TestFixtureInfoCollection collection = loader.TestFixtureInfos;
if (collection == null)
return;
foreach (ITestFixtureInfo fixtureInfo in collection)
{
try
{
ITypeInfo fixtureType = assembly.GetType(fixtureInfo.FullName);
assemblyTest.AddChild(CreateFixtureFromType(fixtureType, delegate(Test fixtureTest)
{
if (fixtureInfo.TestMethods == null)
return;
foreach (ITestMethodInfo testMethodInfo in fixtureInfo.TestMethods)
{
try
{
IMethodInfo methodType = fixtureType.GetMethod(testMethodInfo.Name,
BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
fixtureTest.AddChild(CreateTestFromMethod(methodType, null));
}
catch (Exception ex)
{
TestModel.AddAnnotation(new Annotation(AnnotationType.Error, fixtureType,
"An exception was thrown while exploring a csUnit test case.", ex));
}
}
}));
}
catch (Exception ex)
{
TestModel.AddAnnotation(new Annotation(AnnotationType.Error, assembly,
"An exception was thrown while exploring a csUnit test fixture.", ex));
}
}
});
}
}
private Test BuildAssemblyTest_Reflective(IAssemblyInfo assembly)
{
// Construct the test tree
return CreateAssemblyTest(assembly, String.Empty, delegate(Test assemblyTest)
{
foreach (ITypeInfo fixtureType in assembly.GetExportedTypes())
{
if (!IsTestFixture(fixtureType))
continue;
assemblyTest.AddChild(CreateFixtureFromType(fixtureType, delegate(Test fixtureTest)
{
foreach (IMethodInfo methodType in fixtureType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
{
if (!IsTestCase(methodType))
continue;
fixtureTest.AddChild(CreateTestFromMethod(methodType, null));
}
}));
}
});
}
private static bool IsTestFixture(ITypeInfo fixture)
{
if (fixture.IsAbstract)
return false;
if (AttributeUtils.HasAttribute<TestFixtureAttribute>(fixture, true))
return true;
if (fixture.Name.EndsWith("Test"))
return true;
return false;
}
private static bool IsTestCase(IMethodInfo method)
{
if (method.ReturnType.FullName != "System.Void")
return false;
//if (method.IsGenericMethod)
// return false;
if (AttributeUtils.HasAttribute<FixtureSetUpAttribute>(method, true) ||
AttributeUtils.HasAttribute<FixtureTearDownAttribute>(method, true))
return false;
if (AttributeUtils.HasAttribute<SetUpAttribute>(method, true) ||
AttributeUtils.HasAttribute<TearDownAttribute>(method, true))
return false;
if (method.Name.ToLower().Equals("setup") ||
method.Name.ToLower().Equals("teardown"))
return false;
if (AttributeUtils.HasAttribute<TestAttribute>(method, true))
return true;
if (method.Parameters.Count > 0)
return false; // Parameterized tests must have an attribute
if (method.Name.ToLower().StartsWith("test"))
return true;
return false;
}
private static Test CreateAssemblyTest(IAssemblyInfo assembly, string assemblyLocation, Action<Test> consumer)
{
CSUnitAssemblyTest assemblyTest = new CSUnitAssemblyTest(assembly, assemblyLocation);
assemblyTest.LocalIdHint = assembly.Name; // used to do reverse lookup
assemblyTest.Kind = TestKinds.Assembly;
PopulateAssemblyMetadata(assembly, assemblyTest.Metadata);
if (consumer != null)
consumer(assemblyTest);
return assemblyTest;
}
private static Test CreateFixtureFromType(ITypeInfo fixtureType, Action<Test> consumer)
{
CSUnitTest fixtureTest = new CSUnitTest(fixtureType.Name, fixtureType);
fixtureTest.LocalIdHint = fixtureType.FullName; // used to do reverse lookup
fixtureTest.Kind = TestKinds.Fixture;
PopulateFixtureMetadata(fixtureType, fixtureTest.Metadata);
if (consumer != null)
consumer(fixtureTest);
return fixtureTest;
}
private static Test CreateTestFromMethod(IMethodInfo methodType, Action<Test> consumer)
{
CSUnitTest method = new CSUnitTest(methodType.Name, methodType);
method.LocalIdHint = methodType.DeclaringType.FullName + @"." + methodType.Name; // used to do reverse lookup
method.Kind = TestKinds.Test;
method.IsTestCase = true;
PopulateMethodMetadata(methodType, method.Metadata);
if (consumer != null)
consumer(method);
return method;
}
#region Populate Metadata methods
private static void PopulateAssemblyMetadata(IAssemblyInfo codeElement, PropertyBag metadata)
{
ModelUtils.PopulateMetadataFromAssembly(codeElement, metadata);
// Add documentation.
string xmlDocumentation = codeElement.GetXmlDocumentation();
if (!String.IsNullOrEmpty(xmlDocumentation))
{
metadata.Add(MetadataKeys.XmlDocumentation, xmlDocumentation);
}
}
private static void PopulateFixtureMetadata(ICodeElementInfo codeElement, PropertyBag metadata)
{
foreach (TestFixtureAttribute attr in AttributeUtils.GetAttributes<TestFixtureAttribute>(codeElement, true))
{
// Add categories
string categories = attr.Categories;
if (!String.IsNullOrEmpty(categories))
{
foreach (string category in categories.Split(','))
{
metadata.Add(MetadataKeys.Category, category);
}
}
}
PopulateCommonMetadata(codeElement, metadata);
}
private static void PopulateMethodMetadata(ICodeElementInfo codeElement, PropertyBag metadata)
{
foreach (TestAttribute attr in AttributeUtils.GetAttributes<TestAttribute>(codeElement, true))
{
// Add timeout
if (attr.Timeout > 0)
{
TimeSpan timeout = TimeSpan.FromMilliseconds(attr.Timeout);
metadata.Add("Timeout", timeout.Seconds.ToString("0.000"));
}
// Add categories
string categories = attr.Categories;
if (!String.IsNullOrEmpty(categories))
{
foreach (string category in categories.Split(','))
{
metadata.Add(MetadataKeys.Category, category);
}
}
}
// Add expected exception type
foreach (ExpectedExceptionAttribute attr in AttributeUtils.GetAttributes<ExpectedExceptionAttribute>(codeElement, true))
{
metadata.Add(MetadataKeys.ExpectedException, attr.ExceptionType.FullName);
}
PopulateCommonMetadata(codeElement, metadata);
}
private static void PopulateCommonMetadata(ICodeElementInfo codeElement, PropertyBag metadata)
{
// Add ignore reason.
foreach (IgnoreAttribute attr in AttributeUtils.GetAttributes<IgnoreAttribute>(codeElement, true))
{
metadata.Add(MetadataKeys.IgnoreReason, attr.Reason ?? "<unknown>");
}
// Add documentation.
string xmlDocumentation = codeElement.GetXmlDocumentation();
if (!String.IsNullOrEmpty(xmlDocumentation))
{
metadata.Add(MetadataKeys.XmlDocumentation, xmlDocumentation);
}
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System.Reflection
{
// Summary:
// Provides information about methods and constructors.
[Immutable] // Base class is immutable.
public abstract class MethodBase
{
// Summary:
// Initializes a new instance of the System.Reflection.MethodBase class.
#if SILVERLIGHT && !SILVERLIGHT_5_0
extern internal MethodBase();
#else
extern protected MethodBase();
#endif
// Summary:
// Gets the attributes associated with this method.
//
// Returns:
// One of the System.Reflection.MethodAttributes values.
//public abstract MethodAttributes Attributes { get; }
//
// Summary:
// Gets a value indicating the calling conventions for this method.
//
// Returns:
// The System.Reflection.CallingConventions for this method.
//extern public virtual CallingConventions CallingConvention { get; }
//
// Summary:
// Gets a value indicating whether the generic method contains unassigned generic
// type parameters.
//
// Returns:
// true if the current System.Reflection.MethodBase object represents a generic
// method that contains unassigned generic type parameters; otherwise, false.
extern public virtual bool ContainsGenericParameters { get; }
//
// Summary:
// Gets a value indicating whether the method is abstract.
//
// Returns:
// true if the method is abstract; otherwise, false.
#if !SILVERLIGHT
public abstract bool IsAbstract { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsAbstract { get; }
#else
public extern bool IsAbstract { get; }
#endif
//
// Summary:
// Gets a value indicating whether this method can be called by other classes
// in the same assembly.
//
// Returns:
// true if this method can be called by other classes in the same assembly;
// otherwise, false.
#if !SILVERLIGHT
public abstract bool IsAssembly { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsAssembly { get; }
#else
public extern bool IsAssembly { get; }
#endif
//
// Summary:
// Gets a value indicating whether the method is a constructor.
//
// Returns:
// true if this method is a constructor represented by a System.Reflection.ConstructorInfo
// object (see note in Remarks about System.Reflection.Emit.ConstructorBuilder
// objects); otherwise, false.
#if !SILVERLIGHT
public abstract bool IsConstructor { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsConstructor { get; }
#else
public extern bool IsConstructor { get; }
#endif
//
// Summary:
// Gets a value indicating whether access to this method is restricted to members
// of the class and members of its derived classes.
//
// Returns:
// true if access to the class is restricted to members of the class itself
// and to members of its derived classes; otherwise, false.
#if !SILVERLIGHT
public abstract bool IsFamily { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsFamily { get; }
#else
public extern bool IsFamily { get; }
#endif
//
// Summary:
// Gets a value indicating whether this method can be called by derived classes
// if they are in the same assembly.
//
// Returns:
// true if access to this method is restricted to members of the class itself
// and to members of derived classes that are in the same assembly; otherwise,
// false.
#if !SILVERLIGHT
public abstract bool IsFamilyAndAssembly { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsFamilyAndAssembly { get; }
#else
public extern bool IsFamilyAndAssembly { get; }
#endif
//
// Summary:
// Gets a value indicating whether this method can be called by derived classes,
// wherever they are, and by all classes in the same assembly.
//
// Returns:
// true if access to this method is restricted to members of the class itself,
// members of derived classes wherever they are, and members of other classes
// in the same assembly; otherwise, false.
#if !SILVERLIGHT
public abstract bool IsFamilyOrAssembly { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsFamilyOrAssembly { get; }
#else
public extern bool IsFamilyOrAssembly { get; }
#endif
//
// Summary:
// Gets a value indicating whether this method is final.
//
// Returns:
// true if this method is final; otherwise, false.
#if !SILVERLIGHT
public abstract bool IsFinal { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsFinal { get; }
#else
public extern bool IsFinal { get; }
#endif
//
// Summary:
// Gets a value indicating whether the method is generic.
//
// Returns:
// true if the current System.Reflection.MethodBase represents a generic method;
// otherwise, false.
public abstract bool IsGenericMethod { get; }
//
// Summary:
// Gets a value indicating whether the method is a generic method definition.
//
// Returns:
// true if the current System.Reflection.MethodBase object represents the definition
// of a generic method; otherwise, false.
public abstract bool IsGenericMethodDefinition { get; }
//
// Summary:
// Gets a value indicating whether only a member of the same kind with exactly
// the same signature is hidden in the derived class.
//
// Returns:
// true if the member is hidden by signature; otherwise, false.
#if !SILVERLIGHT
public abstract bool IsHideBySig { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsHideBySig { get; }
#else
public extern bool IsHideBySig { get; }
#endif
//
// Summary:
// Gets a value indicating whether this member is private.
//
// Returns:
// true if access to this method is restricted to other members of the class
// itself; otherwise, false.
#if !SILVERLIGHT
public abstract bool IsPrivate { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsPrivate { get; }
#else
public extern bool IsPrivate { get; }
#endif
//
// Summary:
// Gets a value indicating whether this is a public method.
//
// Returns:
// true if this method is public; otherwise, false.
#if !SILVERLIGHT
public abstract bool IsPublic { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsPublic { get; }
#else
public extern bool IsPublic { get; }
#endif
//
// Summary:
// Gets a value indicating whether this method has a special name.
//
// Returns:
// true if this method has a special name; otherwise, false.
#if !SILVERLIGHT
public abstract bool IsSpecialName { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsSpecialName { get; }
#else
public extern bool IsSpecialName { get; }
#endif
//
// Summary:
// Gets a value indicating whether the method is static.
//
// Returns:
// true if this method is static; otherwise, false.
#if !SILVERLIGHT
public abstract bool IsStatic { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsStatic { get; }
#else
public extern bool IsStatic { get; }
#endif
//
// Summary:
// Gets a value indicating whether the method is virtual.
//
// Returns:
// true if this method is virtual; otherwise, false.
#if !SILVERLIGHT
public abstract bool IsVirtual { get; }
#elif SILVERLIGHT_4_0_WP || SILVERLIGHT_5_0
public extern virtual bool IsVirtual { get; }
#else
public extern bool IsVirtual { get; }
#endif
//
// Summary:
// Gets a handle to the internal metadata representation of a method.
//
// Returns:
// A System.RuntimeMethodHandle object.
//public abstract RuntimeMethodHandle MethodHandle { get; }
// Summary:
// Returns a MethodBase object representing the currently executing method.
//
// Returns:
// A MethodBase object representing the currently executing method.
[Pure]
public static MethodBase GetCurrentMethod()
{
Contract.Ensures(Contract.Result<MethodBase>() != null);
return default(MethodBase);
}
//
// Summary:
// Returns an array of System.Type objects that represent the type arguments
// of a generic method or the type parameters of a generic method definition.
//
// Returns:
// An array of System.Type objects that represent the type arguments of a generic
// method or the type parameters of a generic method definition. Returns an
// empty array if the current method is not a generic method.
//
// Exceptions:
// System.NotSupportedException:
// The current object is a System.Reflection.ConstructorInfo. Generic constructors
// are not supported in the .NET Framework version 2.0. This exception is the
// default behavior if this method is not overridden in a derived class.
[Pure]
public virtual Type[] GetGenericArguments()
{
Contract.Ensures(Contract.Result<Type[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<Type[]>(), type => type != null));
return default(Type[]);
}
//
// Summary:
// When overridden in a derived class, gets a System.Reflection.MethodBody object
// that provides access to the MSIL stream, local variables, and exceptions
// for the current method.
//
// Returns:
// A System.Reflection.MethodBody object that provides access to the MSIL stream,
// local variables, and exceptions for the current method.
//
// Exceptions:
// System.InvalidOperationException:
// This method is invalid unless overridden in a derived class.
#if !SILVERLIGHT
[Pure]
public virtual MethodBody GetMethodBody()
{
Contract.Ensures(Contract.Result<MethodBody>() != null);
return null;
}
#endif
// Summary:
// Gets method information by using the method's internal metadata representation
// (handle).
//
// Parameters:
// handle:
// The method's handle.
//
// Returns:
// A MethodBase containing information about the method.
//
// Exceptions:
// System.ArgumentException:
// handle is invalid.
[Pure]
public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle)
{
Contract.Ensures(Contract.Result<MethodBase>() != null);
return default(MethodBase);
}
//
// Summary:
// Gets a System.Reflection.MethodBase object for the constructor or method
// represented by the specified handle, for the specified generic type.
//
// Parameters:
// declaringType:
// A handle to the generic type that defines the constructor or method.
//
// handle:
// A handle to the internal metadata representation of a constructor or method.
//
// Returns:
// A System.Reflection.MethodBase object representing the method or constructor
// specified by handle, in the generic type specified by declaringType.
//
// Exceptions:
// System.ArgumentException:
// handle is invalid.
[Pure]
public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType)
{
Contract.Ensures(Contract.Result<MethodBase>() != null);
return default(MethodBase);
}
//
// Summary:
// When overridden in a derived class, returns the System.Reflection.MethodImplAttributes
// flags.
//
// Returns:
// The MethodImplAttributes flags.
[Pure]
public virtual MethodImplAttributes GetMethodImplementationFlags()
{
return default(MethodImplAttributes);
}
//
// Summary:
// When overridden in a derived class, gets the parameters of the specified
// method or constructor.
//
// Returns:
// An array of type ParameterInfo containing information that matches the signature
// of the method (or constructor) reflected by this MethodBase instance.
[Pure]
public virtual ParameterInfo[] GetParameters()
{
Contract.Ensures(Contract.Result<ParameterInfo[]>() != null);
return default(ParameterInfo[]);
}
//
// Summary:
// Invokes the method or constructor represented by the current instance, using
// the specified parameters.
//
// Parameters:
// obj:
// The object on which to invoke the method or constructor. If a method is static,
// this argument is ignored. If a constructor is static, this argument must
// be null or an instance of the class that defines the constructor.
//
// parameters:
// An argument list for the invoked method or constructor. This is an array
// of objects with the same number, order, and type as the parameters of the
// method or constructor to be invoked. If there are no parameters, parameters
// should be null.If the method or constructor represented by this instance
// takes a ref parameter (ByRef in Visual Basic), no special attribute is required
// for that parameter in order to invoke the method or constructor using this
// function. Any object in this array that is not explicitly initialized with
// a value will contain the default value for that object type. For reference-type
// elements, this value is null. For value-type elements, this value is 0, 0.0,
// or false, depending on the specific element type.
//
// Returns:
// An object containing the return value of the invoked method, or null in the
// case of a constructor.
//
// Exceptions:
// System.MethodAccessException:
// The caller does not have permission to execute the constructor.
//
// System.InvalidOperationException:
// The type that declares the method is an open generic type. That is, the System.Type.ContainsGenericParameters
// property returns true for the declaring type.
//
// System.Reflection.TargetParameterCountException:
// The parameters array does not have the correct number of arguments.
//
// System.Reflection.TargetInvocationException:
// The invoked method or constructor throws an exception.
//
// System.ArgumentException:
// The elements of the parameters array do not match the signature of the method
// or constructor reflected by this instance.
//
// System.Reflection.TargetException:
// The obj parameter is null and the method is not static.-or- The method is
// not declared or inherited by the class of obj. -or-A static constructor is
// invoked, and obj is neither null nor an instance of the class that declared
// the constructor.
public abstract object Invoke(object obj, object[] parameters);
//
// Summary:
// When overridden in a derived class, invokes the reflected method or constructor
// with the given parameters.
//
// Parameters:
// culture:
// An instance of CultureInfo used to govern the coercion of types. If this
// is null, the CultureInfo for the current thread is used. (This is necessary
// to convert a String that represents 1000 to a Double value, for example,
// since 1000 is represented differently by different cultures.)
//
// obj:
// The object on which to invoke the method or constructor. If a method is static,
// this argument is ignored. If a constructor is static, this argument must
// be null or an instance of the class that defines the constructor.
//
// binder:
// An object that enables the binding, coercion of argument types, invocation
// of members, and retrieval of MemberInfo objects via reflection. If binder
// is null, the default binder is used.
//
// invokeAttr:
// A bitmask that is a combination of 0 or more bit flags from System.Reflection.BindingFlags.
// If binder is null, this parameter is assigned the value System.Reflection.BindingFlags.Default;
// thus, whatever you pass in is ignored.
//
// parameters:
// An argument list for the invoked method or constructor. This is an array
// of objects with the same number, order, and type as the parameters of the
// method or constructor to be invoked. If there are no parameters, this should
// be null.If the method or constructor represented by this instance takes a
// ByRef parameter, there is no special attribute required for that parameter
// in order to invoke the method or constructor using this function. Any object
// in this array that is not explicitly initialized with a value will contain
// the default value for that object type. For reference-type elements, this
// value is null. For value-type elements, this value is 0, 0.0, or false, depending
// on the specific element type.
//
// Returns:
// An Object containing the return value of the invoked method, or null in the
// case of a constructor, or null if the method's return type is void. Before
// calling the method or constructor, Invoke checks to see if the user has access
// permission and verify that the parameters are valid.
//
// Exceptions:
// System.MethodAccessException:
// The caller does not have permission to execute the constructor.
//
// System.InvalidOperationException:
// The type that declares the method is an open generic type. That is, the System.Type.ContainsGenericParameters
// property returns true for the declaring type.
//
// System.Reflection.TargetInvocationException:
// The invoked method or constructor throws an exception.
//
// System.Reflection.TargetParameterCountException:
// The parameters array does not have the correct number of arguments.
//
// System.ArgumentException:
// The type of the parameters parameter does not match the signature of the
// method or constructor reflected by this instance.
//
// System.Reflection.TargetException:
// The obj parameter is null and the method is not static.-or- The method is
// not declared or inherited by the class of obj. -or-A static constructor is
// invoked, and obj is neither null nor an instance of the class that declared
// the constructor.
public virtual object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
return default(object);
}
}
}
| |
// This file is auto generatored. Don't modify it.
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Wu Yuntao
*
* 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;
namespace SecurePrimitive
{
public partial struct SPUInt32
{
#region SPUInt32 <-> SPSByte
public static explicit operator SPUInt32(SPSByte value)
{
return new SPUInt32((uint)value.Value);
}
public static explicit operator SPSByte(SPUInt32 value)
{
return new SPSByte((sbyte)value.Value);
}
#endregion
#region SPUInt32 <-> sbyte
public static explicit operator SPUInt32(sbyte value)
{
return new SPUInt32((uint)value);
}
public static explicit operator sbyte(SPUInt32 value)
{
return (sbyte)value.Value;
}
#endregion
#region SPUInt32 <-> SPByte
public static explicit operator SPUInt32(SPByte value)
{
return new SPUInt32((uint)value.Value);
}
public static explicit operator SPByte(SPUInt32 value)
{
return new SPByte((byte)value.Value);
}
#endregion
#region SPUInt32 <-> byte
public static explicit operator SPUInt32(byte value)
{
return new SPUInt32((uint)value);
}
public static explicit operator byte(SPUInt32 value)
{
return (byte)value.Value;
}
#endregion
#region SPUInt32 <-> SPInt16
public static explicit operator SPUInt32(SPInt16 value)
{
return new SPUInt32((uint)value.Value);
}
public static explicit operator SPInt16(SPUInt32 value)
{
return new SPInt16((short)value.Value);
}
#endregion
#region SPUInt32 <-> short
public static explicit operator SPUInt32(short value)
{
return new SPUInt32((uint)value);
}
public static explicit operator short(SPUInt32 value)
{
return (short)value.Value;
}
#endregion
#region SPUInt32 <-> SPUInt16
public static explicit operator SPUInt32(SPUInt16 value)
{
return new SPUInt32((uint)value.Value);
}
public static explicit operator SPUInt16(SPUInt32 value)
{
return new SPUInt16((ushort)value.Value);
}
#endregion
#region SPUInt32 <-> ushort
public static explicit operator SPUInt32(ushort value)
{
return new SPUInt32((uint)value);
}
public static explicit operator ushort(SPUInt32 value)
{
return (ushort)value.Value;
}
#endregion
#region SPUInt32 <-> SPInt32
public static explicit operator SPUInt32(SPInt32 value)
{
return new SPUInt32((uint)value.Value);
}
public static explicit operator SPInt32(SPUInt32 value)
{
return new SPInt32((int)value.Value);
}
#endregion
#region SPUInt32 <-> int
public static explicit operator SPUInt32(int value)
{
return new SPUInt32((uint)value);
}
public static explicit operator int(SPUInt32 value)
{
return (int)value.Value;
}
#endregion
#region SPUInt32 <-> uint
public static implicit operator SPUInt32(uint value)
{
return new SPUInt32(value);
}
public static implicit operator uint(SPUInt32 value)
{
return value.Value;
}
#endregion
#region SPUInt32 <-> SPInt64
public static explicit operator SPUInt32(SPInt64 value)
{
return new SPUInt32((uint)value.Value);
}
public static explicit operator SPInt64(SPUInt32 value)
{
return new SPInt64((long)value.Value);
}
#endregion
#region SPUInt32 <-> long
public static explicit operator SPUInt32(long value)
{
return new SPUInt32((uint)value);
}
public static explicit operator long(SPUInt32 value)
{
return (long)value.Value;
}
#endregion
#region SPUInt32 <-> SPUInt64
public static explicit operator SPUInt32(SPUInt64 value)
{
return new SPUInt32((uint)value.Value);
}
public static explicit operator SPUInt64(SPUInt32 value)
{
return new SPUInt64((ulong)value.Value);
}
#endregion
#region SPUInt32 <-> ulong
public static explicit operator SPUInt32(ulong value)
{
return new SPUInt32((uint)value);
}
public static explicit operator ulong(SPUInt32 value)
{
return (ulong)value.Value;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServerManagement
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for GatewayOperations.
/// </summary>
public static partial class GatewayOperationsExtensions
{
/// <summary>
/// Creates or updates a ManagementService gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume upgradeMode =
/// Automatic. Possible values include: 'Manual', 'Automatic'
/// </param>
public static GatewayResource Create(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).CreateAsync(resourceGroupName, gatewayName, location, tags, upgradeMode), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a ManagementService gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume upgradeMode =
/// Automatic. Possible values include: 'Manual', 'Automatic'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<GatewayResource> CreateAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, gatewayName, location, tags, upgradeMode, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a ManagementService gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume upgradeMode =
/// Automatic. Possible values include: 'Manual', 'Automatic'
/// </param>
public static GatewayResource BeginCreate(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).BeginCreateAsync(resourceGroupName, gatewayName, location, tags, upgradeMode), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a ManagementService gateway.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume upgradeMode =
/// Automatic. Possible values include: 'Manual', 'Automatic'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<GatewayResource> BeginCreateAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, gatewayName, location, tags, upgradeMode, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a gateway belonging to a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume upgradeMode =
/// Automatic. Possible values include: 'Manual', 'Automatic'
/// </param>
public static GatewayResource Update(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).UpdateAsync(resourceGroupName, gatewayName, location, tags, upgradeMode), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a gateway belonging to a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume upgradeMode =
/// Automatic. Possible values include: 'Manual', 'Automatic'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<GatewayResource> UpdateAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, gatewayName, location, tags, upgradeMode, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a gateway belonging to a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume upgradeMode =
/// Automatic. Possible values include: 'Manual', 'Automatic'
/// </param>
public static GatewayResource BeginUpdate(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).BeginUpdateAsync(resourceGroupName, gatewayName, location, tags, upgradeMode), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a gateway belonging to a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='upgradeMode'>
/// The upgradeMode property gives the flexibility to gateway to auto upgrade
/// itself. If properties value not specified, then we assume upgradeMode =
/// Automatic. Possible values include: 'Manual', 'Automatic'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<GatewayResource> BeginUpdateAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, string location = default(string), object tags = default(object), UpgradeMode? upgradeMode = default(UpgradeMode?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, gatewayName, location, tags, upgradeMode, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a gateway from a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static void Delete(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).DeleteAsync(resourceGroupName, gatewayName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a gateway from a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task DeleteAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum)
/// </param>
/// <param name='expand'>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call. Possible values include: 'status', 'download'
/// </param>
public static GatewayResource Get(this IGatewayOperations operations, string resourceGroupName, string gatewayName, GatewayExpandOption? expand = default(GatewayExpandOption?))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).GetAsync(resourceGroupName, gatewayName, expand), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum)
/// </param>
/// <param name='expand'>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call. Possible values include: 'status', 'download'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<GatewayResource> GetAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, GatewayExpandOption? expand = default(GatewayExpandOption?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, gatewayName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns gateways in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<GatewayResource> List(this IGatewayOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).ListAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns gateways in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<GatewayResource>> ListAsync(this IGatewayOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns gateways in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
public static Microsoft.Rest.Azure.IPage<GatewayResource> ListForResourceGroup(this IGatewayOperations operations, string resourceGroupName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).ListForResourceGroupAsync(resourceGroupName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns gateways in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<GatewayResource>> ListForResourceGroupAsync(this IGatewayOperations operations, string resourceGroupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListForResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Upgrade a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static void Upgrade(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).UpgradeAsync(resourceGroupName, gatewayName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Upgrade a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task UpgradeAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.UpgradeWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Upgrade a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static void BeginUpgrade(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).BeginUpgradeAsync(resourceGroupName, gatewayName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Upgrade a gateway
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginUpgradeAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginUpgradeWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Regenerate a gateway's profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static void RegenerateProfile(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).RegenerateProfileAsync(resourceGroupName, gatewayName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerate a gateway's profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task RegenerateProfileAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.RegenerateProfileWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Regenerate a gateway's profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static void BeginRegenerateProfile(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).BeginRegenerateProfileAsync(resourceGroupName, gatewayName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerate a gateway's profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginRegenerateProfileAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginRegenerateProfileWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a gateway profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static GatewayProfile GetProfile(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).GetProfileAsync(resourceGroupName, gatewayName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a gateway profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<GatewayProfile> GetProfileAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetProfileWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a gateway profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
public static GatewayProfile BeginGetProfile(this IGatewayOperations operations, string resourceGroupName, string gatewayName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).BeginGetProfileAsync(resourceGroupName, gatewayName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a gateway profile
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='gatewayName'>
/// The gateway name (256 characters maximum).
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<GatewayProfile> BeginGetProfileAsync(this IGatewayOperations operations, string resourceGroupName, string gatewayName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginGetProfileWithHttpMessagesAsync(resourceGroupName, gatewayName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns gateways in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<GatewayResource> ListNext(this IGatewayOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns gateways in a subscription
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<GatewayResource>> ListNextAsync(this IGatewayOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns gateways in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<GatewayResource> ListForResourceGroupNext(this IGatewayOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IGatewayOperations)s).ListForResourceGroupNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns gateways in a resource group
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<GatewayResource>> ListForResourceGroupNextAsync(this IGatewayOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListForResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//
// PlayerEngineService.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2006-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.IO;
using System.Collections.Generic;
using System.Reflection;
using Mono.Unix;
using Mono.Addins;
using Hyena;
using Banshee.Base;
using Banshee.Streaming;
using Banshee.ServiceStack;
using Banshee.Metadata;
using Banshee.Configuration;
using Banshee.Collection;
using Banshee.Equalizer;
namespace Banshee.MediaEngine
{
public delegate bool TrackInterceptHandler (TrackInfo track);
public class PlayerEngineService : IInitializeService, IDelayedInitializeService,
IRequiredService, IPlayerEngineService, IDisposable
{
private List<PlayerEngine> engines = new List<PlayerEngine> ();
private PlayerEngine active_engine;
private PlayerEngine default_engine;
private PlayerEngine pending_engine;
private object pending_playback_for_not_ready;
private bool pending_playback_for_not_ready_play;
private TrackInfo synthesized_contacting_track;
private string preferred_engine_id = null;
public event EventHandler PlayWhenIdleRequest;
public event TrackInterceptHandler TrackIntercept;
public event Action<PlayerEngine> EngineBeforeInitialize;
public event Action<PlayerEngine> EngineAfterInitialize;
private event DBusPlayerEventHandler dbus_event_changed;
event DBusPlayerEventHandler IPlayerEngineService.EventChanged {
add { dbus_event_changed += value; }
remove { dbus_event_changed -= value; }
}
private event DBusPlayerStateHandler dbus_state_changed;
event DBusPlayerStateHandler IPlayerEngineService.StateChanged {
add { dbus_state_changed += value; }
remove { dbus_state_changed -= value; }
}
public PlayerEngineService ()
{
}
void IInitializeService.Initialize ()
{
preferred_engine_id = EngineSchema.Get();
if (default_engine == null && engines.Count > 0) {
default_engine = engines[0];
}
foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/MediaEngine/PlayerEngine")) {
LoadEngine (node);
}
if (default_engine != null) {
active_engine = default_engine;
Log.Debug (Catalog.GetString ("Default player engine"), active_engine.Name);
} else {
default_engine = active_engine;
}
if (default_engine == null || active_engine == null || engines == null || engines.Count == 0) {
Log.Warning (Catalog.GetString (
"No player engines were found. Please ensure Banshee has been cleanly installed."),
"Using the featureless NullPlayerEngine.");
PlayerEngine null_engine = new NullPlayerEngine ();
LoadEngine (null_engine);
active_engine = null_engine;
default_engine = null_engine;
}
MetadataService.Instance.HaveResult += OnMetadataServiceHaveResult;
TrackInfo.IsPlayingMethod = track => IsPlaying (track) &&
track.CacheModelId == CurrentTrack.CacheModelId &&
(track.CacheEntryId == null || track.CacheEntryId.Equals (CurrentTrack.CacheEntryId));
}
private void InitializeEngine (PlayerEngine engine)
{
var handler = EngineBeforeInitialize;
if (handler != null) {
handler (engine);
}
engine.Initialize ();
engine.IsInitialized = true;
handler = EngineAfterInitialize;
if (handler != null) {
handler (engine);
}
}
void IDelayedInitializeService.DelayedInitialize ()
{
foreach (var engine in Engines) {
if (engine.DelayedInitialize) {
InitializeEngine (engine);
}
}
}
private void LoadEngine (TypeExtensionNode node)
{
LoadEngine ((PlayerEngine) node.CreateInstance (typeof (PlayerEngine)));
}
private void LoadEngine (PlayerEngine engine)
{
if (!engine.DelayedInitialize) {
InitializeEngine (engine);
}
engine.EventChanged += OnEngineEventChanged;
if (engine.Id == preferred_engine_id) {
DefaultEngine = engine;
} else {
if (active_engine == null) {
active_engine = engine;
}
engines.Add (engine);
}
}
public void Dispose ()
{
MetadataService.Instance.HaveResult -= OnMetadataServiceHaveResult;
foreach (PlayerEngine engine in engines) {
engine.Dispose ();
}
active_engine = null;
default_engine = null;
pending_engine = null;
preferred_engine_id = null;
engines.Clear ();
}
private void OnMetadataServiceHaveResult (object o, MetadataLookupResultArgs args)
{
if (CurrentTrack != null && CurrentTrack.TrackEqual (args.Track as TrackInfo)) {
foreach (StreamTag tag in args.ResultTags) {
StreamTagger.TrackInfoMerge (CurrentTrack, tag);
}
OnEngineEventChanged (new PlayerEventArgs (PlayerEvent.TrackInfoUpdated));
}
}
private void HandleStateChange (PlayerEventStateChangeArgs args)
{
if (args.Current == PlayerState.Loaded && CurrentTrack != null) {
MetadataService.Instance.Lookup (CurrentTrack);
} else if (args.Current == PlayerState.Ready) {
// Enable our preferred equalizer if it exists and was enabled last time.
if (SupportsEqualizer) {
EqualizerManager.Instance.Select ();
}
if (pending_playback_for_not_ready != null) {
OpenCheck (pending_playback_for_not_ready, pending_playback_for_not_ready_play);
pending_playback_for_not_ready = null;
pending_playback_for_not_ready_play = false;
}
}
DBusPlayerStateHandler dbus_handler = dbus_state_changed;
if (dbus_handler != null) {
dbus_handler (args.Current.ToString ().ToLower ());
}
}
private void OnEngineEventChanged (PlayerEventArgs args)
{
if (CurrentTrack != null) {
if (args.Event == PlayerEvent.Error
&& CurrentTrack.PlaybackError == StreamPlaybackError.None) {
CurrentTrack.SavePlaybackError (StreamPlaybackError.Unknown);
} else if (args.Event == PlayerEvent.Iterate
&& CurrentTrack.PlaybackError != StreamPlaybackError.None) {
CurrentTrack.SavePlaybackError (StreamPlaybackError.None);
}
}
if (args.Event == PlayerEvent.StartOfStream) {
incremented_last_played = false;
}
RaiseEvent (args);
// Do not raise iterate across DBus to avoid so many calls;
// DBus clients should do their own iterating and
// event/state checking locally
if (args.Event == PlayerEvent.Iterate) {
return;
}
DBusPlayerEventHandler dbus_handler = dbus_event_changed;
if (dbus_handler != null) {
dbus_handler (args.Event.ToString ().ToLower (),
args is PlayerEventErrorArgs ? ((PlayerEventErrorArgs)args).Message : String.Empty,
args is PlayerEventBufferingArgs ? ((PlayerEventBufferingArgs)args).Progress : 0
);
}
}
private void OnPlayWhenIdleRequest ()
{
EventHandler handler = PlayWhenIdleRequest;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
private bool OnTrackIntercept (TrackInfo track)
{
TrackInterceptHandler handler = TrackIntercept;
if (handler == null) {
return false;
}
bool handled = false;
foreach (TrackInterceptHandler single_handler in handler.GetInvocationList ()) {
handled |= single_handler (track);
}
return handled;
}
public void Open (TrackInfo track)
{
OpenPlay (track, false);
}
public void Open (SafeUri uri)
{
OpenCheck (uri);
}
void IPlayerEngineService.Open (string uri)
{
OpenCheck (new SafeUri (uri));
}
public void SetNextTrack (TrackInfo track)
{
if (track != null && EnsureActiveEngineCanPlay (track.Uri)) {
active_engine.SetNextTrack (track);
} else {
active_engine.SetNextTrack ((TrackInfo) null);
}
}
public void SetNextTrack (SafeUri uri)
{
if (EnsureActiveEngineCanPlay (uri)) {
active_engine.SetNextTrack (uri);
} else {
active_engine.SetNextTrack ((SafeUri) null);
}
}
private bool EnsureActiveEngineCanPlay (SafeUri uri)
{
if (uri == null) {
// No engine can play the null URI.
return false;
}
if (active_engine != FindSupportingEngine (uri)) {
if (active_engine.CurrentState == PlayerState.Playing) {
// If we're currently playing then we can't switch engines now.
// We can't ensure the active engine can play this URI.
return false;
} else {
// If we're not playing, we can switch the active engine to
// something that will play this URI.
SwitchToEngine (FindSupportingEngine (uri));
CheckPending ();
return true;
}
}
return true;
}
public void OpenPlay (TrackInfo track)
{
OpenPlay (track, true);
}
private void OpenPlay (TrackInfo track, bool play)
{
if (track == null || !track.CanPlay || OnTrackIntercept (track)) {
return;
}
try {
OpenCheck (track, true);
} catch (Exception e) {
Log.Exception (e);
Log.Error (Catalog.GetString ("Problem with Player Engine"), e.Message, true);
Close ();
ActiveEngine = default_engine;
}
}
private void OpenCheck (object o)
{
OpenCheck (o, false);
}
private void OpenCheck (object o, bool play)
{
if (CurrentState == PlayerState.NotReady) {
pending_playback_for_not_ready = o;
pending_playback_for_not_ready_play = play;
return;
}
SafeUri uri = null;
TrackInfo track = null;
if (o is SafeUri) {
uri = (SafeUri)o;
} else if (o is TrackInfo) {
track = (TrackInfo)o;
uri = track.Uri;
} else {
return;
}
if (track != null && (track.MediaAttributes & TrackMediaAttributes.ExternalResource) != 0) {
RaiseEvent (new PlayerEventArgs (PlayerEvent.EndOfStream));
return;
}
PlayerEngine supportingEngine = FindSupportingEngine (uri);
SwitchToEngine (supportingEngine);
CheckPending ();
if (track != null) {
active_engine.Open (track);
} else if (uri != null) {
active_engine.Open (uri);
}
if (play) {
active_engine.Play ();
}
}
public void IncrementLastPlayed ()
{
// If Length <= 0 assume 100% completion.
IncrementLastPlayed (active_engine.Length <= 0
? 1.0
: (double)active_engine.Position / active_engine.Length);
}
private bool incremented_last_played = true;
public void IncrementLastPlayed (double completed)
{
if (!incremented_last_played && CurrentTrack != null && CurrentTrack.PlaybackError == StreamPlaybackError.None) {
CurrentTrack.OnPlaybackFinished (completed);
incremented_last_played = true;
}
}
private PlayerEngine FindSupportingEngine (SafeUri uri)
{
foreach (PlayerEngine engine in engines) {
foreach (string extension in engine.ExplicitDecoderCapabilities) {
if (!uri.AbsoluteUri.EndsWith (extension)) {
continue;
}
return engine;
}
}
foreach (PlayerEngine engine in engines) {
foreach (string scheme in engine.SourceCapabilities) {
bool supported = scheme == uri.Scheme;
if (supported) {
return engine;
}
}
}
// If none of our engines support this URI, return the currently active one.
// There doesn't seem to be anything better to do.
return active_engine;
}
private bool SwitchToEngine (PlayerEngine switchTo)
{
if (active_engine != switchTo) {
Close ();
pending_engine = switchTo;
Log.DebugFormat ("Switching engine to: {0}", switchTo.GetType ());
return true;
}
return false;
}
public void Close ()
{
Close (false);
}
public void Close (bool fullShutdown)
{
IncrementLastPlayed ();
active_engine.Reset ();
active_engine.Close (fullShutdown);
}
public void Play ()
{
if (CurrentState == PlayerState.Idle) {
OnPlayWhenIdleRequest ();
} else {
active_engine.Play ();
}
}
public void Pause ()
{
if (!CanPause) {
Close ();
} else {
active_engine.Pause ();
}
}
// For use by RadioTrackInfo
// TODO remove this method once RadioTrackInfo playlist downloading/parsing logic moved here?
internal void StartSynthesizeContacting (TrackInfo track)
{
//OnStateChanged (PlayerState.Contacting);
RaiseEvent (new PlayerEventStateChangeArgs (CurrentState, PlayerState.Contacting));
synthesized_contacting_track = track;
}
internal void EndSynthesizeContacting (TrackInfo track, bool idle)
{
if (track == synthesized_contacting_track) {
synthesized_contacting_track = null;
if (idle) {
RaiseEvent (new PlayerEventStateChangeArgs (PlayerState.Contacting, PlayerState.Idle));
}
}
}
public void TogglePlaying ()
{
if (IsPlaying () && CurrentState != PlayerState.Paused) {
Pause ();
} else if (CurrentState != PlayerState.NotReady) {
Play ();
}
}
public void VideoExpose (IntPtr displayContext, bool direct)
{
active_engine.VideoExpose (displayContext, direct);
}
public void VideoWindowRealize (IntPtr displayContext)
{
active_engine.VideoWindowRealize (displayContext);
}
public IntPtr VideoDisplayContext {
set { active_engine.VideoDisplayContext = value; }
get { return active_engine.VideoDisplayContext; }
}
public void TrackInfoUpdated ()
{
active_engine.TrackInfoUpdated ();
}
public bool IsPlaying (TrackInfo track)
{
return IsPlaying () && track != null && track.TrackEqual (CurrentTrack);
}
public bool IsPlaying ()
{
return CurrentState == PlayerState.Playing ||
CurrentState == PlayerState.Paused ||
CurrentState == PlayerState.Loaded ||
CurrentState == PlayerState.Loading ||
CurrentState == PlayerState.Contacting;
}
private void CheckPending ()
{
if (pending_engine != null && pending_engine != active_engine) {
if (active_engine.CurrentState == PlayerState.Idle) {
Close ();
}
active_engine = pending_engine;
pending_engine = null;
}
}
public TrackInfo CurrentTrack {
get { return active_engine.CurrentTrack ?? synthesized_contacting_track; }
}
private Dictionary<string, object> dbus_sucks;
IDictionary<string, object> IPlayerEngineService.CurrentTrack {
get {
// FIXME: Managed DBus sucks - it explodes if you transport null
// or even an empty dictionary (a{sv} in our case). Piece of shit.
if (dbus_sucks == null) {
dbus_sucks = new Dictionary<string, object> ();
dbus_sucks.Add (String.Empty, String.Empty);
}
return CurrentTrack == null ? dbus_sucks : CurrentTrack.GenerateExportable ();
}
}
public SafeUri CurrentSafeUri {
get { return active_engine.CurrentUri; }
}
string IPlayerEngineService.CurrentUri {
get { return CurrentSafeUri == null ? String.Empty : CurrentSafeUri.AbsoluteUri; }
}
public PlayerState CurrentState {
get { return synthesized_contacting_track != null ? PlayerState.Contacting : active_engine.CurrentState; }
}
string IPlayerEngineService.CurrentState {
get { return CurrentState.ToString ().ToLower (); }
}
public PlayerState LastState {
get { return active_engine.LastState; }
}
string IPlayerEngineService.LastState {
get { return LastState.ToString ().ToLower (); }
}
public ushort Volume {
get { return active_engine.Volume; }
set {
foreach (PlayerEngine engine in engines) {
engine.Volume = value;
}
}
}
public uint Position {
get { return active_engine.Position; }
set { active_engine.Position = value; }
}
public byte Rating {
get { return (byte)(CurrentTrack == null ? 0 : CurrentTrack.Rating); }
set {
if (CurrentTrack != null) {
CurrentTrack.Rating = (int)Math.Min (5u, value);
CurrentTrack.Save ();
}
}
}
public bool CanSeek {
get { return active_engine.CanSeek; }
}
public bool CanPause {
get { return CurrentTrack != null && !CurrentTrack.IsLive; }
}
public bool SupportsEqualizer {
get { return ((active_engine is IEqualizer) && active_engine.SupportsEqualizer); }
}
public VideoDisplayContextType VideoDisplayContextType {
get { return active_engine.VideoDisplayContextType; }
}
public uint Length {
get {
uint length = active_engine.Length;
if (length > 0) {
return length;
} else if (CurrentTrack == null) {
return 0;
}
return (uint) CurrentTrack.Duration.TotalSeconds;
}
}
public PlayerEngine ActiveEngine {
get { return active_engine; }
set { pending_engine = value; }
}
public PlayerEngine DefaultEngine {
get { return default_engine; }
set {
if (engines.Contains (value)) {
engines.Remove (value);
}
engines.Insert (0, value);
default_engine = value;
EngineSchema.Set (value.Id);
}
}
public IEnumerable<PlayerEngine> Engines {
get { return engines; }
}
#region Player Event System
private LinkedList<PlayerEventHandlerSlot> event_handlers = new LinkedList<PlayerEventHandlerSlot> ();
private struct PlayerEventHandlerSlot
{
public PlayerEvent EventMask;
public PlayerEventHandler Handler;
public PlayerEventHandlerSlot (PlayerEvent mask, PlayerEventHandler handler)
{
EventMask = mask;
Handler = handler;
}
}
private const PlayerEvent event_all_mask = PlayerEvent.Iterate
| PlayerEvent.StateChange
| PlayerEvent.StartOfStream
| PlayerEvent.EndOfStream
| PlayerEvent.Buffering
| PlayerEvent.Seek
| PlayerEvent.Error
| PlayerEvent.Volume
| PlayerEvent.Metadata
| PlayerEvent.TrackInfoUpdated
| PlayerEvent.RequestNextTrack
| PlayerEvent.PrepareVideoWindow;
private const PlayerEvent event_default_mask = event_all_mask & ~PlayerEvent.Iterate;
private static void VerifyEventMask (PlayerEvent eventMask)
{
if (eventMask <= PlayerEvent.None || eventMask > event_all_mask) {
throw new ArgumentOutOfRangeException ("eventMask", "A valid event mask must be provided");
}
}
public void ConnectEvent (PlayerEventHandler handler)
{
ConnectEvent (handler, event_default_mask, false);
}
public void ConnectEvent (PlayerEventHandler handler, PlayerEvent eventMask)
{
ConnectEvent (handler, eventMask, false);
}
public void ConnectEvent (PlayerEventHandler handler, bool connectAfter)
{
ConnectEvent (handler, event_default_mask, connectAfter);
}
public void ConnectEvent (PlayerEventHandler handler, PlayerEvent eventMask, bool connectAfter)
{
lock (event_handlers) {
VerifyEventMask (eventMask);
PlayerEventHandlerSlot slot = new PlayerEventHandlerSlot (eventMask, handler);
if (connectAfter) {
event_handlers.AddLast (slot);
} else {
event_handlers.AddFirst (slot);
}
}
}
private LinkedListNode<PlayerEventHandlerSlot> FindEventNode (PlayerEventHandler handler)
{
LinkedListNode<PlayerEventHandlerSlot> node = event_handlers.First;
while (node != null) {
if (node.Value.Handler == handler) {
return node;
}
node = node.Next;
}
return null;
}
public void DisconnectEvent (PlayerEventHandler handler)
{
lock (event_handlers) {
LinkedListNode<PlayerEventHandlerSlot> node = FindEventNode (handler);
if (node != null) {
event_handlers.Remove (node);
}
}
}
public void ModifyEvent (PlayerEvent eventMask, PlayerEventHandler handler)
{
lock (event_handlers) {
VerifyEventMask (eventMask);
LinkedListNode<PlayerEventHandlerSlot> node = FindEventNode (handler);
if (node != null) {
PlayerEventHandlerSlot slot = node.Value;
slot.EventMask = eventMask;
node.Value = slot;
}
}
}
private void RaiseEvent (PlayerEventArgs args)
{
lock (event_handlers) {
if (args.Event == PlayerEvent.StateChange && args is PlayerEventStateChangeArgs) {
HandleStateChange ((PlayerEventStateChangeArgs)args);
}
LinkedListNode<PlayerEventHandlerSlot> node = event_handlers.First;
while (node != null) {
if ((node.Value.EventMask & args.Event) == args.Event) {
node.Value.Handler (args);
}
node = node.Next;
}
}
}
#endregion
string IService.ServiceName {
get { return "PlayerEngine"; }
}
IDBusExportable IDBusExportable.Parent {
get { return null; }
}
public static readonly SchemaEntry<int> VolumeSchema = new SchemaEntry<int> (
"player_engine", "volume",
80,
"Volume",
"Volume of playback relative to mixer output"
);
public static readonly SchemaEntry<string> EngineSchema = new SchemaEntry<string> (
"player_engine", "backend",
"helix-remote",
"Backend",
"Name of media playback engine backend"
);
}
}
| |
/*
Copyright 2013 Roman Fortunatov
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.
*/
#region Usings
using System;
using System.Runtime.InteropServices;
#endregion
namespace WirelessAudioServer
{
/// <summary>
/// Win32
/// </summary>
public class Win32
{
//Konstanten
public delegate void DelegateTimerProc(IntPtr lpParameter, bool TimerOrWaitFired);
public delegate void DelegateWaveInProc(
IntPtr hWaveIn, WIM_Messages msg, IntPtr dwInstance, ref WAVEHDR wavehdr, IntPtr lParam);
public delegate void DelegateWaveOutProc(
IntPtr hWaveOut, WOM_Messages msg, IntPtr dwInstance, ref WAVEHDR wavehdr, IntPtr lParam);
public delegate void TimerEventHandler(UInt32 id, UInt32 msg, ref UInt32 userCtx, UInt32 rsv1, UInt32 rsv2);
[Flags]
public enum HRESULT : long
{
S_OK = 0L,
S_FALSE = 1L
}
/// <summary>
/// MMRESULT
/// </summary>
public enum MMRESULT : uint
{
MMSYSERR_NOERROR = 0,
MMSYSERR_ERROR = 1,
MMSYSERR_BADDEVICEID = 2,
MMSYSERR_NOTENABLED = 3,
MMSYSERR_ALLOCATED = 4,
MMSYSERR_INVALHANDLE = 5,
MMSYSERR_NODRIVER = 6,
MMSYSERR_NOMEM = 7,
MMSYSERR_NOTSUPPORTED = 8,
MMSYSERR_BADERRNUM = 9,
MMSYSERR_INVALFLAG = 10,
MMSYSERR_INVALPARAM = 11,
MMSYSERR_HANDLEBUSY = 12,
MMSYSERR_INVALIDALIAS = 13,
MMSYSERR_BADDB = 14,
MMSYSERR_KEYNOTFOUND = 15,
MMSYSERR_READERROR = 16,
MMSYSERR_WRITEERROR = 17,
MMSYSERR_DELETEERROR = 18,
MMSYSERR_VALNOTFOUND = 19,
MMSYSERR_NODRIVERCB = 20,
WAVERR_BADFORMAT = 32,
WAVERR_STILLPLAYING = 33,
WAVERR_UNPREPARED = 34
}
/// <summary>
/// MMSYSERR
/// </summary>
public enum MMSYSERR : uint
{
// Add MMSYSERR's here!
MMSYSERR_BASE = 0x0000,
MMSYSERR_NOERROR = 0x0000
}
/// <summary>
/// WIM_Messages
/// </summary>
public enum WIM_Messages
{
OPEN = 0x03BE,
CLOSE = 0x03BF,
DATA = 0x03C0
}
/// <summary>
/// WOM_Messages
/// </summary>
public enum WOM_Messages
{
OPEN = 0x03BB,
CLOSE = 0x03BC,
DONE = 0x03BD
}
[Flags]
public enum WaveFormatFlags
{
WAVE_FORMAT_PCM = 0x0001
}
[Flags]
public enum WaveHdrFlags : uint
{
WHDR_DONE = 1,
WHDR_PREPARED = 2,
WHDR_BEGINLOOP = 4,
WHDR_ENDLOOP = 8,
WHDR_INQUEUE = 16
}
[Flags]
public enum WaveProcFlags
{
CALLBACK_NULL = 0,
CALLBACK_FUNCTION = 0x30000,
CALLBACK_EVENT = 0x50000,
CALLBACK_WINDOW = 0x10000,
CALLBACK_THREAD = 0x20000,
WAVE_FORMAT_QUERY = 1,
WAVE_MAPPED = 4,
WAVE_FORMAT_DIRECT = 8
}
public const int WAVE_MAPPER = -1;
public const int WT_EXECUTEDEFAULT = 0x00000000;
public const int WT_EXECUTEINIOTHREAD = 0x00000001;
public const int WT_EXECUTEINTIMERTHREAD = 0x00000020;
public const int WT_EXECUTEINPERSISTENTTHREAD = 0x00000080;
public const int TIME_ONESHOT = 0;
public const int TIME_PERIODIC = 1;
[DllImport("Kernel32.dll", EntryPoint = "QueryPerformanceCounter")]
public static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
[DllImport("Kernel32.dll", EntryPoint = "QueryPerformanceFrequency")]
public static extern bool QueryPerformanceFrequency(out long lpFrequency);
[DllImport("winmm.dll", SetLastError = true, EntryPoint = "timeSetEvent")]
public static extern UInt32 TimeSetEvent(UInt32 msDelay, UInt32 msResolution, TimerEventHandler handler,
ref UInt32 userCtx, UInt32 eventType);
[DllImport("winmm.dll", SetLastError = true, EntryPoint = "timeKillEvent")]
public static extern UInt32 TimeKillEvent(UInt32 timerId);
[DllImport("kernel32.dll", EntryPoint = "CreateTimerQueue")]
public static extern IntPtr CreateTimerQueue();
[DllImport("kernel32.dll", EntryPoint = "DeleteTimerQueue")]
public static extern bool DeleteTimerQueue(IntPtr TimerQueue);
[DllImport("kernel32.dll", EntryPoint = "CreateTimerQueueTimer")]
public static extern bool CreateTimerQueueTimer(out IntPtr phNewTimer, IntPtr TimerQueue,
DelegateTimerProc Callback, IntPtr Parameter, uint DueTime, uint Period, uint Flags);
[DllImport("kernel32.dll")]
public static extern bool DeleteTimerQueueTimer(IntPtr TimerQueue, IntPtr Timer, IntPtr CompletionEvent);
[DllImport("winmm.dll", SetLastError = true, EntryPoint = "timeGetDevCaps")]
public static extern MMRESULT TimeGetDevCaps(ref TimeCaps timeCaps, UInt32 sizeTimeCaps);
[DllImport("winmm.dll", SetLastError = true, EntryPoint = "timeBeginPeriod")]
public static extern MMRESULT TimeBeginPeriod(UInt32 uPeriod);
[DllImport("winmm.dll", SetLastError = true, EntryPoint = "timeEndPeriod")]
public static extern MMRESULT TimeEndPeriod(UInt32 uPeriod);
[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MMRESULT waveOutOpen(ref IntPtr hWaveOut, int uDeviceID, ref WAVEFORMATEX lpFormat,
DelegateWaveOutProc dwCallBack, int dwInstance, int dwFlags);
[DllImport("winmm.dll")]
public static extern MMRESULT waveInOpen(ref IntPtr hWaveIn, int deviceId, ref WAVEFORMATEX wfx,
DelegateWaveInProc dwCallBack, int dwInstance, int dwFlags);
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT waveInStart(IntPtr hWaveIn);
[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint waveInGetDevCaps(int index, ref WAVEINCAPS pwic, int cbwic);
[DllImport("winmm.dll", SetLastError = true)]
public static extern uint waveInGetNumDevs();
[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint waveOutGetDevCaps(int index, ref WAVEOUTCAPS pwoc, int cbwoc);
[DllImport("winmm.dll", SetLastError = true)]
public static extern uint waveOutGetNumDevs();
[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MMRESULT waveOutWrite(IntPtr hWaveOut, ref WAVEHDR pwh, int cbwh);
[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MMRESULT waveOutPrepareHeader(IntPtr hWaveOut, ref WAVEHDR lpWaveOutHdr, int uSize);
[DllImport("winmm.dll", EntryPoint = "waveInStop", SetLastError = true)]
public static extern MMRESULT waveInStop(IntPtr hWaveIn);
[DllImport("winmm.dll", EntryPoint = "waveInReset", SetLastError = true)]
public static extern MMRESULT waveInReset(IntPtr hWaveIn);
[DllImport("winmm.dll", EntryPoint = "waveOutReset", SetLastError = true)]
public static extern MMRESULT waveOutReset(IntPtr hWaveOut);
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT waveInPrepareHeader(IntPtr hWaveIn, ref WAVEHDR pwh, int cbwh);
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT waveInUnprepareHeader(IntPtr hWaveIn, ref WAVEHDR pwh, int cbwh);
[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MMRESULT waveOutUnprepareHeader(IntPtr hWaveOut, ref WAVEHDR pwh, int cbwh);
[DllImport("winmm.dll", EntryPoint = "waveInAddBuffer", SetLastError = true)]
public static extern MMRESULT waveInAddBuffer(IntPtr hWaveIn, ref WAVEHDR pwh, int cbwh);
[DllImport("winmm.dll", SetLastError = true)]
public static extern MMRESULT waveInClose(IntPtr hWaveIn);
[DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MMRESULT waveOutClose(IntPtr hWaveOut);
[DllImport("winmm.dll")]
public static extern MMRESULT waveOutPause(IntPtr hWaveOut);
[DllImport("winmm.dll", EntryPoint = "waveOutRestart", SetLastError = true)]
public static extern MMRESULT waveOutRestart(IntPtr hWaveOut);
/// <summary>
/// TimeCaps
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct TimeCaps
{
public UInt32 wPeriodMin;
public UInt32 wPeriodMax;
};
/// <summary>
/// WAVEFORMATEX
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct WAVEFORMATEX
{
public ushort wFormatTag;
public ushort nChannels;
public uint nSamplesPerSec;
public uint nAvgBytesPerSec;
public ushort nBlockAlign;
public ushort wBitsPerSample;
public ushort cbSize;
}
/// <summary>
/// WAVEHDR
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct WAVEHDR
{
public IntPtr lpData; // pointer to locked data buffer
public uint dwBufferLength; // length of data buffer
public uint dwBytesRecorded; // used for input only
public IntPtr dwUser; // for client's use
public WaveHdrFlags dwFlags; // assorted flags (see defines)
public uint dwLoops; // loop control counter
public IntPtr lpNext; // PWaveHdr, reserved for driver
public IntPtr reserved; // reserved for driver
}
/// <summary>
/// WAVEINCAPS
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)]
public struct WAVEINCAPS
{
public short wMid;
public short wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szPname;
public uint dwFormats;
public short wChannels;
public short wReserved;
public int dwSupport;
}
/// <summary>
/// WAVEOUTCAPS
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)]
public struct WAVEOUTCAPS
{
public short wMid;
public short wPid;
public int vDriverVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szPname;
public uint dwFormats;
public short wChannels;
public short wReserved;
public int dwSupport;
}
}
}
| |
//
// TagStore.cs
//
// Author:
// Ettore Perazzoli <ettore@src.gnome.org>
// Stephane Delcroix <stephane@delcroix.org>
// Larry Ewing <lewing@novell.com>
//
// Copyright (C) 2003-2009 Novell, Inc.
// Copyright (C) 2003 Ettore Perazzoli
// Copyright (C) 2007-2009 Stephane Delcroix
// Copyright (C) 2004-2006 Larry Ewing
//
// 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 Gdk;
using Gtk;
using Mono.Unix;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System;
using FSpot;
using FSpot.Core;
using FSpot.Database;
using FSpot.Jobs;
using FSpot.Query;
using FSpot.Utils;
using Hyena;
using Hyena.Data.Sqlite;
namespace FSpot {
public class InvalidTagOperationException : InvalidOperationException {
public Tag tag;
public InvalidTagOperationException (Tag t, string message) : base (message)
{
tag = t;
}
public Tag Tag {
get {
return tag;
}
}
}
// Sorts tags into an order that it will be safe to delete
// them in (eg children first).
public class TagRemoveComparer : IComparer {
public int Compare (object obj1, object obj2)
{
Tag t1 = obj1 as Tag;
Tag t2 = obj2 as Tag;
return Compare (t1, t2);
}
public int Compare (Tag t1, Tag t2)
{
if (t1.IsAncestorOf (t2))
return 1;
else if (t2.IsAncestorOf (t1))
return -1;
else
return 0;
}
}
public class TagStore : DbStore<Tag> {
Category root_category;
public Category RootCategory {
get {
return root_category;
}
}
private const string STOCK_ICON_DB_PREFIX = "stock_icon:";
static void SetIconFromString (Tag tag, string icon_string)
{
if (icon_string == null) {
tag.Icon = null;
// IconWasCleared automatically set already, override
// it in this case since it was NULL in the db.
tag.IconWasCleared = false;
} else if (icon_string == String.Empty)
tag.Icon = null;
else if (icon_string.StartsWith (STOCK_ICON_DB_PREFIX))
tag.ThemeIconName = icon_string.Substring (STOCK_ICON_DB_PREFIX.Length);
else
tag.Icon = GdkUtils.Deserialize (Convert.FromBase64String (icon_string));
}
private Tag hidden;
public Tag Hidden {
get {
return hidden;
}
}
public Tag GetTagByName (string name)
{
foreach (Tag t in this.item_cache.Values)
if (t.Name.ToLower () == name.ToLower ())
return t;
return null;
}
public Tag GetTagById (int id)
{
foreach (Tag t in this.item_cache.Values)
if (t.Id == id)
return t;
return null;
}
public Tag [] GetTagsByNameStart (string s)
{
List <Tag> l = new List<Tag> ();
foreach (Tag t in this.item_cache.Values) {
if (t.Name.ToLower ().StartsWith (s.ToLower ()))
l.Add (t);
}
if (l.Count == 0)
return null;
l.Sort (delegate (Tag t1, Tag t2) {return t2.Popularity.CompareTo (t1.Popularity); });
return l.ToArray ();
}
// In this store we keep all the items (i.e. the tags) in memory at all times. This is
// mostly to simplify handling of the parent relationship between tags, but it also makes it
// a little bit faster. We achieve this by passing "true" as the cache_is_immortal to our
// base class.
private void LoadAllTags ()
{
// Pass 1, get all the tags.
IDataReader reader = Database.Query ("SELECT id, name, is_category, sort_priority, icon FROM tags");
while (reader.Read ()) {
uint id = Convert.ToUInt32 (reader ["id"]);
string name = reader ["name"].ToString ();
bool is_category = (Convert.ToUInt32 (reader ["is_category"]) != 0);
Tag tag;
if (is_category)
tag = new Category (null, id, name);
else
tag = new Tag (null, id, name);
if (reader ["icon"] != null)
try {
SetIconFromString (tag, reader ["icon"].ToString ());
} catch (Exception ex) {
Log.Exception ("Unable to load icon for tag " + name, ex);
}
tag.SortPriority = Convert.ToInt32 (reader["sort_priority"]);
AddToCache (tag);
}
reader.Dispose ();
// Pass 2, set the parents.
reader = Database.Query ("SELECT id, category_id FROM tags");
while (reader.Read ()) {
uint id = Convert.ToUInt32 (reader ["id"]);
uint category_id = Convert.ToUInt32 (reader ["category_id"]);
Tag tag = Get (id) as Tag;
if (tag == null)
throw new Exception (String.Format ("Cannot find tag {0}", id));
if (category_id == 0)
tag.Category = RootCategory;
else {
tag.Category = Get (category_id) as Category;
if (tag.Category == null)
Log.Warning ("Tag Without category found");
}
}
reader.Dispose ();
//Pass 3, set popularity
reader = Database.Query ("SELECT tag_id, COUNT (*) AS popularity FROM photo_tags GROUP BY tag_id");
while (reader.Read ()) {
Tag t = Get (Convert.ToUInt32 (reader ["tag_id"])) as Tag;
if (t != null)
t.Popularity = Convert.ToInt32 (reader ["popularity"]);
}
reader.Dispose ();
if (FSpot.App.Instance.Database.Meta.HiddenTagId.Value != null)
hidden = LookupInCache ((uint) FSpot.App.Instance.Database.Meta.HiddenTagId.ValueAsInt) as Tag;
}
private void CreateTable ()
{
Database.Execute (
"CREATE TABLE tags (\n" +
" id INTEGER PRIMARY KEY NOT NULL, \n" +
" name TEXT UNIQUE, \n" +
" category_id INTEGER, \n" +
" is_category BOOLEAN, \n" +
" sort_priority INTEGER, \n" +
" icon TEXT\n" +
")");
}
private void CreateDefaultTags ()
{
Category favorites_category = CreateCategory (RootCategory, Catalog.GetString ("Favorites"), false);
favorites_category.ThemeIconName = "emblem-favorite";
favorites_category.SortPriority = -10;
Commit (favorites_category);
Tag hidden_tag = CreateTag (RootCategory, Catalog.GetString ("Hidden"), false);
hidden_tag.ThemeIconName = "emblem-readonly";
hidden_tag.SortPriority = -9;
this.hidden = hidden_tag;
Commit (hidden_tag);
FSpot.App.Instance.Database.Meta.HiddenTagId.ValueAsInt = (int) hidden_tag.Id;
FSpot.App.Instance.Database.Meta.Commit (FSpot.App.Instance.Database.Meta.HiddenTagId);
Tag people_category = CreateCategory (RootCategory, Catalog.GetString ("People"), false);
people_category.ThemeIconName = "emblem-people";
people_category.SortPriority = -8;
Commit (people_category);
Tag places_category = CreateCategory (RootCategory, Catalog.GetString ("Places"), false);
places_category.ThemeIconName = "emblem-places";
places_category.SortPriority = -8;
Commit (places_category);
Tag events_category = CreateCategory (RootCategory, Catalog.GetString ("Events"), false);
events_category.ThemeIconName = "emblem-event";
events_category.SortPriority = -7;
Commit (events_category);
}
// Constructor
public TagStore (FSpotDatabaseConnection database, bool is_new)
: base (database, true)
{
// The label for the root category is used in new and edit tag dialogs
root_category = new Category (null, 0, Catalog.GetString ("(None)"));
if (! is_new) {
LoadAllTags ();
} else {
CreateTable ();
CreateDefaultTags ();
}
}
private uint InsertTagIntoTable (Category parent_category, string name, bool is_category, bool autoicon)
{
uint parent_category_id = parent_category.Id;
String default_tag_icon_value = autoicon ? null : String.Empty;
int id = Database.Execute (new HyenaSqliteCommand ("INSERT INTO tags (name, category_id, is_category, sort_priority, icon)"
+ "VALUES (?, ?, ?, 0, ?)",
name,
parent_category_id,
is_category ? 1 : 0,
default_tag_icon_value));
return (uint) id;
}
public Tag CreateTag (Category category, string name, bool autoicon)
{
if (category == null)
category = RootCategory;
uint id = InsertTagIntoTable (category, name, false, autoicon);
Tag tag = new Tag (category, id, name);
tag.IconWasCleared = !autoicon;
AddToCache (tag);
EmitAdded (tag);
return tag;
}
public Category CreateCategory (Category parent_category, string name, bool autoicon)
{
if (parent_category == null)
parent_category = RootCategory;
uint id = InsertTagIntoTable (parent_category, name, true, autoicon);
Category new_category = new Category (parent_category, id, name);
new_category.IconWasCleared = !autoicon;
AddToCache (new_category);
EmitAdded (new_category);
return new_category;
}
public override Tag Get (uint id)
{
if (id == 0)
return RootCategory;
else
return LookupInCache (id);
}
public override void Remove (Tag tag)
{
Category category = tag as Category;
if (category != null &&
category.Children != null &&
category.Children.Count > 0)
throw new InvalidTagOperationException (category, "Cannot remove category that contains children");
RemoveFromCache (tag);
tag.Category = null;
Database.Execute (new HyenaSqliteCommand ("DELETE FROM tags WHERE id = ?", tag.Id));
EmitRemoved (tag);
}
private string GetIconString (Tag tag)
{
if (tag.ThemeIconName != null)
return STOCK_ICON_DB_PREFIX + tag.ThemeIconName;
if (tag.Icon == null) {
if (tag.IconWasCleared)
return String.Empty;
return null;
}
byte [] data = GdkUtils.Serialize (tag.Icon);
return Convert.ToBase64String (data);
}
public override void Commit (Tag tag)
{
Commit (tag, false);
}
public void Commit (Tag tag, bool update_xmp)
{
Commit (new Tag[] {tag}, update_xmp);
}
public void Commit (Tag [] tags, bool update_xmp)
{
// TODO.
bool use_transactions = update_xmp;//!Database.InTransaction && update_xmp;
//if (use_transactions)
// Database.BeginTransaction ();
// FIXME: this hack is used, because HyenaSqliteConnection does not support
// the InTransaction propery
if (use_transactions) {
try {
Database.BeginTransaction ();
} catch {
use_transactions = false;
}
}
foreach (Tag tag in tags) {
Database.Execute (new HyenaSqliteCommand ("UPDATE tags SET name = ?, category_id = ?, "
+ "is_category = ?, sort_priority = ?, icon = ? WHERE id = ?",
tag.Name,
tag.Category.Id,
tag is Category ? 1 : 0,
tag.SortPriority,
GetIconString (tag),
tag.Id));
if (update_xmp && Preferences.Get<bool> (Preferences.METADATA_EMBED_IN_IMAGE)) {
Photo [] photos = App.Instance.Database.Photos.Query (new Tag [] { tag });
foreach (Photo p in photos)
if (p.HasTag (tag)) // the query returns all the pics of the tag and all its child. this avoids updating child tags
SyncMetadataJob.Create (App.Instance.Database.Jobs, p);
}
}
if (use_transactions)
Database.CommitTransaction ();
EmitChanged (tags);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.Animation.ColorKeyFrameCollection.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Animation
{
public partial class ColorKeyFrameCollection : System.Windows.Freezable, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable
{
#region Methods and constructors
public int Add(ColorKeyFrame keyFrame)
{
return default(int);
}
public void Clear()
{
}
public System.Windows.Media.Animation.ColorKeyFrameCollection Clone()
{
return default(System.Windows.Media.Animation.ColorKeyFrameCollection);
}
protected override void CloneCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void CloneCurrentValueCore(System.Windows.Freezable sourceFreezable)
{
}
public ColorKeyFrameCollection()
{
}
public bool Contains(ColorKeyFrame keyFrame)
{
return default(bool);
}
public void CopyTo(ColorKeyFrame[] array, int index)
{
}
protected override System.Windows.Freezable CreateInstanceCore()
{
return default(System.Windows.Freezable);
}
protected override bool FreezeCore(bool isChecking)
{
return default(bool);
}
protected override void GetAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
public System.Collections.IEnumerator GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
public int IndexOf(ColorKeyFrame keyFrame)
{
return default(int);
}
public void Insert(int index, ColorKeyFrame keyFrame)
{
}
public void Remove(ColorKeyFrame keyFrame)
{
}
public void RemoveAt(int index)
{
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
}
int System.Collections.IList.Add(Object keyFrame)
{
return default(int);
}
bool System.Collections.IList.Contains(Object keyFrame)
{
return default(bool);
}
int System.Collections.IList.IndexOf(Object keyFrame)
{
return default(int);
}
void System.Collections.IList.Insert(int index, Object keyFrame)
{
}
void System.Collections.IList.Remove(Object keyFrame)
{
}
#endregion
#region Properties and indexers
public int Count
{
get
{
return default(int);
}
}
public static System.Windows.Media.Animation.ColorKeyFrameCollection Empty
{
get
{
return default(System.Windows.Media.Animation.ColorKeyFrameCollection);
}
}
public bool IsFixedSize
{
get
{
return default(bool);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public bool IsSynchronized
{
get
{
return default(bool);
}
}
public ColorKeyFrame this [int index]
{
get
{
return default(ColorKeyFrame);
}
set
{
}
}
public Object SyncRoot
{
get
{
return default(Object);
}
}
Object System.Collections.IList.this [int index]
{
get
{
return default(Object);
}
set
{
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.15.0.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.Management.TrafficManager
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for EndpointsOperations.
/// </summary>
public static partial class EndpointsOperationsExtensions
{
/// <summary>
/// Update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the Update operation.
/// </param>
public static Endpoint Update(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).UpdateAsync(resourceGroupName, profileName, endpointType, endpointName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the Update operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> UpdateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint.
/// </param>
public static Endpoint Get(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).GetAsync(resourceGroupName, profileName, endpointType, endpointName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> GetAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be created or updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the CreateOrUpdate
/// operation.
/// </param>
public static Endpoint CreateOrUpdate(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).CreateOrUpdateAsync(resourceGroupName, profileName, endpointType, endpointName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be created or updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the CreateOrUpdate
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> CreateOrUpdateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be deleted.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be deleted.
/// </param>
public static void Delete(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName)
{
Task.Factory.StartNew(s => ((IEndpointsOperations)s).DeleteAsync(resourceGroupName, profileName, endpointType, endpointName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be deleted.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
using System;
namespace DuckGame
{
// Token: 0x020004E4 RID: 1252
[BaggedProperty("canSpawn", true)]
[BaggedProperty("isOnlineCapable", true)]
[EditorGroup("guns|laser")]
public class CoilGun : Gun
{
// Token: 0x17000647 RID: 1607
// (get) Token: 0x0600222E RID: 8750
// (set) Token: 0x0600222F RID: 8751
private byte netAnimationIndex
{
get
{
if (this._chargeAnim == null)
{
return 0;
}
return (byte)this._chargeAnim.animationIndex;
}
set
{
if (this._chargeAnim != null && this._chargeAnim.animationIndex != (int)value)
{
this._chargeAnim.animationIndex = (int)value;
}
}
}
// Token: 0x17000648 RID: 1608
// (get) Token: 0x06002230 RID: 8752
// (set) Token: 0x06002231 RID: 8753
public byte spriteFrame
{
get
{
if (this._chargeAnim == null)
{
return 0;
}
return (byte)this._chargeAnim._frame;
}
set
{
if (this._chargeAnim != null)
{
this._chargeAnim._frame = (int)value;
}
}
}
// Token: 0x06002232 RID: 8754
public CoilGun(float xval, float yval) : base(xval, yval)
{
this.ammo = 30;
this._type = "gun";
this.center = new Vec2(16f, 16f);
this.collisionOffset = new Vec2(-11f, -8f);
this.collisionSize = new Vec2(22f, 12f);
this._barrelOffsetTL = new Vec2(25f, 13f);
this._fireSound = "";
this._fullAuto = false;
this._fireWait = 1f;
this._kickForce = 1f;
this._holdOffset = new Vec2(3f, 1f);
this._editorName = "Death Laser";
this._chargeAnim = new SpriteMap("coilGun", 32, 32, false);
SpriteMap chargeAnim = this._chargeAnim;
string name = "idle";
float speed = 1f;
bool looping = true;
int[] frames = new int[1];
chargeAnim.AddAnimation(name, speed, looping, frames);
this._chargeAnim.AddAnimation("charge", 0.38f, false, new int[]
{
1,
2,
3,
0,
1,
2,
3,
4,
5,
6,
7,
4,
5,
6,
7
});
this._chargeAnim.AddAnimation("charged", 1f, true, new int[]
{
8,
9,
10,
11
});
this._chargeAnim.AddAnimation("uncharge", 1.2f, false, new int[]
{
7,
6,
5,
4,
7,
6,
5,
4,
3,
2,
1,
0,
3,
2,
1,
0
});
this._chargeAnim.AddAnimation("drain", 2f, false, new int[]
{
7,
6,
5,
4,
7,
6,
5,
4,
3,
2,
1,
0,
3,
2,
1,
0
});
this._chargeAnim.SetAnimation("idle");
this.graphic = this._chargeAnim;
}
// Token: 0x06002233 RID: 8755
public override void Initialize()
{
this._chargeSound = SFX.Get("laserCharge", 0f, 0f, 0f, false);
this._chargeSoundShort = SFX.Get("laserChargeShort", 0f, 0f, 0f, false);
this._unchargeSound = SFX.Get("laserUncharge", 0f, 0f, 0f, false);
this._unchargeSoundShort = SFX.Get("laserUnchargeShort", 0f, 0f, 0f, false);
}
// Token: 0x06002234 RID: 8756
public override void Update()
{
base.Update();
if (this._charge > 0f)
{
this._charge -= 0.1f;
}
else
{
this._charge = 0f;
}
if (this._chargeAnim.currentAnimation == "uncharge" && this._chargeAnim.finished)
{
this._chargeAnim.SetAnimation("idle");
}
if ((Network.isActive && this.doBlast && !this._lastDoBlast) || (this._chargeAnim.currentAnimation == "charge" && this._chargeAnim.finished && base.isServerForObject))
{
this._chargeAnim.SetAnimation("charged");
}
if (this.doBlast && base.isServerForObject)
{
this._framesSinceBlast++;
if (this._framesSinceBlast > 10)
{
this._framesSinceBlast = 0;
this.doBlast = false;
}
}
if (this._chargeAnim.currentAnimation == "drain" && this._chargeAnim.finished)
{
this._chargeAnim.SetAnimation("idle");
}
this._lastDoBlast = this.doBlast;
}
// Token: 0x06002235 RID: 8757
public override void Draw()
{
base.Draw();
}
// Token: 0x06002236 RID: 8758
public override void OnPressAction()
{
if (this._chargeAnim.currentAnimation == "idle")
{
this._chargeSound.Volume = 1f;
this._chargeSound.Play();
this._chargeAnim.SetAnimation("charge");
this._unchargeSound.Stop();
this._unchargeSound.Volume = 0f;
this._unchargeSoundShort.Stop();
this._unchargeSoundShort.Volume = 0f;
return;
}
if (this._chargeAnim.currentAnimation == "uncharge")
{
if (this._chargeAnim.frame > 18)
{
this._chargeSound.Volume = 1f;
this._chargeSound.Play();
}
else
{
this._chargeSoundShort.Volume = 1f;
this._chargeSoundShort.Play();
}
int index = this._chargeAnim.frame;
this._chargeAnim.SetAnimation("charge");
this._chargeAnim.frame = 22 - index;
this._unchargeSound.Stop();
this._unchargeSound.Volume = 0f;
this._unchargeSoundShort.Stop();
this._unchargeSoundShort.Volume = 0f;
}
}
// Token: 0x06002237 RID: 8759
public override void OnHoldAction()
{
}
// Token: 0x06002238 RID: 8760
public override void OnReleaseAction()
{
if (this._chargeAnim.currentAnimation == "charge")
{
if (this._chargeAnim.frame > 20)
{
this._unchargeSound.Volume = 1f;
this._unchargeSound.Play();
}
else
{
this._unchargeSoundShort.Volume = 1f;
this._unchargeSoundShort.Play();
}
int index = this._chargeAnim.frame;
this._chargeAnim.SetAnimation("uncharge");
this._chargeAnim.frame = 22 - index;
this._chargeSound.Stop();
this._chargeSound.Volume = 0f;
this._chargeSoundShort.Stop();
this._chargeSoundShort.Volume = 0f;
}
if (this._chargeAnim.currentAnimation == "charged")
{
Graphics.FlashScreen();
this._chargeAnim.SetAnimation("drain");
SFX.Play("laserBlast", 1f, 0f, 0f, false);
for (int i = 0; i < 4; i++)
{
Level.Add(new ElectricalCharge(base.barrelPosition.x, base.barrelPosition.y, (int)this.offDir, this));
}
}
}
// Token: 0x04002105 RID: 8453
public StateBinding _laserStateBinding = new StateFlagBinding(new string[]
{
"_charging",
"_fired",
"doBlast"
});
// Token: 0x04002106 RID: 8454
public StateBinding _animationIndexBinding = new StateBinding("netAnimationIndex", 4, false, false);
// Token: 0x04002107 RID: 8455
public StateBinding _frameBinding = new StateBinding("spriteFrame", -1, false, false);
// Token: 0x04002108 RID: 8456
public bool doBlast;
// Token: 0x04002109 RID: 8457
private bool _lastDoBlast;
// Token: 0x0400210A RID: 8458
private float _charge;
// Token: 0x0400210B RID: 8459
public bool _charging;
// Token: 0x0400210C RID: 8460
public bool _fired;
// Token: 0x0400210D RID: 8461
private SpriteMap _chargeAnim;
// Token: 0x0400210E RID: 8462
private Sound _chargeSound;
// Token: 0x0400210F RID: 8463
private Sound _chargeSoundShort;
// Token: 0x04002110 RID: 8464
private Sound _unchargeSound;
// Token: 0x04002111 RID: 8465
private Sound _unchargeSoundShort;
// Token: 0x04002112 RID: 8466
private int _framesSinceBlast;
}
}
| |
//---------------------------------------------------------------------
// <copyright file="FilteredReadOnlyMetadataCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Diagnostics;
using System.Reflection;
using System.Text;
namespace System.Data.Metadata.Edm
{
internal interface IBaseList<T> : IList
{
T this[string identity] { get;}
new T this[int index] { get;}
int IndexOf(T item);
}
#pragma warning disable 1711 // compiler bug: reports TDerived and TBase as type parameters for non-existing IsReadOnly property
/// <summary>
/// Class to filter stuff out from a metadata collection
/// </summary>
/*
*/
internal class FilteredReadOnlyMetadataCollection<TDerived, TBase> : ReadOnlyMetadataCollection<TDerived>, IBaseList<TBase>
where TDerived : TBase
where TBase : MetadataItem
{
#region Constructors
/// <summary>
/// The constructor for constructing a read-only metadata collection to wrap another MetadataCollection.
/// </summary>
/// <param name="collection">The metadata collection to wrap</param>
/// <exception cref="System.ArgumentNullException">Thrown if collection argument is null</exception>
/// <param name="predicate">Predicate method which determines membership</param>
internal FilteredReadOnlyMetadataCollection(ReadOnlyMetadataCollection<TBase> collection, Predicate<TBase> predicate) : base(FilterCollection(collection, predicate))
{
Debug.Assert(collection != null);
Debug.Assert(collection.IsReadOnly, "wrappers should only be created once loading is over, and this collection is still loading");
_source = collection;
_predicate = predicate;
}
#endregion
#region Private Fields
// The original metadata collection over which this filtered collection is the view
private readonly ReadOnlyMetadataCollection<TBase> _source;
private readonly Predicate<TBase> _predicate;
#endregion
#region Properties
/// <summary>
/// Gets an item from the collection with the given identity
/// </summary>
/// <param name="identity">The identity of the item to search for</param>
/// <returns>An item from the collection</returns>
/// <exception cref="System.ArgumentNullException">Thrown if identity argument passed in is null</exception>
/// <exception cref="System.NotSupportedException">Thrown if setter is called</exception>
public override TDerived this[string identity]
{
get
{
TBase item = _source[identity];
if (_predicate(item))
{
return (TDerived)item;
}
throw EntityUtil.ItemInvalidIdentity(identity, "identity");
}
}
#endregion
#region Methods
/// <summary>
/// Gets an item from the collection with the given identity
/// </summary>
/// <param name="identity">The identity of the item to search for</param>
/// <param name="ignoreCase">Whether case is ignore in the search</param>
/// <returns>An item from the collection</returns>
/// <exception cref="System.ArgumentNullException">Thrown if identity argument passed in is null</exception>
/// <exception cref="System.ArgumentException">Thrown if the Collection does not have an item with the given identity</exception>
public override TDerived GetValue(string identity, bool ignoreCase)
{
TBase item = _source.GetValue(identity, ignoreCase);
if (_predicate(item))
{
return (TDerived)item;
}
throw EntityUtil.ItemInvalidIdentity(identity, "identity");
}
/// <summary>
/// Determines if this collection contains an item of the given identity
/// </summary>
/// <param name="identity">The identity of the item to check for</param>
/// <returns>True if the collection contains the item with the given identity</returns>
/// <exception cref="System.ArgumentNullException">Thrown if identity argument passed in is null</exception>
/// <exception cref="System.ArgumentException">Thrown if identity argument passed in is empty string</exception>
public override bool Contains(string identity)
{
TBase item;
if (_source.TryGetValue(identity, false/*ignoreCase*/, out item))
{
return (_predicate(item));
}
return false;
}
/// <summary>
/// Gets an item from the collection with the given identity
/// </summary>
/// <param name="identity">The identity of the item to search for</param>
/// <param name="ignoreCase">Whether case is ignore in the search</param>
/// <param name="item">An item from the collection, null if the item is not found</param>
/// <returns>True an item is retrieved</returns>
/// <exception cref="System.ArgumentNullException">if identity argument is null</exception>
public override bool TryGetValue(string identity, bool ignoreCase, out TDerived item)
{
item = null;
TBase baseTypeItem;
if (_source.TryGetValue(identity, ignoreCase, out baseTypeItem))
{
if (_predicate(baseTypeItem))
{
item = (TDerived)baseTypeItem;
return true;
}
}
return false;
}
internal static List<TDerived> FilterCollection(ReadOnlyMetadataCollection<TBase> collection, Predicate<TBase> predicate)
{
List<TDerived> list = new List<TDerived>(collection.Count);
foreach (TBase item in collection)
{
if (predicate(item))
{
list.Add((TDerived)item);
}
}
return list;
}
/// <summary>
/// Get index of the element passed as the argument
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public override int IndexOf(TDerived value)
{
TBase item;
if (_source.TryGetValue(value.Identity, false /*ignoreCase*/, out item))
{
if (_predicate(item))
{
// Since we are gauranteed to have a unique identity per collection, this item must of T Type
return base.IndexOf((TDerived)item);
}
}
return -1;
}
#endregion
#region IBaseList<TBaseItem> Members
TBase IBaseList<TBase>.this[string identity]
{
get { return this[identity]; }
}
TBase IBaseList<TBase>.this[int index]
{
get
{
return this[index];
}
}
/// <summary>
/// Get index of the element passed as the argument
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
int IBaseList<TBase>.IndexOf(TBase item)
{
if (_predicate(item))
{
return this.IndexOf((TDerived)item);
}
return -1;
}
#endregion
}
#pragma warning restore 1711
}
| |
/* transpiled with BefunCompile v1.3.0 (c) 2017 */
public static class Program
{
private static readonly string _g = "Ah+LCAAAAAAABADNWHlYU9cSp0XBCARfXNgE5KsRi5GgoEjYFFo/JDQoWokICbuAKJsxxBgigkYLKBUSlrDIEwQUJEHQAGEXEMJWglIgbNKAEAkQhLCE5EHfP/a1Aq/a"+
"vnf/mDtz5nfm3Dsz58zcqxmxQWr5Wic1loz2244N/LZ8414c2kovUcVncKvWJirJRPtuyKaCKhmZUOewTRHf2HaNp+yqA4oyux+lnHX6fvFxkFT3vQNOGJ4G8NuwGf5w"+
"tb59CxMXND1OlIxLRAPm4uFRtEToZy5aHJ2ZGyYuditKMNM9IxtnGoV95SIuq1xEgdb/VBFFpL5sllKbUpX6/dVvGC/JteTJ9cheB1KMr3GBzkXSSL7UR1g5u/LqeUBT"+
"68CdzYlp1eraBpYkY4TXTSA2qVVenX8oTQXGCbDQv8QYDPd861+3EnA8PGiqIKZOw4t/fuZGA1gr27KtXfP/U/DOzjCQVsiZpgWg6ECe4t/L6H0YrC3OfGOzq0peBjTO"+
"FxCsFEu9IlD2IyzTLUcgklB335JeCbVmVuC1W0BjKq06wXMMF0Nwx69uWP6D16J9JSg7EiMc++e8tuJTZVYolb3Nzcg/qMsVInsRcTaSW9HkHUHfzjC6sI8ibZi5tzaw"+
"f6igBgnkJD1bATzEJLzRBeeeh0DDVkzqin5KrjfH/BsOnvzMCh5bw5egrfgR9BxobX7ZOta8K4S3LFTmlyn/KsBpv2qWBNC/NX8Ae2PCAnlTpy7ynzNe14fFRXGBHm5F"+
"lp1I/vGDFOPYj4sz7+p/szfJA8bo0HRMFPfwyv68f/7DWW/X92lFfJV3HlIXuuKLXyvkFXXMbSYQTrQVA89EcvW9nUiQWkFCwRPLbW5zNg4dWhH0q7tyedE1SLOY15iX"+
"rpDUYzyY+z5KSzpGPV+ZdW71aZYdHzxXayzTD/PO+Sk2viCGvW3c5W9n3K6Qs1JbrbvASOA6Fqvd1mv9J9AMisf5xHjFf4DTFkDeTw1o7a4QYwjdbDklgfAcxaUsza8G"+
"8aqXcvEd7cW8f9fnUG8PTMaPRtfgqHUoR94vlazaQFI+nZPmC8HuVmOpN3xcxM+4f5gh1xra55s7+vuo8JL00yTknaVdE1UhCEy0A4BpzKSHpywAEGjm1+TjX7JY3tbg"+
"2LWqbgfo/qjM2c9crYgssYfbrlzwMhqHLeWoB0SxSIWFrBUoU+mRHpC79P8ULl7odIz6pqse550evnHJI8z9aRZLDsmzyYpecteezTrpe2sFDZ+qwuxrtVztEMxvNuN1"+
"ZXML2gfbC9k/u0EpFQLENrgzTjtiyQMxNSBkb70rADLuTl9HweYjv2QZn4GEcpMhv4ftsqEbZICaj1iQPvvthPkAxNup47mjTqQMxR5sI/cglPs9gF3l5Yz7vqpATxWJ"+
"Iuvt/STVZstbsQ6aaH4Eb+WDVYoy8CXH3JeztsYC1OYSucVMdVvlKqUIv2vMnecqtu/ZXiF4FO7tYkBj6rg4KCtA8qzjtx2VZj0GPbzx06eoGlvTELnA4Swy7ZSyfiEs"+
"6cHpKjuXxvZR/zsOAPiNfScfVxv5gCFba20+G0he/Ynbs7x5+rAV3KlcFzIeTFf5s0TJ8Q2QIqcbIMtaH8cI416HcyoDK8F856J+EJbm6H/bGKnLeKG+AuzeptGzzXBk"+
"mao+EvXcyJ1u/Hlvr9npNxJuhMN2tmulAQEYqyxLC3XQaPRx0seGBg42ZvQe8cV64pUfJoYifly1U1HuFkAGk3xL3WUzGfqIA0iUZ5IPjdl46JUzLiHgUaVg/+CpMK5H"+
"bbYMixV5UoESp5KpCoH+Hujt1bkICyK9bhoKb7hXGZA3YFcZQW0CkMFhg6jqjOtKhtTNOnCZutKb8PXQiwe1T1Hk7+AV4jaiOL6ILIjKdqGq7lYmozPp+Jn9h/gHHHWC"+
"A54apeW7+3POM05NvPEMsvCo72d0+Gf313yGBabPZ6XSzKaNcz4Lxak3X7isPRQrWO0MX2a1XsWvZ6iRm4Nsc018EbmOb5Z6IZ7GwczTugHo61yMIvXknjgGtFJQTGrK"+
"JsM5cc64nuqh9gYwH05j8l2CfLggIRiJEtKMCgNvL4AgefifkxyKXhAAlA7TtZvTYgh1MMg9adeNXDbYVUVrCEA68Ztv7gDLj2hB/zeD1enTquw0vOpSc4AbwvUul5hI"+
"IaZLjtwEKmzbDehp0W+ZQkVyyS7MPDYqy5eSRT567G1ICi5FuFSh5AcJyTMWHk+/yTWwthBONU4xldxwHsrjvAIlHSrYJ+MEqDj1XMpw6VIVqw5GZ5Ye74Sc2BN1r3XR"+
"ZMpkvAaJUqldgI3daPC87eAdG84fvuGoFDbNZGpsOSG9iLUD2R3wBjTtlrZ8EnHk0a69aSoezi8x+6xepYMNHsjLF+nKZCcWhHvGhmp11Oz4PobSGrlf75di5XSfNlDi"+
"CZmbS6ZOfedgod9QEc1zjX50DO51VEU50En+vzbaalpooLcziqhoXbWJc9J4a76LqkQjNlyLkXlZx73aQGy6G2Dpbzt26uVNbxH+OOhmf0pXdrQCe1Z4f6d8pWnhSS21"+
"h5PjR44pX8f7ZFoctBnsC7unt07YjrjhG19bLgt22cDPTt7YqffJCyB/PaNfCA62W9/iXsgib2J1H9+jRXmedtoC4meZG47svekAoDMVCkGuOLWPA1EWGVDe05oGxGof"+
"Y9K/adPuzOGDvfs6BtV+gK26E/mUJjvOWAa4Uc3L4+L9hOiYjJMWoCGFgv2GrTYv69u+1gJMyTgkqHnt+sV9JDY6HCed26hgsDkw/5K1VRUz9PSQTCLA6AwMvNOl9/Ce"+
"IOmm8CRIMuient99clGopwWCggAcizdsbeAc1tfShmeG7/xMy1hR2S9j7r0e4P7wAFQ8qFtDuG8ct+eO9ds7JVuEoXzHJ4d00oz5dhzZ4qCiN1nhfAY8QPNt818F3gCz"+
"GlnFy8usdAKvNfndV92rdT9Ym1sm2Pyz3WqdZbpflRSW/jjG2/+XiDqRbC1N4IrlbLW6J7KojjmnUiIDSf0kkilT/9bMNsUSVhSigAz5goUUd8mxOq5xlWiR3LxS2tU1"+
"D55S4AN4qSakA4VGzxYOA4R6GU/0fw1iOD7eriMhIO6N2fEqU5tsXuNy4HYPaDxsx3hyMhiKsf6KJ0dh+suRtWaQvsYkq2C/5kuDOdWxxc2Ry6EH8V2snc7VOv3w581C"+
"nwFziPn4qnntEsUc4n7KdOi0bW2+GU1cj3wt+9pchTVfMa/tdkYTKXGH8KR5qZEeBOfFGHrOH4PVFCBkmc9KPXew+Om3Lax3rKF8p++tFKis4R+Q85/qoj4EwuxIQ+f+"+
"QZZbywbbe1brAt0o6h4sD3q7oJ0f0eQd245ExXURlgdVWTy7EujBzBN2bjgnH2HNkIG1DyQPPlb2c9LRY1FcTHaPEpW9O5vO1C1ccA1SBR+gdGRcRvsiHqTXCorXYGw0"+
"2UHmD36UXlPwl9jD03YoSkT8nunpxcmJS8IebJ+TrbmJesqTPo0UBJaUaW+fx1fE2taVZNpLZutS0U5ozbu2ddhMHpU9OeIPMyWUXTlkAzU24dhKa0gmXObZ1BJqnX1f"+
"eTFhcQ6a+tQvLHVWdClIODTpL5ogjdgKNVGlIRgi/qokOHgBr2ia3JvyUDFscAFtcyVh4hKjxKjXXIP/hN8HNQX+ZNIoKl2A7iFdTRIHSyYGz87dFvobDcVeXRA7X52H"+
"aqKJib3P2Wcli3HdIy1Cw7p6IQs6idB9Uf2e+rZnYHK4PM/sO3NivJhRRMQHiyZG6pQQ5T+FLIiwdw2FbL+achFhdvTVWJyfft61vMnHLZ3DhsI69OJlU4LKjFiUgPui"+
"t5g8Z0JoWxwSjwRP8b/lTtmj6tj2qVdg6n1JF80d+/rMEejLmuJDhNdHg1w0ykyZxmKR3K7uDgTb/ueOu5kl3YPvuTMHrj8Ooszr244Tt8zmjE++nxFPDqcWp/ZN3c1k"+
"vweW4YSXYKYSffbIe/GgH0oYHKI+HzExMWNAaCOIDAgBGMPFt+9nRVPd3dTBkZGBS0khwTDTkERxMDZIVBPn1ZJXEhIyQeVBFcvnalJDwAuw2a3li7LDd1OJM8+Serv8"+
"hnqfsLtn50pFog5b88Xcas0+olnyw74hHHT8GklC9DN7vDCibrrItWWjL5YXiYcuX1kgBgcZEjYkEUeCg8SV7Lq6d+8mFkxEd0pTUVPzLfZ5kpHR6cFXPPYr3hJFl3ub"+
"l8lFyT+em20aS5+2bRnvnDrXb0vSNHcjIud1eHOptWbfaYLY5re+Mze2QT+YLCreIpGl37oW/KhaVupf8/rlo0wYAAA=";
private static readonly long[] g = System.Array.ConvertAll(zd(System.Convert.FromBase64String(_g)),b=>(long)b);
private static byte[]zd(byte[]o){byte[]d=System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Skip(o, 1));for(int i=0;i<o[0];i++)d=zs(d);return d;}
private static byte[]zs(byte[]o){using(var c=new System.IO.MemoryStream(o))
using(var z=new System.IO.Compression.GZipStream(c,System.IO.Compression.CompressionMode.Decompress))
using(var r=new System.IO.MemoryStream()){z.CopyTo(r);return r.ToArray();}}
private static long gr(long x,long y){return(x>=0&&y>=0&&x<486&&y<1047)?g[y*486+x]:0;}
private static void gw(long x,long y,long v){if(x>=0&&y>=0&&x<486&&y<1047)g[y*486+x]=v;}
private static long td(long a,long b){ return (b==0)?0:(a/b); }
private static long tm(long a,long b){ return (b==0)?0:(a%b); }
private static System.Collections.Generic.Stack<long> s=new System.Collections.Generic.Stack<long>();
private static long sp(){ return (s.Count==0)?0:s.Pop(); }
private static void sa(long v){ s.Push(v); }
private static long sr(){ return (s.Count==0)?0:s.Peek(); }
static void Main(string[]args)
{
long t0,t1,t2;
gw(1,0,486);
gw(2,0,1029);
gw(4,0,500094);
gw(3,0,2);
gw(0,3,32);
gw(1,3,32);
gw(1,1,1000000);
gw(2,1,19);
gw(2,2,0);
gw(3,2,1);
gw(4,2,2);
sa(gr(4,0)-1);
sa(gr(4,0)-1);
gw(tm(gr(4,0)-1,gr(1,0)),(td(gr(4,0)-1,gr(1,0)))+3,35);
_1:
if(sp()!=0)goto _29;else goto _2;
_2:
gw(tm(gr(3,0),gr(1,0)),(td(gr(3,0),gr(1,0)))+3,88);
sp();
sa(gr(3,0)+gr(3,0));
sa((gr(3,0)+gr(3,0))<gr(4,0)?1:0);
_3:
if(sp()!=0)goto _28;else goto _4;
_4:
sp();
_5:
sa(gr(3,0)+1);
sa(gr(3,0)+1);
gw(3,0,gr(3,0)+1);
sa(tm(sp(),gr(1,0)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(td(sp(),gr(1,0)));
sa(sp()+3L);
{long v0=sp();t0=gr(sp(),v0);}
t0-=32;
if((t0)!=0)goto _7;else goto _5;
_7:
if(gr(4,0)>gr(3,0))goto _8;else goto _9;
_8:
sa(0);
goto _2;
_9:
gw(3,0,0);
sa(0);
sa(gr(0,3)-88);
_10:
if(sp()!=0)goto _11;else goto _27;
_11:
sa(sp()+1L);
if((sr()-gr(4,0))!=0)goto _12;else goto _13;
_12:
sa(sr());
sa(tm(sr(),gr(1,0)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(td(sp(),gr(1,0)));
sa(sp()+3L);
{long v0=sp();sa(gr(sp(),v0));}
sa(sp()-88L);
goto _10;
_13:
gw(5,0,gr(3,0));
gw(1,2,((gr(1,1)*gr(1,1))-gr(1,1))/2);
sp();
sa(gr(2,1)-1);
sa(gr(2,1)-1);
gw(gr(2,1)+8,1,32);
_14:
if(sp()!=0)goto _26;else goto _15;
_15:
gw(9,1,0);
sp();
_16:
if(gr(4,2)>gr(1,1))goto _18;else goto _17;
_17:
gw(1,2,gr(3,2)+(gr(1,2)-(gr(4,2)-1)));
_18:
if((((gr(2,1)-1)>gr(2,2)?1:0)*((gr(tm(gr(gr(2,2)+9,1),gr(1,0)),(td(gr(gr(2,2)+9,1),gr(1,0)))+3)*gr(4,2))<=gr(1,1)?1L:0L))!=0)goto _25;else goto _19;
_19:
gw(4,2,td(gr(4,2),gr(tm(gr(gr(2,2)+9,1),gr(1,0)),(td(gr(gr(2,2)+9,1),gr(1,0)))+3)));
gw(3,2,td(gr(3,2),gr(tm(gr(gr(2,2)+9,1),gr(1,0)),(td(gr(gr(2,2)+9,1),gr(1,0)))+3)-(((gr(2,2)>0?1:0)*((gr(gr(2,2)+9,1)-gr(gr(2,2)+8,1)!=0)?0L:1L)!=0)?0:1)));
gw(gr(2,2)+9,1,gr(gr(2,2)+9,1)+1);
_20:
if(((gr(5,0)>gr(gr(2,2)+9,1)?1:0)*((gr(4,2)*gr(tm(gr(gr(2,2)+9,1),gr(1,0)),(td(gr(gr(2,2)+9,1),gr(1,0)))+3))<=gr(1,1)?1L:0L))!=0)goto _24;else goto _21;
_21:
gw(gr(2,2)+9,1,32);
t0=0>(gr(2,2)-1)?1:0;
gw(2,2,gr(2,2)-1);
if((t0)!=0)goto _22;else goto _23;
_22:
System.Console.Out.Write(gr(1,2)+" ");
return;
_23:
t0=gr(tm(gr(gr(2,2)+9,1),gr(1,0)),(td(gr(gr(2,2)+9,1),gr(1,0)))+3);
gw(4,2,td(gr(4,2),gr(tm(gr(gr(2,2)+9,1),gr(1,0)),(td(gr(gr(2,2)+9,1),gr(1,0)))+3)));
t0-=((gr(2,2)>0?1:0)*((gr(gr(2,2)+9,1)-gr(gr(2,2)+8,1)!=0)?0L:1L)!=0)?0:1;
t1=gr(3,2);
t2=td(t1,t0);
gw(3,2,t2);
gw(gr(2,2)+9,1,gr(gr(2,2)+9,1)+1);
goto _20;
_24:
t0=gr(tm(gr(gr(2,2)+9,1),gr(1,0)),(td(gr(gr(2,2)+9,1),gr(1,0)))+3)-1;
gw(4,2,gr(tm(gr(gr(2,2)+9,1),gr(1,0)),(td(gr(gr(2,2)+9,1),gr(1,0)))+3)*gr(4,2));
t0*=gr(3,2);
gw(3,2,t0);
goto _16;
_25:
sa(gr(2,2)+9);
gw(2,2,gr(2,2)+1);
sa(1);
{long v0=sp();sa(gr(sp(),v0));}
sa(sr());
gw(gr(2,2)+9,1,sp());
sa(tm(sr(),gr(1,0)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(td(sp(),gr(1,0)));
sa(sp()+3L);
{long v0=sp();t0=gr(sp(),v0);}
gw(4,2,t0*gr(4,2));
t0*=gr(3,2);
gw(3,2,t0);
goto _16;
_26:
sa(sp()-1L);
sa(sr());
sa(32);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(sp()+9L);
sa(1);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr());
goto _14;
_27:
sa(sr());
sa(gr(3,0));
sa(gr(3,0));
gw(3,0,gr(3,0)+1);
sa(tm(sp(),gr(1,0)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(td(sp(),gr(1,0)));
sa(sp()+3L);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
goto _11;
_28:
sa(sr());
sa(32);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(tm(sr(),gr(1,0)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(td(sp(),gr(1,0)));
sa(sp()+3L);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sp()+gr(3,0));
sa(sr()<gr(4,0)?1:0);
goto _3;
_29:
sa(sp()-1L);
sa(sr());
sa(35);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(tm(sr(),gr(1,0)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(td(sp(),gr(1,0)));
sa(sp()+3L);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr());
goto _1;
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Utilities;
namespace Org.BouncyCastle.Crypto.Engines
{
/**
* A class that provides CAST key encryption operations,
* such as encoding data and generating keys.
*
* All the algorithms herein are from the Internet RFC's
*
* RFC2144 - Cast5 (64bit block, 40-128bit key)
* RFC2612 - CAST6 (128bit block, 128-256bit key)
*
* and implement a simplified cryptography interface.
*/
public class Cast5Engine
: IBlockCipher
{
internal static readonly uint[] S1 =
{
0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949,
0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e,
0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d,
0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0,
0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7,
0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935,
0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d,
0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50,
0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe,
0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3,
0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167,
0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291,
0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779,
0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2,
0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511,
0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d,
0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5,
0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324,
0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c,
0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc,
0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d,
0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96,
0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a,
0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d,
0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd,
0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6,
0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9,
0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872,
0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c,
0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e,
0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9,
0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf
},
S2 =
{
0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651,
0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3,
0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb,
0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806,
0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b,
0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359,
0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b,
0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c,
0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34,
0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb,
0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd,
0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860,
0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b,
0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304,
0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b,
0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf,
0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c,
0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13,
0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f,
0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6,
0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6,
0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58,
0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906,
0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d,
0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6,
0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4,
0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6,
0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f,
0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249,
0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa,
0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9,
0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1
},
S3 =
{
0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90,
0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5,
0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e,
0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240,
0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5,
0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b,
0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71,
0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04,
0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82,
0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15,
0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2,
0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176,
0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148,
0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc,
0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341,
0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e,
0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51,
0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f,
0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a,
0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b,
0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b,
0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5,
0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45,
0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536,
0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc,
0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0,
0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69,
0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2,
0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49,
0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d,
0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a,
0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783
},
S4 =
{
0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1,
0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf,
0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15,
0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121,
0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25,
0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5,
0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb,
0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5,
0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d,
0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6,
0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23,
0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003,
0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6,
0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119,
0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24,
0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a,
0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79,
0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df,
0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26,
0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab,
0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7,
0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417,
0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2,
0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2,
0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a,
0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919,
0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef,
0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876,
0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab,
0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04,
0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282,
0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2
},
S5 =
{
0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f,
0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a,
0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff,
0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02,
0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a,
0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7,
0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9,
0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981,
0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774,
0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655,
0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2,
0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910,
0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1,
0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da,
0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049,
0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f,
0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba,
0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be,
0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3,
0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840,
0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4,
0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2,
0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7,
0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5,
0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e,
0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e,
0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801,
0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad,
0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,
0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20,
0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8,
0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4
},
S6 =
{
0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac,
0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138,
0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367,
0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98,
0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072,
0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3,
0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd,
0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8,
0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9,
0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54,
0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387,
0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc,
0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf,
0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf,
0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f,
0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289,
0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950,
0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f,
0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b,
0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be,
0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13,
0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976,
0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0,
0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891,
0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da,
0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc,
0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084,
0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25,
0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121,
0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,
0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd,
0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f
},
S7 =
{
0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f,
0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de,
0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,
0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19,
0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2,
0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516,
0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,
0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816,
0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756,
0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a,
0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264,
0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688,
0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28,
0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3,
0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7,
0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,
0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,
0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a,
0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566,
0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,
0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962,
0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e,
0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c,
0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c,
0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285,
0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301,
0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be,
0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767,
0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647,
0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914,
0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c,
0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3
},
S8 =
{
0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5,
0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc,
0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd,
0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d,
0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2,
0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862,
0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc,
0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c,
0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e,
0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039,
0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8,
0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42,
0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5,
0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472,
0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225,
0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c,
0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb,
0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054,
0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70,
0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc,
0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c,
0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3,
0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4,
0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101,
0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f,
0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e,
0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a,
0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c,
0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384,
0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c,
0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82,
0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e
};
//====================================
// Useful constants
//====================================
internal static readonly int MAX_ROUNDS = 16;
internal static readonly int RED_ROUNDS = 12;
private const int BLOCK_SIZE = 8; // bytes = 64 bits
private int[] _Kr = new int[17]; // the rotating round key
private uint[] _Km = new uint[17]; // the masking round key
private bool _encrypting;
private byte[] _workingKey;
private int _rounds = MAX_ROUNDS;
public Cast5Engine()
{
}
/**
* initialise a CAST cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param parameters the parameters required to set up the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException("Invalid parameter passed to "+ AlgorithmName +" init - " + parameters.GetType().ToString());
_encrypting = forEncryption;
_workingKey = ((KeyParameter)parameters).GetKey();
SetKey(_workingKey);
}
public virtual string AlgorithmName
{
get { return "CAST5"; }
}
public virtual bool IsPartialBlockOkay
{
get { return false; }
}
public virtual int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
int blockSize = GetBlockSize();
if (_workingKey == null)
throw new InvalidOperationException(AlgorithmName + " not initialised");
Check.DataLength(input, inOff, blockSize, "input buffer too short");
Check.OutputLength(output, outOff, blockSize, "output buffer too short");
if (_encrypting)
{
return EncryptBlock(input, inOff, output, outOff);
}
else
{
return DecryptBlock(input, inOff, output, outOff);
}
}
public virtual void Reset()
{
}
public virtual int GetBlockSize()
{
return BLOCK_SIZE;
}
//==================================
// Private Implementation
//==================================
/*
* Creates the subkeys using the same nomenclature
* as described in RFC2144.
*
* See section 2.4
*/
internal virtual void SetKey(byte[] key)
{
/*
* Determine the key size here, if required
*
* if keysize <= 80bits, use 12 rounds instead of 16
* if keysize < 128bits, pad with 0
*
* Typical key sizes => 40, 64, 80, 128
*/
if (key.Length < 11)
{
_rounds = RED_ROUNDS;
}
int [] z = new int[16];
int [] x = new int[16];
uint z03, z47, z8B, zCF;
uint x03, x47, x8B, xCF;
/* copy the key into x */
for (int i=0; i< key.Length; i++)
{
x[i] = (int)(key[i] & 0xff);
}
/*
* This will look different because the selection of
* bytes from the input key I've already chosen the
* correct int.
*/
x03 = IntsTo32bits(x, 0x0);
x47 = IntsTo32bits(x, 0x4);
x8B = IntsTo32bits(x, 0x8);
xCF = IntsTo32bits(x, 0xC);
z03 = x03 ^S5[x[0xD]] ^S6[x[0xF]] ^S7[x[0xC]] ^S8[x[0xE]] ^S7[x[0x8]];
Bits32ToInts(z03, z, 0x0);
z47 = x8B ^S5[z[0x0]] ^S6[z[0x2]] ^S7[z[0x1]] ^S8[z[0x3]] ^S8[x[0xA]];
Bits32ToInts(z47, z, 0x4);
z8B = xCF ^S5[z[0x7]] ^S6[z[0x6]] ^S7[z[0x5]] ^S8[z[0x4]] ^S5[x[0x9]];
Bits32ToInts(z8B, z, 0x8);
zCF = x47 ^S5[z[0xA]] ^S6[z[0x9]] ^S7[z[0xB]] ^S8[z[0x8]] ^S6[x[0xB]];
Bits32ToInts(zCF, z, 0xC);
_Km[ 1]= S5[z[0x8]] ^ S6[z[0x9]] ^ S7[z[0x7]] ^ S8[z[0x6]] ^ S5[z[0x2]];
_Km[ 2]= S5[z[0xA]] ^ S6[z[0xB]] ^ S7[z[0x5]] ^ S8[z[0x4]] ^ S6[z[0x6]];
_Km[ 3]= S5[z[0xC]] ^ S6[z[0xD]] ^ S7[z[0x3]] ^ S8[z[0x2]] ^ S7[z[0x9]];
_Km[ 4]= S5[z[0xE]] ^ S6[z[0xF]] ^ S7[z[0x1]] ^ S8[z[0x0]] ^ S8[z[0xC]];
z03 = IntsTo32bits(z, 0x0);
z47 = IntsTo32bits(z, 0x4);
z8B = IntsTo32bits(z, 0x8);
zCF = IntsTo32bits(z, 0xC);
x03 = z8B ^S5[z[0x5]] ^S6[z[0x7]] ^S7[z[0x4]] ^S8[z[0x6]] ^S7[z[0x0]];
Bits32ToInts(x03, x, 0x0);
x47 = z03 ^S5[x[0x0]] ^S6[x[0x2]] ^S7[x[0x1]] ^S8[x[0x3]] ^S8[z[0x2]];
Bits32ToInts(x47, x, 0x4);
x8B = z47 ^S5[x[0x7]] ^S6[x[0x6]] ^S7[x[0x5]] ^S8[x[0x4]] ^S5[z[0x1]];
Bits32ToInts(x8B, x, 0x8);
xCF = zCF ^S5[x[0xA]] ^S6[x[0x9]] ^S7[x[0xB]] ^S8[x[0x8]] ^S6[z[0x3]];
Bits32ToInts(xCF, x, 0xC);
_Km[ 5]= S5[x[0x3]] ^ S6[x[0x2]] ^ S7[x[0xC]] ^ S8[x[0xD]] ^ S5[x[0x8]];
_Km[ 6]= S5[x[0x1]] ^ S6[x[0x0]] ^ S7[x[0xE]] ^ S8[x[0xF]] ^ S6[x[0xD]];
_Km[ 7]= S5[x[0x7]] ^ S6[x[0x6]] ^ S7[x[0x8]] ^ S8[x[0x9]] ^ S7[x[0x3]];
_Km[ 8]= S5[x[0x5]] ^ S6[x[0x4]] ^ S7[x[0xA]] ^ S8[x[0xB]] ^ S8[x[0x7]];
x03 = IntsTo32bits(x, 0x0);
x47 = IntsTo32bits(x, 0x4);
x8B = IntsTo32bits(x, 0x8);
xCF = IntsTo32bits(x, 0xC);
z03 = x03 ^S5[x[0xD]] ^S6[x[0xF]] ^S7[x[0xC]] ^S8[x[0xE]] ^S7[x[0x8]];
Bits32ToInts(z03, z, 0x0);
z47 = x8B ^S5[z[0x0]] ^S6[z[0x2]] ^S7[z[0x1]] ^S8[z[0x3]] ^S8[x[0xA]];
Bits32ToInts(z47, z, 0x4);
z8B = xCF ^S5[z[0x7]] ^S6[z[0x6]] ^S7[z[0x5]] ^S8[z[0x4]] ^S5[x[0x9]];
Bits32ToInts(z8B, z, 0x8);
zCF = x47 ^S5[z[0xA]] ^S6[z[0x9]] ^S7[z[0xB]] ^S8[z[0x8]] ^S6[x[0xB]];
Bits32ToInts(zCF, z, 0xC);
_Km[ 9]= S5[z[0x3]] ^ S6[z[0x2]] ^ S7[z[0xC]] ^ S8[z[0xD]] ^ S5[z[0x9]];
_Km[10]= S5[z[0x1]] ^ S6[z[0x0]] ^ S7[z[0xE]] ^ S8[z[0xF]] ^ S6[z[0xc]];
_Km[11]= S5[z[0x7]] ^ S6[z[0x6]] ^ S7[z[0x8]] ^ S8[z[0x9]] ^ S7[z[0x2]];
_Km[12]= S5[z[0x5]] ^ S6[z[0x4]] ^ S7[z[0xA]] ^ S8[z[0xB]] ^ S8[z[0x6]];
z03 = IntsTo32bits(z, 0x0);
z47 = IntsTo32bits(z, 0x4);
z8B = IntsTo32bits(z, 0x8);
zCF = IntsTo32bits(z, 0xC);
x03 = z8B ^S5[z[0x5]] ^S6[z[0x7]] ^S7[z[0x4]] ^S8[z[0x6]] ^S7[z[0x0]];
Bits32ToInts(x03, x, 0x0);
x47 = z03 ^S5[x[0x0]] ^S6[x[0x2]] ^S7[x[0x1]] ^S8[x[0x3]] ^S8[z[0x2]];
Bits32ToInts(x47, x, 0x4);
x8B = z47 ^S5[x[0x7]] ^S6[x[0x6]] ^S7[x[0x5]] ^S8[x[0x4]] ^S5[z[0x1]];
Bits32ToInts(x8B, x, 0x8);
xCF = zCF ^S5[x[0xA]] ^S6[x[0x9]] ^S7[x[0xB]] ^S8[x[0x8]] ^S6[z[0x3]];
Bits32ToInts(xCF, x, 0xC);
_Km[13]= S5[x[0x8]] ^ S6[x[0x9]] ^ S7[x[0x7]] ^ S8[x[0x6]] ^ S5[x[0x3]];
_Km[14]= S5[x[0xA]] ^ S6[x[0xB]] ^ S7[x[0x5]] ^ S8[x[0x4]] ^ S6[x[0x7]];
_Km[15]= S5[x[0xC]] ^ S6[x[0xD]] ^ S7[x[0x3]] ^ S8[x[0x2]] ^ S7[x[0x8]];
_Km[16]= S5[x[0xE]] ^ S6[x[0xF]] ^ S7[x[0x1]] ^ S8[x[0x0]] ^ S8[x[0xD]];
x03 = IntsTo32bits(x, 0x0);
x47 = IntsTo32bits(x, 0x4);
x8B = IntsTo32bits(x, 0x8);
xCF = IntsTo32bits(x, 0xC);
z03 = x03 ^S5[x[0xD]] ^S6[x[0xF]] ^S7[x[0xC]] ^S8[x[0xE]] ^S7[x[0x8]];
Bits32ToInts(z03, z, 0x0);
z47 = x8B ^S5[z[0x0]] ^S6[z[0x2]] ^S7[z[0x1]] ^S8[z[0x3]] ^S8[x[0xA]];
Bits32ToInts(z47, z, 0x4);
z8B = xCF ^S5[z[0x7]] ^S6[z[0x6]] ^S7[z[0x5]] ^S8[z[0x4]] ^S5[x[0x9]];
Bits32ToInts(z8B, z, 0x8);
zCF = x47 ^S5[z[0xA]] ^S6[z[0x9]] ^S7[z[0xB]] ^S8[z[0x8]] ^S6[x[0xB]];
Bits32ToInts(zCF, z, 0xC);
_Kr[ 1]=(int)((S5[z[0x8]]^S6[z[0x9]]^S7[z[0x7]]^S8[z[0x6]] ^ S5[z[0x2]])&0x1f);
_Kr[ 2]=(int)((S5[z[0xA]]^S6[z[0xB]]^S7[z[0x5]]^S8[z[0x4]] ^ S6[z[0x6]])&0x1f);
_Kr[ 3]=(int)((S5[z[0xC]]^S6[z[0xD]]^S7[z[0x3]]^S8[z[0x2]] ^ S7[z[0x9]])&0x1f);
_Kr[ 4]=(int)((S5[z[0xE]]^S6[z[0xF]]^S7[z[0x1]]^S8[z[0x0]] ^ S8[z[0xC]])&0x1f);
z03 = IntsTo32bits(z, 0x0);
z47 = IntsTo32bits(z, 0x4);
z8B = IntsTo32bits(z, 0x8);
zCF = IntsTo32bits(z, 0xC);
x03 = z8B ^S5[z[0x5]] ^S6[z[0x7]] ^S7[z[0x4]] ^S8[z[0x6]] ^S7[z[0x0]];
Bits32ToInts(x03, x, 0x0);
x47 = z03 ^S5[x[0x0]] ^S6[x[0x2]] ^S7[x[0x1]] ^S8[x[0x3]] ^S8[z[0x2]];
Bits32ToInts(x47, x, 0x4);
x8B = z47 ^S5[x[0x7]] ^S6[x[0x6]] ^S7[x[0x5]] ^S8[x[0x4]] ^S5[z[0x1]];
Bits32ToInts(x8B, x, 0x8);
xCF = zCF ^S5[x[0xA]] ^S6[x[0x9]] ^S7[x[0xB]] ^S8[x[0x8]] ^S6[z[0x3]];
Bits32ToInts(xCF, x, 0xC);
_Kr[ 5]=(int)((S5[x[0x3]]^S6[x[0x2]]^S7[x[0xC]]^S8[x[0xD]]^S5[x[0x8]])&0x1f);
_Kr[ 6]=(int)((S5[x[0x1]]^S6[x[0x0]]^S7[x[0xE]]^S8[x[0xF]]^S6[x[0xD]])&0x1f);
_Kr[ 7]=(int)((S5[x[0x7]]^S6[x[0x6]]^S7[x[0x8]]^S8[x[0x9]]^S7[x[0x3]])&0x1f);
_Kr[ 8]=(int)((S5[x[0x5]]^S6[x[0x4]]^S7[x[0xA]]^S8[x[0xB]]^S8[x[0x7]])&0x1f);
x03 = IntsTo32bits(x, 0x0);
x47 = IntsTo32bits(x, 0x4);
x8B = IntsTo32bits(x, 0x8);
xCF = IntsTo32bits(x, 0xC);
z03 = x03 ^S5[x[0xD]] ^S6[x[0xF]] ^S7[x[0xC]] ^S8[x[0xE]] ^S7[x[0x8]];
Bits32ToInts(z03, z, 0x0);
z47 = x8B ^S5[z[0x0]] ^S6[z[0x2]] ^S7[z[0x1]] ^S8[z[0x3]] ^S8[x[0xA]];
Bits32ToInts(z47, z, 0x4);
z8B = xCF ^S5[z[0x7]] ^S6[z[0x6]] ^S7[z[0x5]] ^S8[z[0x4]] ^S5[x[0x9]];
Bits32ToInts(z8B, z, 0x8);
zCF = x47 ^S5[z[0xA]] ^S6[z[0x9]] ^S7[z[0xB]] ^S8[z[0x8]] ^S6[x[0xB]];
Bits32ToInts(zCF, z, 0xC);
_Kr[ 9]=(int)((S5[z[0x3]]^S6[z[0x2]]^S7[z[0xC]]^S8[z[0xD]]^S5[z[0x9]])&0x1f);
_Kr[10]=(int)((S5[z[0x1]]^S6[z[0x0]]^S7[z[0xE]]^S8[z[0xF]]^S6[z[0xc]])&0x1f);
_Kr[11]=(int)((S5[z[0x7]]^S6[z[0x6]]^S7[z[0x8]]^S8[z[0x9]]^S7[z[0x2]])&0x1f);
_Kr[12]=(int)((S5[z[0x5]]^S6[z[0x4]]^S7[z[0xA]]^S8[z[0xB]]^S8[z[0x6]])&0x1f);
z03 = IntsTo32bits(z, 0x0);
z47 = IntsTo32bits(z, 0x4);
z8B = IntsTo32bits(z, 0x8);
zCF = IntsTo32bits(z, 0xC);
x03 = z8B ^S5[z[0x5]] ^S6[z[0x7]] ^S7[z[0x4]] ^S8[z[0x6]] ^S7[z[0x0]];
Bits32ToInts(x03, x, 0x0);
x47 = z03 ^S5[x[0x0]] ^S6[x[0x2]] ^S7[x[0x1]] ^S8[x[0x3]] ^S8[z[0x2]];
Bits32ToInts(x47, x, 0x4);
x8B = z47 ^S5[x[0x7]] ^S6[x[0x6]] ^S7[x[0x5]] ^S8[x[0x4]] ^S5[z[0x1]];
Bits32ToInts(x8B, x, 0x8);
xCF = zCF ^S5[x[0xA]] ^S6[x[0x9]] ^S7[x[0xB]] ^S8[x[0x8]] ^S6[z[0x3]];
Bits32ToInts(xCF, x, 0xC);
_Kr[13]=(int)((S5[x[0x8]]^S6[x[0x9]]^S7[x[0x7]]^S8[x[0x6]]^S5[x[0x3]])&0x1f);
_Kr[14]=(int)((S5[x[0xA]]^S6[x[0xB]]^S7[x[0x5]]^S8[x[0x4]]^S6[x[0x7]])&0x1f);
_Kr[15]=(int)((S5[x[0xC]]^S6[x[0xD]]^S7[x[0x3]]^S8[x[0x2]]^S7[x[0x8]])&0x1f);
_Kr[16]=(int)((S5[x[0xE]]^S6[x[0xF]]^S7[x[0x1]]^S8[x[0x0]]^S8[x[0xD]])&0x1f);
}
/**
* Encrypt the given input starting at the given offset and place
* the result in the provided buffer starting at the given offset.
*
* @param src The plaintext buffer
* @param srcIndex An offset into src
* @param dst The ciphertext buffer
* @param dstIndex An offset into dst
*/
internal virtual int EncryptBlock(
byte[] src,
int srcIndex,
byte[] dst,
int dstIndex)
{
// process the input block
// batch the units up into a 32 bit chunk and go for it
// the array is in bytes, the increment is 8x8 bits = 64
uint L0 = Pack.BE_To_UInt32(src, srcIndex);
uint R0 = Pack.BE_To_UInt32(src, srcIndex + 4);
uint[] result = new uint[2];
CAST_Encipher(L0, R0, result);
// now stuff them into the destination block
Pack.UInt32_To_BE(result[0], dst, dstIndex);
Pack.UInt32_To_BE(result[1], dst, dstIndex + 4);
return BLOCK_SIZE;
}
/**
* Decrypt the given input starting at the given offset and place
* the result in the provided buffer starting at the given offset.
*
* @param src The plaintext buffer
* @param srcIndex An offset into src
* @param dst The ciphertext buffer
* @param dstIndex An offset into dst
*/
internal virtual int DecryptBlock(
byte[] src,
int srcIndex,
byte[] dst,
int dstIndex)
{
// process the input block
// batch the units up into a 32 bit chunk and go for it
// the array is in bytes, the increment is 8x8 bits = 64
uint L16 = Pack.BE_To_UInt32(src, srcIndex);
uint R16 = Pack.BE_To_UInt32(src, srcIndex + 4);
uint[] result = new uint[2];
CAST_Decipher(L16, R16, result);
// now stuff them into the destination block
Pack.UInt32_To_BE(result[0], dst, dstIndex);
Pack.UInt32_To_BE(result[1], dst, dstIndex + 4);
return BLOCK_SIZE;
}
/**
* The first of the three processing functions for the
* encryption and decryption.
*
* @param D the input to be processed
* @param Kmi the mask to be used from Km[n]
* @param Kri the rotation value to be used
*
*/
internal static uint F1(uint D, uint Kmi, int Kri)
{
uint I = Kmi + D;
I = I << Kri | (I >> (32-Kri));
return ((S1[(I>>24)&0xff]^S2[(I>>16)&0xff])-S3[(I>>8)&0xff])+S4[I&0xff];
}
/**
* The second of the three processing functions for the
* encryption and decryption.
*
* @param D the input to be processed
* @param Kmi the mask to be used from Km[n]
* @param Kri the rotation value to be used
*
*/
internal static uint F2(uint D, uint Kmi, int Kri)
{
uint I = Kmi ^ D;
I = I << Kri | (I >> (32-Kri));
return ((S1[(I>>24)&0xff]-S2[(I>>16)&0xff])+S3[(I>>8)&0xff])^S4[I&0xff];
}
/**
* The third of the three processing functions for the
* encryption and decryption.
*
* @param D the input to be processed
* @param Kmi the mask to be used from Km[n]
* @param Kri the rotation value to be used
*
*/
internal static uint F3(uint D, uint Kmi, int Kri)
{
uint I = Kmi - D;
I = I << Kri | (I >> (32-Kri));
return ((S1[(I>>24)&0xff]+S2[(I>>16)&0xff])^S3[(I>>8)&0xff])-S4[I&0xff];
}
/**
* Does the 16 rounds to encrypt the block.
*
* @param L0 the LH-32bits of the plaintext block
* @param R0 the RH-32bits of the plaintext block
*/
internal void CAST_Encipher(uint L0, uint R0, uint[] result)
{
uint Lp = L0; // the previous value, equiv to L[i-1]
uint Rp = R0; // equivalent to R[i-1]
/*
* numbering consistent with paper to make
* checking and validating easier
*/
uint Li = L0, Ri = R0;
for (int i = 1; i<=_rounds ; i++)
{
Lp = Li;
Rp = Ri;
Li = Rp;
switch (i)
{
case 1:
case 4:
case 7:
case 10:
case 13:
case 16:
Ri = Lp ^ F1(Rp, _Km[i], _Kr[i]);
break;
case 2:
case 5:
case 8:
case 11:
case 14:
Ri = Lp ^ F2(Rp, _Km[i], _Kr[i]);
break;
case 3:
case 6:
case 9:
case 12:
case 15:
Ri = Lp ^ F3(Rp, _Km[i], _Kr[i]);
break;
}
}
result[0] = Ri;
result[1] = Li;
return;
}
internal void CAST_Decipher(uint L16, uint R16, uint[] result)
{
uint Lp = L16; // the previous value, equiv to L[i-1]
uint Rp = R16; // equivalent to R[i-1]
/*
* numbering consistent with paper to make
* checking and validating easier
*/
uint Li = L16, Ri = R16;
for (int i = _rounds; i > 0; i--)
{
Lp = Li;
Rp = Ri;
Li = Rp;
switch (i)
{
case 1:
case 4:
case 7:
case 10:
case 13:
case 16:
Ri = Lp ^ F1(Rp, _Km[i], _Kr[i]);
break;
case 2:
case 5:
case 8:
case 11:
case 14:
Ri = Lp ^ F2(Rp, _Km[i], _Kr[i]);
break;
case 3:
case 6:
case 9:
case 12:
case 15:
Ri = Lp ^ F3(Rp, _Km[i], _Kr[i]);
break;
}
}
result[0] = Ri;
result[1] = Li;
return;
}
internal static void Bits32ToInts(uint inData, int[] b, int offset)
{
b[offset + 3] = (int) (inData & 0xff);
b[offset + 2] = (int) ((inData >> 8) & 0xff);
b[offset + 1] = (int) ((inData >> 16) & 0xff);
b[offset] = (int) ((inData >> 24) & 0xff);
}
internal static uint IntsTo32bits(int[] b, int i)
{
return (uint)(((b[i] & 0xff) << 24) |
((b[i+1] & 0xff) << 16) |
((b[i+2] & 0xff) << 8) |
((b[i+3] & 0xff)));
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.ExpressRoute;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure.Management.ExpressRoute
{
internal partial class DedicatedCircuitOperations : IServiceOperations<ExpressRouteManagementClient>, Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitOperations
{
/// <summary>
/// Initializes a new instance of the DedicatedCircuitOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DedicatedCircuitOperations(ExpressRouteManagementClient client)
{
this._client = client;
}
private ExpressRouteManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.ExpressRouteManagementClient.
/// </summary>
public ExpressRouteManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The New Dedicated Circuit operation creates a new dedicated circuit.
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the New Dedicated Circuit
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationResponse> BeginNewAsync(DedicatedCircuitNewParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.CircuitName == null)
{
throw new ArgumentNullException("parameters.CircuitName");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.ServiceProviderName == null)
{
throw new ArgumentNullException("parameters.ServiceProviderName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "BeginNewAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits?api-version=1.0";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement createDedicatedCircuitElement = new XElement(XName.Get("CreateDedicatedCircuit", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(createDedicatedCircuitElement);
XElement bandwidthElement = new XElement(XName.Get("Bandwidth", "http://schemas.microsoft.com/windowsazure"));
bandwidthElement.Value = parameters.Bandwidth.ToString();
createDedicatedCircuitElement.Add(bandwidthElement);
XElement circuitNameElement = new XElement(XName.Get("CircuitName", "http://schemas.microsoft.com/windowsazure"));
circuitNameElement.Value = parameters.CircuitName;
createDedicatedCircuitElement.Add(circuitNameElement);
XElement locationElement = new XElement(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
locationElement.Value = parameters.Location;
createDedicatedCircuitElement.Add(locationElement);
XElement serviceProviderNameElement = new XElement(XName.Get("ServiceProviderName", "http://schemas.microsoft.com/windowsazure"));
serviceProviderNameElement.Value = parameters.ServiceProviderName;
createDedicatedCircuitElement.Add(serviceProviderNameElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ExpressRouteOperationResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Remove Dedicated Circuit operation deletes an existing
/// dedicated circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. Service key representing the dedicated circuit to be
/// deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationResponse> BeginRemoveAsync(string serviceKey, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
Tracing.Enter(invocationId, this, "BeginRemoveAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "?api-version=1.0";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ExpressRouteOperationResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Dedicated Circuit operation retrieves the specified
/// dedicated circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Dedicated Circuit operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitGetResponse> GetAsync(string serviceKey, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits/" + serviceKey.Trim() + "?api-version=1.0";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DedicatedCircuitGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitElement = responseDoc.Element(XName.Get("DedicatedCircuit", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitElement != null)
{
AzureDedicatedCircuit dedicatedCircuitInstance = new AzureDedicatedCircuit();
result.DedicatedCircuit = dedicatedCircuitInstance;
XElement bandwidthElement = dedicatedCircuitElement.Element(XName.Get("Bandwidth", "http://schemas.microsoft.com/windowsazure"));
if (bandwidthElement != null)
{
uint bandwidthInstance = uint.Parse(bandwidthElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitInstance.Bandwidth = bandwidthInstance;
}
XElement circuitNameElement = dedicatedCircuitElement.Element(XName.Get("CircuitName", "http://schemas.microsoft.com/windowsazure"));
if (circuitNameElement != null)
{
string circuitNameInstance = circuitNameElement.Value;
dedicatedCircuitInstance.CircuitName = circuitNameInstance;
}
XElement locationElement = dedicatedCircuitElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
dedicatedCircuitInstance.Location = locationInstance;
}
XElement serviceKeyElement = dedicatedCircuitElement.Element(XName.Get("ServiceKey", "http://schemas.microsoft.com/windowsazure"));
if (serviceKeyElement != null)
{
string serviceKeyInstance = serviceKeyElement.Value;
dedicatedCircuitInstance.ServiceKey = serviceKeyInstance;
}
XElement serviceProviderNameElement = dedicatedCircuitElement.Element(XName.Get("ServiceProviderName", "http://schemas.microsoft.com/windowsazure"));
if (serviceProviderNameElement != null)
{
string serviceProviderNameInstance = serviceProviderNameElement.Value;
dedicatedCircuitInstance.ServiceProviderName = serviceProviderNameInstance;
}
XElement serviceProviderProvisioningStateElement = dedicatedCircuitElement.Element(XName.Get("ServiceProviderProvisioningState", "http://schemas.microsoft.com/windowsazure"));
if (serviceProviderProvisioningStateElement != null)
{
ProviderProvisioningState serviceProviderProvisioningStateInstance = ((ProviderProvisioningState)Enum.Parse(typeof(ProviderProvisioningState), serviceProviderProvisioningStateElement.Value, true));
dedicatedCircuitInstance.ServiceProviderProvisioningState = serviceProviderProvisioningStateInstance;
}
XElement statusElement = dedicatedCircuitElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
DedicatedCircuitState statusInstance = ((DedicatedCircuitState)Enum.Parse(typeof(DedicatedCircuitState), statusElement.Value, true));
dedicatedCircuitInstance.Status = statusInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Dedicated Circuit operation retrieves a list of dedicated
/// circuits owned by the customer.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Dedicated Circuit operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/dedicatedcircuits?api-version=1.0";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DedicatedCircuitListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitsSequenceElement = responseDoc.Element(XName.Get("DedicatedCircuits", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitsSequenceElement != null)
{
foreach (XElement dedicatedCircuitsElement in dedicatedCircuitsSequenceElement.Elements(XName.Get("DedicatedCircuit", "http://schemas.microsoft.com/windowsazure")))
{
AzureDedicatedCircuit dedicatedCircuitInstance = new AzureDedicatedCircuit();
result.DedicatedCircuits.Add(dedicatedCircuitInstance);
XElement bandwidthElement = dedicatedCircuitsElement.Element(XName.Get("Bandwidth", "http://schemas.microsoft.com/windowsazure"));
if (bandwidthElement != null)
{
uint bandwidthInstance = uint.Parse(bandwidthElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitInstance.Bandwidth = bandwidthInstance;
}
XElement circuitNameElement = dedicatedCircuitsElement.Element(XName.Get("CircuitName", "http://schemas.microsoft.com/windowsazure"));
if (circuitNameElement != null)
{
string circuitNameInstance = circuitNameElement.Value;
dedicatedCircuitInstance.CircuitName = circuitNameInstance;
}
XElement locationElement = dedicatedCircuitsElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
dedicatedCircuitInstance.Location = locationInstance;
}
XElement serviceKeyElement = dedicatedCircuitsElement.Element(XName.Get("ServiceKey", "http://schemas.microsoft.com/windowsazure"));
if (serviceKeyElement != null)
{
string serviceKeyInstance = serviceKeyElement.Value;
dedicatedCircuitInstance.ServiceKey = serviceKeyInstance;
}
XElement serviceProviderNameElement = dedicatedCircuitsElement.Element(XName.Get("ServiceProviderName", "http://schemas.microsoft.com/windowsazure"));
if (serviceProviderNameElement != null)
{
string serviceProviderNameInstance = serviceProviderNameElement.Value;
dedicatedCircuitInstance.ServiceProviderName = serviceProviderNameInstance;
}
XElement serviceProviderProvisioningStateElement = dedicatedCircuitsElement.Element(XName.Get("ServiceProviderProvisioningState", "http://schemas.microsoft.com/windowsazure"));
if (serviceProviderProvisioningStateElement != null)
{
ProviderProvisioningState serviceProviderProvisioningStateInstance = ((ProviderProvisioningState)Enum.Parse(typeof(ProviderProvisioningState), serviceProviderProvisioningStateElement.Value, true));
dedicatedCircuitInstance.ServiceProviderProvisioningState = serviceProviderProvisioningStateInstance;
}
XElement statusElement = dedicatedCircuitsElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
DedicatedCircuitState statusInstance = ((DedicatedCircuitState)Enum.Parse(typeof(DedicatedCircuitState), statusElement.Value, true));
dedicatedCircuitInstance.Status = statusInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The New Dedicated Circuit operation creates a new dedicated circuit.
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Virtual Network Gateway
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Dedicated Circuit operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitGetResponse> NewAsync(DedicatedCircuitNewParameters parameters, CancellationToken cancellationToken)
{
ExpressRouteManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "NewAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationResponse originalResponse = await client.DedicatedCircuits.BeginNewAsync(parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationStatusResponse result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
while (result.Status == ExpressRouteOperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 10;
}
if (result.Status == ExpressRouteOperationStatus.Failed)
{
string exStr = "A new dedicated circuit could not be created due to an internal server error.";
throw new ArgumentException(exStr);
}
cancellationToken.ThrowIfCancellationRequested();
DedicatedCircuitGetResponse getResult = await client.DedicatedCircuits.GetAsync(result.Data, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return getResult;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// The Remove Dedicated Circuit operation deletes an existing
/// dedicated circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. Service Key associated with the dedicated circuit to be
/// deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.ExpressRoute.Models.ExpressRouteOperationStatusResponse> RemoveAsync(string serviceKey, CancellationToken cancellationToken)
{
ExpressRouteManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
Tracing.Enter(invocationId, this, "RemoveAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationResponse originalResponse = await client.DedicatedCircuits.BeginRemoveAsync(serviceKey, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationStatusResponse result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
while (result.Status == ExpressRouteOperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 10;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using InTheHand.Net.Bluetooth.Widcomm;
using NUnit.Framework;
using System.Diagnostics;
namespace InTheHand.Net.Tests.Widcomm
{
class TestRfcommPort : IRfcommPort
{
WidcommRfcommStreamBase parent;
// Write
List<byte[]> m_writtenContent = new List<byte[]>();
// Connect
int m_OpenClientCalled, m_CloseCalled;
System.Threading.ManualResetEvent m_OpenClientCalledEvent = new System.Threading.ManualResetEvent(false);
PORT_RETURN_CODE m_OpenClientResult;
int m_DestroyRfcommPortCalled;
int m_ocScn;
byte[] m_ocAddress;
//--------
public void SetParentStream(InTheHand.Net.Bluetooth.Widcomm.WidcommRfcommStreamBase parent)
{
this.parent = parent;
}
internal void TestHackClearParentStream()
{
this.parent = null;
}
//--------
public void AssertWrittenContentAndClear(string name, params byte[][] expectedData)
{
AssertWrittenContent(name, expectedData);
ClearWrittenContent();
}
public void AssertWrittenContent(string name, params byte[][] expectedData)
{
bool sameNumber = (expectedData.Length == m_writtenContent.Count);
for (int i = 0; i < Math.Min(expectedData.Length, m_writtenContent.Count); ++i) {
Assert.AreEqual(expectedData[i], m_writtenContent[i], name + " -- at " + i);
//ManualAssertByteArraysEqual(expectedData[i], m_writtenContent[i]);
} //for
Assert.AreEqual(expectedData.Length, m_writtenContent.Count, name + " -- number of blocks");
}
private void ManualAssertByteArraysEqual(byte[] expected, byte[] actual)
{
if (expected.Length != actual.Length)
throw new AssertionException("Array lengths differ, expected " + expected.Length
+ " but was " + actual.Length);
for (int i = 0; i < expected.Length; ++i) {
if (expected[i] != actual[i])
throw new AssertionException("Arrays differ at index " + i
+ " expected " + expected[i] + " but was " + actual[i]);
}
}
internal void ClearWrittenContent()
{
m_writtenContent.Clear();
}
PORT_RETURN_CODE? m_writeResult;
ushort? m_writeAcceptLength;
object _lock = new object();
public virtual InTheHand.Net.Bluetooth.Widcomm.PORT_RETURN_CODE Write(
byte[] p_data, ushort len_to_write, out ushort p_len_written)
{
lock(_lock) {
Debug.Assert(len_to_write <= p_data.Length, "len_to_write too long");
if (m_writeResult != null) { // Failure result
Debug.Assert(m_writeResult != PORT_RETURN_CODE.SUCCESS);
p_len_written = 9999;
Debug.Assert(m_writeAcceptLength == null, "we don't use it here...");
return m_writeResult.Value;
} else {
ushort writeAcceptLength ;
if (m_writeAcceptLength != null) {
writeAcceptLength = Math.Min(len_to_write, m_writeAcceptLength.Value);
int remains = m_writeAcceptLength.Value - writeAcceptLength;
m_writeAcceptLength = checked((ushort)remains);
} else {
writeAcceptLength = len_to_write;
}
byte[] acceptedData = new byte[writeAcceptLength];
Array.Copy(p_data, acceptedData, acceptedData.Length);
m_writtenContent.Add(acceptedData);
p_len_written = checked((ushort)acceptedData.Length);
return PORT_RETURN_CODE.SUCCESS;
}
}
}
internal void SetWriteResult(PORT_RETURN_CODE result)
{
lock (_lock) {
m_writeResult = result;
m_writeAcceptLength = null;
}
}
internal void SetWriteResult(ushort amountToAccept)
{
lock (_lock) {
m_writeResult = null;
m_writeAcceptLength = amountToAccept;
}
}
internal ushort? GetWriteCapacity()
{
lock (_lock) { return m_writeAcceptLength; }
}
internal PORT_RETURN_CODE? GetWriteResultStatus()
{
lock (_lock) { return m_writeResult; }
}
//--------
internal void NewEvent(PORT_EV eventId)
{
parent.HandlePortEvent(eventId, this);
}
public void NewReceive(byte[] data)
{
parent.HandlePortReceive(data, this);
}
//--------
public PORT_RETURN_CODE OpenClient(int scn, byte[] address)
{
Debug.Assert(m_OpenClientCalled == 0, "called twice?! pre-count: " + m_OpenClientCalled);
++m_OpenClientCalled;
m_OpenClientCalledEvent.Set();
Debug.Assert(m_ocAddress == null, "called twice?!");
m_ocScn = scn;
m_ocAddress = (byte[])address.Clone();
return m_OpenClientResult;
}
public void WaitOpenClientCalled()
{
bool signalled = m_OpenClientCalledEvent.WaitOne(30 * 1000, false);
Assert.IsTrue(signalled, "Test Timeout");
}
public void SetOpenClientResult(PORT_RETURN_CODE ret)
{
m_OpenClientResult = ret;
}
public void AssertOpenClientNotCalled()
{
Assert.AreEqual(0, m_OpenClientCalled, "NOT OpenClientCalled");
}
public void AssertOpenClientCalledAndClear(byte[] address, byte channel)
{
Assert.AreEqual(1, m_OpenClientCalled, "OpenClientCalled");
Assert.AreEqual(address, m_ocAddress, "Address");
Assert.AreEqual(channel, m_ocScn, "Channel");
//
m_OpenClientCalled = 0;
//...
}
//--------
public PORT_RETURN_CODE Close()
{
++m_CloseCalled;
return PORT_RETURN_CODE.SUCCESS;
}
public void AssertCloseCalledOnce(string name)
{
Assert.AreEqual(1, m_CloseCalled, "CloseCalled -- " + name);
//Assert.AreEqual(1, m_DestroyRfcommPortCalled, "DestroyRfcommPortCalled -- " + name);
}
public void AssertCloseCalledAtLeastOnce(string name)
{
Assert.Greater(m_CloseCalled, 0, "CloseCalled -- " + name);
Assert.AreEqual(1, m_DestroyRfcommPortCalled, "DestroyRfcommPortCalled -- " + name);
}
//--------
public void Create()
{
m_debugId = System.Threading.Interlocked.Increment(ref s_nextDebugId);
//Console.WriteLine("TestRfcommPort.Created: " + DebugId);
}
static int s_nextDebugId;
int m_debugId;
public string DebugId { get { return m_debugId.ToString(); } }
public void Destroy()
{
++m_DestroyRfcommPortCalled;
}
//--------
public virtual PORT_RETURN_CODE OpenServer(int scn)
{
throw new Exception("The method or operation is not implemented.");
}
//--------
bool m_IsConnectedReturnsFalse, m_IsConnectedThrows;
public void SetIsConnectedReturnsFalse()
{
m_IsConnectedReturnsFalse = true;
}
public void SetIsConnectedThrows()
{
m_IsConnectedThrows = true;
}
public virtual bool IsConnected(out BluetoothAddress p_remote_bdaddr)
{
if (m_IsConnectedThrows)
throw new RankException("SetIsConnectedThrows");
else if (m_IsConnectedReturnsFalse) {
p_remote_bdaddr = BluetoothAddress.Parse("99:99:99:99:99:99");
return false;
} else {
p_remote_bdaddr = BluetoothAddress.Parse("00:11:22:33:44:55");
return true;
}
}
}//class2
}
| |
//------------------------------------------------------------------------------
// <copyright file="ToolZone.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls.WebParts {
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Util;
public abstract class ToolZone : WebZone, IPostBackEventHandler {
private const string headerCloseEventArgument = "headerClose";
private const int baseIndex = 0;
private const int editUIStyleIndex = 1;
private const int headerCloseVerbIndex = 3;
private const int headerVerbStyleIndex = 4;
private const int instructionTextStyleIndex = 5;
private const int labelStyleIndex = 6;
private const int viewStateArrayLength = 7;
private Style _editUIStyle;
private WebPartVerb _headerCloseVerb;
private Style _headerVerbStyle;
private Style _instructionTextStyle;
private Style _labelStyle;
private WebPartDisplayModeCollection _associatedDisplayModes;
protected ToolZone(ICollection associatedDisplayModes) {
if ((associatedDisplayModes == null) || (associatedDisplayModes.Count == 0)) {
throw new ArgumentNullException("associatedDisplayModes");
}
_associatedDisplayModes = new WebPartDisplayModeCollection();
foreach (WebPartDisplayMode mode in associatedDisplayModes) {
_associatedDisplayModes.Add(mode);
}
_associatedDisplayModes.SetReadOnly(SR.ToolZone_DisplayModesReadOnly);
}
protected ToolZone(WebPartDisplayMode associatedDisplayMode) {
if (associatedDisplayMode == null) {
throw new ArgumentNullException("associatedDisplayMode");
}
_associatedDisplayModes = new WebPartDisplayModeCollection();
_associatedDisplayModes.Add(associatedDisplayMode);
_associatedDisplayModes.SetReadOnly(SR.ToolZone_DisplayModesReadOnly);
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public WebPartDisplayModeCollection AssociatedDisplayModes {
get {
return _associatedDisplayModes;
}
}
protected virtual bool Display {
get {
if (WebPartManager != null) {
WebPartDisplayModeCollection associatedDisplayModes = AssociatedDisplayModes;
if (associatedDisplayModes != null) {
return associatedDisplayModes.Contains(WebPartManager.DisplayMode);
}
}
return false;
}
}
[
DefaultValue(null),
NotifyParentProperty(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.ToolZone_EditUIStyle),
]
public Style EditUIStyle {
get {
if (_editUIStyle == null) {
_editUIStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_editUIStyle).TrackViewState();
}
}
return _editUIStyle;
}
}
[
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Verbs"),
WebSysDescription(SR.ToolZone_HeaderCloseVerb),
]
public virtual WebPartVerb HeaderCloseVerb {
get {
if (_headerCloseVerb == null) {
_headerCloseVerb = new WebPartHeaderCloseVerb();
_headerCloseVerb.EventArgument = headerCloseEventArgument;
if (IsTrackingViewState) {
((IStateManager)_headerCloseVerb).TrackViewState();
}
}
return _headerCloseVerb;
}
}
[
DefaultValue(null),
NotifyParentProperty(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.ToolZone_HeaderVerbStyle),
]
public Style HeaderVerbStyle {
get {
if (_headerVerbStyle == null) {
_headerVerbStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_headerVerbStyle).TrackViewState();
}
}
return _headerVerbStyle;
}
}
[
// Must use WebSysDefaultValue instead of DefaultValue, since it is overridden in extending classes
Localizable(true),
WebSysDefaultValue(""),
WebCategory("Behavior"),
WebSysDescription(SR.ToolZone_InstructionText),
]
public virtual string InstructionText {
get {
string s = (string)ViewState["InstructionText"];
return((s == null) ? String.Empty : s);
}
set {
ViewState["InstructionText"] = value;
}
}
[
DefaultValue(null),
NotifyParentProperty(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.ToolZone_InstructionTextStyle),
]
public Style InstructionTextStyle {
get {
if (_instructionTextStyle == null) {
_instructionTextStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_instructionTextStyle).TrackViewState();
}
}
return _instructionTextStyle;
}
}
[
DefaultValue(null),
NotifyParentProperty(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
PersistenceMode(PersistenceMode.InnerProperty),
WebCategory("Styles"),
WebSysDescription(SR.ToolZone_LabelStyle),
]
public Style LabelStyle {
get {
if (_labelStyle == null) {
_labelStyle = new Style();
if (IsTrackingViewState) {
((IStateManager)_labelStyle).TrackViewState();
}
}
return _labelStyle;
}
}
[
Bindable(false),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
EditorBrowsable(EditorBrowsableState.Never),
]
public override bool Visible {
get {
return Display && base.Visible;
}
set {
if (!DesignMode) {
throw new InvalidOperationException(SR.GetString(SR.ToolZone_CantSetVisible));
}
}
}
protected abstract void Close();
protected override void LoadViewState(object savedState) {
if (savedState == null) {
base.LoadViewState(null);
}
else {
object[] myState = (object[]) savedState;
if (myState.Length != viewStateArrayLength) {
throw new ArgumentException(SR.GetString(SR.ViewState_InvalidViewState));
}
base.LoadViewState(myState[baseIndex]);
if (myState[editUIStyleIndex] != null) {
((IStateManager) EditUIStyle).LoadViewState(myState[editUIStyleIndex]);
}
if (myState[headerCloseVerbIndex] != null) {
((IStateManager) HeaderCloseVerb).LoadViewState(myState[headerCloseVerbIndex]);
}
if (myState[headerVerbStyleIndex] != null) {
((IStateManager) HeaderVerbStyle).LoadViewState(myState[headerVerbStyleIndex]);
}
if (myState[instructionTextStyleIndex] != null) {
((IStateManager) InstructionTextStyle).LoadViewState(myState[instructionTextStyleIndex]);
}
if (myState[labelStyleIndex] != null) {
((IStateManager) LabelStyle).LoadViewState(myState[labelStyleIndex]);
}
}
}
protected virtual void OnDisplayModeChanged(object sender, WebPartDisplayModeEventArgs e) {
}
/// <internalonly/>
protected internal override void OnInit(EventArgs e) {
base.OnInit(e);
WebPartManager webPartManager = WebPartManager;
if (webPartManager != null) {
webPartManager.DisplayModeChanged += new WebPartDisplayModeEventHandler(OnDisplayModeChanged);
webPartManager.SelectedWebPartChanged += new WebPartEventHandler(OnSelectedWebPartChanged);
}
}
protected virtual void OnSelectedWebPartChanged(object sender, WebPartEventArgs e) {
}
protected virtual void RaisePostBackEvent(string eventArgument) {
ValidateEvent(UniqueID, eventArgument);
if (String.Equals(eventArgument, headerCloseEventArgument, StringComparison.OrdinalIgnoreCase) &&
HeaderCloseVerb.Visible && HeaderCloseVerb.Enabled) {
Close();
}
}
protected override void RenderFooter(HtmlTextWriter writer) {
writer.AddStyleAttribute(HtmlTextWriterStyle.Margin, "4px");
writer.RenderBeginTag(HtmlTextWriterTag.Div);
RenderVerbs(writer);
writer.RenderEndTag(); // Div
}
protected override void RenderHeader(HtmlTextWriter writer) {
// Render title bar
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "2");
writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
TitleStyle headerStyle = HeaderStyle;
if (!headerStyle.IsEmpty) {
// Apply font and forecolor from HeaderStyle to inner table
Style style = new Style();
if (!headerStyle.ForeColor.IsEmpty) {
style.ForeColor = headerStyle.ForeColor;
}
style.Font.CopyFrom(headerStyle.Font);
if (!headerStyle.Font.Size.IsEmpty) {
// If the font size is specified on the HeaderStyle, force the font size to 100%,
// so it inherits the font size from its parent in IE compatibility mode. I would
// think that "1em" would work here as well, but "1em" doesn't work when you change
// the font size in the browser.
style.Font.Size = new FontUnit(new Unit(100, UnitType.Percentage));
}
if (!style.IsEmpty) {
style.AddAttributesToRender(writer, this);
}
}
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
// Copied from Panel.cs
//
HorizontalAlign hAlign = headerStyle.HorizontalAlign;
if (hAlign != HorizontalAlign.NotSet) {
TypeConverter hac = TypeDescriptor.GetConverter(typeof(HorizontalAlign));
writer.AddAttribute(HtmlTextWriterAttribute.Align, hac.ConvertToString(hAlign));
}
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
writer.AddStyleAttribute(HtmlTextWriterStyle.WhiteSpace, "nowrap");
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.Write(HeaderText);
writer.RenderEndTag(); // Td
WebPartVerb headerCloseVerb = HeaderCloseVerb;
if (headerCloseVerb.Visible) {
writer.AddStyleAttribute(HtmlTextWriterStyle.WhiteSpace, "nowrap");
writer.RenderBeginTag(HtmlTextWriterTag.Td);
ZoneLinkButton closeButton = new ZoneLinkButton(this, headerCloseVerb.EventArgument);
closeButton.Text = headerCloseVerb.Text;
closeButton.ImageUrl = headerCloseVerb.ImageUrl;
closeButton.ToolTip = headerCloseVerb.Description;
closeButton.Enabled = headerCloseVerb.Enabled;
closeButton.Page = Page;
closeButton.ApplyStyle(HeaderVerbStyle);
closeButton.RenderControl(writer);
writer.RenderEndTag(); // Td
}
writer.RenderEndTag(); // Tr
writer.RenderEndTag(); // Table
}
protected virtual void RenderVerbs(HtmlTextWriter writer) {
}
internal void RenderVerbsInternal(HtmlTextWriter writer, ICollection verbs) {
ArrayList visibleVerbs = new ArrayList();
foreach (WebPartVerb verb in verbs) {
if (verb.Visible) {
visibleVerbs.Add(verb);
}
}
// Render between each pair of verbs (VSWhidbey 77709)
if (visibleVerbs.Count > 0) {
bool firstVerb = true;
foreach (WebPartVerb verb in visibleVerbs) {
if (!firstVerb) {
writer.Write(" ");
}
RenderVerb(writer, verb);
firstVerb = false;
}
}
}
protected virtual void RenderVerb(HtmlTextWriter writer, WebPartVerb verb) {
string eventArgument = verb.EventArgument;
WebControl verbControl;
if (VerbButtonType == ButtonType.Button) {
ZoneButton button = new ZoneButton(this, eventArgument);
button.Text = verb.Text;
verbControl = button;
} else {
ZoneLinkButton linkButton = new ZoneLinkButton(this, eventArgument);
linkButton.Text = verb.Text;
if (VerbButtonType == ButtonType.Image) {
linkButton.ImageUrl = verb.ImageUrl;
}
verbControl = linkButton;
}
verbControl.ApplyStyle(VerbStyle);
verbControl.ToolTip = verb.Description;
verbControl.Enabled = verb.Enabled;
verbControl.Page = Page;
verbControl.RenderControl(writer);
}
protected override object SaveViewState() {
object[] myState = new object[viewStateArrayLength];
myState[baseIndex] = base.SaveViewState();
myState[editUIStyleIndex] = (_editUIStyle != null) ? ((IStateManager)_editUIStyle).SaveViewState() : null;
myState[headerCloseVerbIndex] = (_headerCloseVerb != null) ? ((IStateManager)_headerCloseVerb).SaveViewState() : null;
myState[headerVerbStyleIndex] = (_headerVerbStyle != null) ? ((IStateManager)_headerVerbStyle).SaveViewState() : null;
myState[instructionTextStyleIndex] = (_instructionTextStyle != null) ? ((IStateManager)_instructionTextStyle).SaveViewState() : null;
myState[labelStyleIndex] = (_labelStyle != null) ? ((IStateManager)_labelStyle).SaveViewState() : null;
for (int i=0; i < viewStateArrayLength; i++) {
if (myState[i] != null) {
return myState;
}
}
// More performant to return null than an array of null values
return null;
}
protected override void TrackViewState() {
base.TrackViewState();
if (_editUIStyle != null) {
((IStateManager) _editUIStyle).TrackViewState();
}
if (_headerCloseVerb != null) {
((IStateManager) _headerCloseVerb).TrackViewState();
}
if (_headerVerbStyle != null) {
((IStateManager) _headerVerbStyle).TrackViewState();
}
if (_instructionTextStyle != null) {
((IStateManager) _instructionTextStyle).TrackViewState();
}
if (_labelStyle != null) {
((IStateManager) _labelStyle).TrackViewState();
}
}
#region Implementation of IPostBackEventHandler
/// <internalonly/>
void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) {
RaisePostBackEvent(eventArgument);
}
#endregion
}
}
| |
using System;
using System.Text;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AttributeSource = Lucene.Net.Util.AttributeSource;
using LevenshteinAutomata = Lucene.Net.Util.Automaton.LevenshteinAutomata;
using SingleTermsEnum = Lucene.Net.Index.SingleTermsEnum;
using Term = Lucene.Net.Index.Term;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// Implements the fuzzy search query. The similarity measurement
/// is based on the Damerau-Levenshtein (optimal string alignment) algorithm,
/// though you can explicitly choose classic Levenshtein by passing <c>false</c>
/// to the <c>transpositions</c> parameter.
///
/// <para/>this query uses <see cref="MultiTermQuery.TopTermsScoringBooleanQueryRewrite"/>
/// as default. So terms will be collected and scored according to their
/// edit distance. Only the top terms are used for building the <see cref="BooleanQuery"/>.
/// It is not recommended to change the rewrite mode for fuzzy queries.
///
/// <para/>At most, this query will match terms up to
/// <see cref="Lucene.Net.Util.Automaton.LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE"/> edits.
/// Higher distances (especially with transpositions enabled), are generally not useful and
/// will match a significant amount of the term dictionary. If you really want this, consider
/// using an n-gram indexing technique (such as the SpellChecker in the
/// <a href="{@docRoot}/../suggest/overview-summary.html">suggest module</a>) instead.
///
/// <para/>NOTE: terms of length 1 or 2 will sometimes not match because of how the scaled
/// distance between two terms is computed. For a term to match, the edit distance between
/// the terms must be less than the minimum length term (either the input term, or
/// the candidate term). For example, <see cref="FuzzyQuery"/> on term "abcd" with maxEdits=2 will
/// not match an indexed term "ab", and <see cref="FuzzyQuery"/> on term "a" with maxEdits=2 will not
/// match an indexed term "abc".
/// </summary>
public class FuzzyQuery : MultiTermQuery
{
public const int DefaultMaxEdits = LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE;
public const int DefaultPrefixLength = 0;
public const int DefaultMaxExpansions = 50;
public const bool DefaultTranspositions = true;
private readonly int maxEdits;
private readonly int maxExpansions;
private readonly bool transpositions;
private readonly int prefixLength;
private readonly Term term;
/// <summary>
/// Create a new <see cref="FuzzyQuery"/> that will match terms with an edit distance
/// of at most <paramref name="maxEdits"/> to <paramref name="term"/>.
/// If a <paramref name="prefixLength"/> > 0 is specified, a common prefix
/// of that length is also required.
/// </summary>
/// <param name="term"> The term to search for </param>
/// <param name="maxEdits"> Must be >= 0 and <= <see cref="LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE"/>. </param>
/// <param name="prefixLength"> Length of common (non-fuzzy) prefix </param>
/// <param name="maxExpansions"> The maximum number of terms to match. If this number is
/// greater than <see cref="BooleanQuery.MaxClauseCount"/> when the query is rewritten,
/// then the maxClauseCount will be used instead. </param>
/// <param name="transpositions"> <c>true</c> if transpositions should be treated as a primitive
/// edit operation. If this is <c>false</c>, comparisons will implement the classic
/// Levenshtein algorithm. </param>
public FuzzyQuery(Term term, int maxEdits, int prefixLength, int maxExpansions, bool transpositions)
: base(term.Field)
{
if (maxEdits < 0 || maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE)
{
throw new System.ArgumentException("maxEdits must be between 0 and " + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE);
}
if (prefixLength < 0)
{
throw new System.ArgumentException("prefixLength cannot be negative.");
}
if (maxExpansions < 0)
{
throw new System.ArgumentException("maxExpansions cannot be negative.");
}
this.term = term;
this.maxEdits = maxEdits;
this.prefixLength = prefixLength;
this.transpositions = transpositions;
this.maxExpansions = maxExpansions;
MultiTermRewriteMethod = new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(maxExpansions);
}
/// <summary>
/// Calls <see cref="FuzzyQuery.FuzzyQuery(Term, int, int, int, bool)">
/// FuzzyQuery(term, maxEdits, prefixLength, defaultMaxExpansions, defaultTranspositions)</see>.
/// </summary>
public FuzzyQuery(Term term, int maxEdits, int prefixLength)
: this(term, maxEdits, prefixLength, DefaultMaxExpansions, DefaultTranspositions)
{
}
/// <summary>
/// Calls <see cref="FuzzyQuery(Term, int, int)">FuzzyQuery(term, maxEdits, defaultPrefixLength)</see>.
/// </summary>
public FuzzyQuery(Term term, int maxEdits)
: this(term, maxEdits, DefaultPrefixLength)
{
}
/// <summary>
/// Calls <see cref="FuzzyQuery(Term, int)">FuzzyQuery(term, defaultMaxEdits)</see>.
/// </summary>
public FuzzyQuery(Term term)
: this(term, DefaultMaxEdits)
{
}
/// <returns> The maximum number of edit distances allowed for this query to match. </returns>
public virtual int MaxEdits
{
get
{
return maxEdits;
}
}
/// <summary>
/// Returns the non-fuzzy prefix length. This is the number of characters at the start
/// of a term that must be identical (not fuzzy) to the query term if the query
/// is to match that term.
/// </summary>
public virtual int PrefixLength
{
get
{
return prefixLength;
}
}
/// <summary>
/// Returns <c>true</c> if transpositions should be treated as a primitive edit operation.
/// If this is <c>false</c>, comparisons will implement the classic Levenshtein algorithm.
/// </summary>
public virtual bool Transpositions
{
get
{
return transpositions;
}
}
protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
{
if (maxEdits == 0 || prefixLength >= term.Text().Length) // can only match if it's exact
{
return new SingleTermsEnum(terms.GetIterator(null), term.Bytes);
}
return new FuzzyTermsEnum(terms, atts, Term, maxEdits, prefixLength, transpositions);
}
/// <summary>
/// Returns the pattern term.
/// </summary>
public virtual Term Term
{
get
{
return term;
}
}
public override string ToString(string field)
{
var buffer = new StringBuilder();
if (!term.Field.Equals(field, StringComparison.Ordinal))
{
buffer.Append(term.Field);
buffer.Append(":");
}
buffer.Append(term.Text());
buffer.Append('~');
buffer.Append(Convert.ToString(maxEdits));
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
public override int GetHashCode()
{
const int prime = 31;
int result = base.GetHashCode();
result = prime * result + maxEdits;
result = prime * result + prefixLength;
result = prime * result + maxExpansions;
result = prime * result + (transpositions ? 0 : 1);
result = prime * result + ((term == null) ? 0 : term.GetHashCode());
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (!base.Equals(obj))
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
FuzzyQuery other = (FuzzyQuery)obj;
if (maxEdits != other.maxEdits)
{
return false;
}
if (prefixLength != other.prefixLength)
{
return false;
}
if (maxExpansions != other.maxExpansions)
{
return false;
}
if (transpositions != other.transpositions)
{
return false;
}
if (term == null)
{
if (other.term != null)
{
return false;
}
}
else if (!term.Equals(other.term))
{
return false;
}
return true;
}
/// @deprecated pass integer edit distances instead.
[Obsolete("pass integer edit distances instead.")]
public const float DefaultMinSimilarity = LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE;
/// <summary>
/// Helper function to convert from deprecated "minimumSimilarity" fractions
/// to raw edit distances.
/// <para/>
/// NOTE: this was floatToEdits() in Lucene
/// </summary>
/// <param name="minimumSimilarity"> Scaled similarity </param>
/// <param name="termLen"> Length (in unicode codepoints) of the term. </param>
/// <returns> Equivalent number of maxEdits </returns>
[Obsolete("pass integer edit distances instead.")]
public static int SingleToEdits(float minimumSimilarity, int termLen)
{
if (minimumSimilarity >= 1f)
{
return (int)Math.Min(minimumSimilarity, LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE);
}
else if (minimumSimilarity == 0.0f)
{
return 0; // 0 means exact, not infinite # of edits!
}
else
{
return Math.Min((int)((1D - minimumSimilarity) * termLen), LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE);
}
}
}
}
| |
#region MIT License
/*
* Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using System.Drawing;
using AdvanceMath;
using AdvanceMath.Geometry2D;
using Graphics2DDotNet;
using Physics2DDotNet;
using Physics2DDotNet.Ignorers;
using Physics2DDotNet.Joints;
using Physics2DDotNet.Shapes;
using Physics2DDotNet.PhysicsLogics;
using SdlDotNet;
using SdlDotNet.Core;
using SdlDotNet.Input;
using SdlDotNet.Graphics;
namespace Physics2DDotNet.Demo.Demos
{
[PhysicsDemo("Advance", "Rube Goldberg Challenge", "TODO")]
public class RubeGoldbergChallenge : BaseDemo
{
public static DisposeCallback RegisterDup(DemoOpenInfo info, List<Body> bodies)
{
LinkedList<Body> removable = new LinkedList<Body>();
Body body = null;
Scalar rotation = 0;
Vector2D scale = new Vector2D(1, 1);
bool duplicate = false;
bool makeJoint = false;
Vector2D anchor = Vector2D.Zero;
int count = 0;
Body bj1 = null;
Body bj2 = null;
EventHandler<ViewportMouseButtonEventArgs> mouseDown = delegate(object sender, ViewportMouseButtonEventArgs e)
{
IntersectionInfo temp;
switch (e.Button)
{
case MouseButton.PrimaryButton:
if (makeJoint)
{
count++;
switch (count)
{
case 1:
for (LinkedListNode<Body> node = removable.First;
node != null;
node = node.Next)
{
Vector2D pos = node.Value.Matrices.ToBody * e.Position;
if (node.Value.Shape.TryGetIntersection(pos, out temp))
{
bj1 = node.Value;
return;
}
}
count--;
break;
case 2:
anchor = e.Position;
break;
case 3:
for (LinkedListNode<Body> node = removable.First;
node != null;
node = node.Next)
{
Vector2D pos = node.Value.Matrices.ToBody * e.Position;
if (node.Value.Shape.TryGetIntersection(pos, out temp))
{
bj2 = node.Value;
return;
}
}
count--;
break;
}
}
else
{
foreach (Body b in bodies)
{
Vector2D pos = b.Matrices.ToBody * e.Position;
if (b.Shape.TryGetIntersection(pos, out temp))
{
body = b.Duplicate();
info.Scene.AddGraphic(new BodyGraphic(body));
return;
}
}
for (LinkedListNode<Body> node = removable.First;
node != null;
node = node.Next)
{
Vector2D pos = node.Value.Matrices.ToBody * e.Position;
if (node.Value.Shape.TryGetIntersection(pos, out temp))
{
if (duplicate)
{
body = node.Value.Duplicate();
info.Scene.AddGraphic(new BodyGraphic(body));
return;
}
else
{
body = node.Value;
removable.Remove(node);
return;
}
}
}
}
break;
case MouseButton.SecondaryButton:
for (LinkedListNode<Body> node = removable.First;
node != null;
node = node.Next)
{
Vector2D pos = node.Value.Matrices.ToBody * e.Position;
if (node.Value.Shape.TryGetIntersection(pos, out temp))
{
node.Value.Lifetime.IsExpired = true;
removable.Remove(node);
return;
}
}
break;
}
};
EventHandler<ViewportMouseMotionEventArgs> mouseMotion = delegate(object sender, ViewportMouseMotionEventArgs e)
{
if (body != null)
{
body.State.Position.Linear = e.Position;
}
};
EventHandler<ViewportMouseButtonEventArgs> mouseUp = delegate(object sender, ViewportMouseButtonEventArgs e)
{
if (body != null)
{
removable.AddLast(body);
body = null;
}
};
EventHandler<KeyboardEventArgs> keyDown = delegate(object sender, KeyboardEventArgs e)
{
switch (e.Key)
{
case Key.Q:
rotation -= .05f;
break;
case Key.E:
rotation += .05f;
break;
case Key.W:
scale.Y += .05f;
break;
case Key.S:
scale.Y -= .05f;
break;
case Key.A:
scale.X -= .05f;
break;
case Key.D:
scale.X += .05f;
break;
case Key.LeftControl:
case Key.RightControl:
duplicate = true;
break;
case Key.LeftShift:
case Key.RightShift:
count = 0;
makeJoint = true;
break;
}
};
EventHandler<KeyboardEventArgs> keyUp = delegate(object sender, KeyboardEventArgs e)
{
switch (e.Key)
{
case Key.Q:
rotation += .05f;
break;
case Key.E:
rotation -= .05f;
break;
case Key.W:
scale.Y -= .05f;
break;
case Key.S:
scale.Y += .05f;
break;
case Key.A:
scale.X += .05f;
break;
case Key.D:
scale.X -= .05f;
break;
case Key.LeftControl:
case Key.RightControl:
duplicate = false;
break;
case Key.LeftShift:
case Key.RightShift:
switch (count)
{
case 2:
info.Scene.Engine.AddJoint(new FixedHingeJoint(bj1, anchor, new Lifespan()));
break;
case 3:
info.Scene.Engine.AddJoint(new HingeJoint(bj1, bj2, anchor, new Lifespan()));
break;
}
count = 0;
makeJoint = false;
break;
}
};
EventHandler<DrawEventArgs> onDraw = delegate(object sender, DrawEventArgs e)
{
if (body != null)
{
body.State.Position.Angular += rotation;
body.Transformation *= Matrix2x3.FromScale(scale);
body.ApplyPosition();
}
};
info.Scene.BeginDrawing += onDraw;
info.Viewport.MouseDown += mouseDown;
info.Viewport.MouseMotion += mouseMotion;
info.Viewport.MouseUp += mouseUp;
Events.KeyboardDown += keyDown;
Events.KeyboardUp += keyUp;
return delegate()
{
info.Scene.BeginDrawing -= onDraw;
info.Viewport.MouseDown -= mouseDown;
info.Viewport.MouseMotion -= mouseMotion;
info.Viewport.MouseUp -= mouseUp;
Events.KeyboardDown -= keyDown;
Events.KeyboardUp -= keyUp;
};
}
DisposeCallback dispose;
protected override void Open()
{
Scene.IsPaused = true;
List<Body> bodies = new List<Body>();
Body b = DemoHelper.AddLine(DemoInfo, new Vector2D(300, 200), new Vector2D(400, 200), 40, Scalar.PositiveInfinity);
b.IgnoresPhysicsLogics = true;
bodies.Add(b);
Body b2 = DemoHelper.AddCircle(DemoInfo, 20, 40, Scalar.PositiveInfinity, new ALVector2D(0, 300, 100));
b2.IgnoresPhysicsLogics = true;
bodies.Add(b2);
Body b3 = DemoHelper.AddCircle(DemoInfo, 20, 40, 50, new ALVector2D(0, 100, 100));
bodies.Add(b3);
Body b4 = DemoHelper.AddRectangle(DemoInfo, 20, 20, 20, new ALVector2D(0, 150, 150));
bodies.Add(b4);
dispose += RegisterDup(DemoInfo, bodies);
DemoHelper.AddShell(DemoInfo, new BoundingRectangle(0, 0, 200, 200), 10, Scalar.PositiveInfinity).ForEach(delegate(Body sb) { sb.IgnoresPhysicsLogics = true; });
Body bStart = DemoHelper.AddShape(DemoInfo,ShapeFactory.CreateSprite(Cache<SurfacePolygons>.GetItem("start.png"),2,16,3),Scalar.PositiveInfinity,new ALVector2D(0,100, 650));
// Body bStart = DemoHelper.AddLine(DemoInfo, new Vector2D(10, 600), new Vector2D(100, 600), 40, Scalar.PositiveInfinity);
bStart.IgnoresPhysicsLogics = true;
Body bStop = DemoHelper.AddShape(DemoInfo, ShapeFactory.CreateSprite(Cache<SurfacePolygons>.GetItem("stop.png"), 2, 16, 3), Scalar.PositiveInfinity, new ALVector2D(0, 100, 700));
//Body bEnd = DemoHelper.AddLine(DemoInfo, new Vector2D(10, 700), new Vector2D(100, 700), 40, Scalar.PositiveInfinity);
bStop.IgnoresPhysicsLogics = true;
Scene.Engine.AddLogic (new GravityField(new Vector2D(0, 1000), new Lifespan()));
dispose += DemoHelper.RegisterClick(DemoInfo, bStart, MouseButton.PrimaryButton,
delegate(object sender, EventArgs e)
{
Scene.IsPaused = false;
});
dispose += DemoHelper.RegisterClick(DemoInfo, bStop, MouseButton.PrimaryButton,
delegate(object sender, EventArgs e)
{
Scene.IsPaused = true;
});
}
protected override void Dispose(bool disposing)
{
if (dispose != null) { dispose(); }
}
}
}
| |
// 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.Diagnostics;
using System.Data;
using System.Data.SqlTypes;
using System.Globalization;
namespace Microsoft.SqlServer.Server
{
// DESIGN NOTES
//
// The following classes are a tight inheritance hierarchy, and are not designed for
// being inherited outside of this file. Instances are guaranteed to be immutable, and
// outside classes rely on this fact.
//
// The various levels may not all be used outside of this file, but for clarity of purpose
// they are all useful distinctions to make.
//
// In general, moving lower in the type hierarchy exposes less portable values. Thus,
// the root metadata can be readily shared across different (MSSQL) servers and clients,
// while QueryMetaData has attributes tied to a specific query, running against specific
// data storage on a specific server.
//
// The SmiMetaData hierarchy does not do data validation on retail builds! It will assert
// that the values passed to it have been validated externally, however.
//
// SmiMetaData
//
// Root of the hierarchy.
// Represents the minimal amount of metadata required to represent any Sql Server datum
// without any references to any particular server or schema (thus, no server-specific multi-part names).
// It could be used to communicate solely between two disconnected clients, for instance.
//
// NOTE: It currently does not contain sufficient information to describe typed XML, since we
// don't have a good server-independent mechanism for such.
//
// This class is also used as implementation for the public SqlMetaData class.
internal class SmiMetaData
{
private SqlDbType _databaseType; // Main enum that determines what is valid for other attributes.
private long _maxLength; // Varies for variable-length types, others are fixed value per type
private byte _precision; // Varies for SqlDbType.Decimal, others are fixed value per type
private byte _scale; // Varies for SqlDbType.Decimal, others are fixed value per type
private long _localeId; // Valid only for character types, others are 0
private SqlCompareOptions _compareOptions; // Valid only for character types, others are SqlCompareOptions.Default
private bool _isMultiValued; // Multiple instances per value? (I.e. tables, arrays)
private IList<SmiExtendedMetaData> _fieldMetaData; // Metadata of fields for structured types
private SmiMetaDataPropertyCollection _extendedProperties; // Extended properties, Key columns, sort order, etc.
// DevNote: For now, since the list of extended property types is small, we can handle them in a simple list.
// In the future, we may need to create a more performant storage & lookup mechanism, such as a hash table
// of lists indexed by type of property or an array of lists with a well-known index for each type.
// Limits for attributes (SmiMetaData will assert that these limits as applicable in constructor)
internal const long UnlimitedMaxLengthIndicator = -1; // unlimited (except by implementation) max-length.
internal const long MaxUnicodeCharacters = 4000; // Maximum for limited type
internal const long MaxANSICharacters = 8000; // Maximum for limited type
internal const long MaxBinaryLength = 8000; // Maximum for limited type
internal const int MinPrecision = 1; // SqlDecimal defines max precision
internal const int MinScale = 0; // SqlDecimal defines max scale
internal const int MaxTimeScale = 7; // Max scale for time, datetime2, and datetimeoffset
internal static readonly DateTime MaxSmallDateTime = new DateTime(2079, 06, 06, 23, 59, 29, 998);
internal static readonly DateTime MinSmallDateTime = new DateTime(1899, 12, 31, 23, 59, 29, 999);
internal static readonly SqlMoney MaxSmallMoney = new SqlMoney(((Decimal)Int32.MaxValue) / 10000);
internal static readonly SqlMoney MinSmallMoney = new SqlMoney(((Decimal)Int32.MinValue) / 10000);
internal const SqlCompareOptions DefaultStringCompareOptions = SqlCompareOptions.IgnoreCase
| SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth;
internal const long MaxNameLength = 128; // maximum length in the server is 128.
private static readonly IList<SmiExtendedMetaData> s_emptyFieldList = new SmiExtendedMetaData[0];
// Precision to max length lookup table
private static byte[] s_maxLenFromPrecision = new byte[] {5,5,5,5,5,5,5,5,5,9,9,9,9,9,
9,9,9,9,9,13,13,13,13,13,13,13,13,13,17,17,17,17,17,17,17,17,17,17};
// Scale offset to max length lookup table
private static byte[] s_maxVarTimeLenOffsetFromScale = new byte[] { 2, 2, 2, 1, 1, 0, 0, 0 };
// Defaults
// SmiMetaData(SqlDbType, MaxLen, Prec, Scale, CompareOptions)
internal static readonly SmiMetaData DefaultBigInt = new SmiMetaData(SqlDbType.BigInt, 8, 19, 0, SqlCompareOptions.None); // SqlDbType.BigInt
internal static readonly SmiMetaData DefaultBinary = new SmiMetaData(SqlDbType.Binary, 1, 0, 0, SqlCompareOptions.None); // SqlDbType.Binary
internal static readonly SmiMetaData DefaultBit = new SmiMetaData(SqlDbType.Bit, 1, 1, 0, SqlCompareOptions.None); // SqlDbType.Bit
internal static readonly SmiMetaData DefaultChar_NoCollation = new SmiMetaData(SqlDbType.Char, 1, 0, 0, DefaultStringCompareOptions);// SqlDbType.Char
internal static readonly SmiMetaData DefaultDateTime = new SmiMetaData(SqlDbType.DateTime, 8, 23, 3, SqlCompareOptions.None); // SqlDbType.DateTime
internal static readonly SmiMetaData DefaultDecimal = new SmiMetaData(SqlDbType.Decimal, 9, 18, 0, SqlCompareOptions.None); // SqlDbType.Decimal
internal static readonly SmiMetaData DefaultFloat = new SmiMetaData(SqlDbType.Float, 8, 53, 0, SqlCompareOptions.None); // SqlDbType.Float
internal static readonly SmiMetaData DefaultImage = new SmiMetaData(SqlDbType.Image, UnlimitedMaxLengthIndicator, 0, 0, SqlCompareOptions.None); // SqlDbType.Image
internal static readonly SmiMetaData DefaultInt = new SmiMetaData(SqlDbType.Int, 4, 10, 0, SqlCompareOptions.None); // SqlDbType.Int
internal static readonly SmiMetaData DefaultMoney = new SmiMetaData(SqlDbType.Money, 8, 19, 4, SqlCompareOptions.None); // SqlDbType.Money
internal static readonly SmiMetaData DefaultNChar_NoCollation = new SmiMetaData(SqlDbType.NChar, 1, 0, 0, DefaultStringCompareOptions);// SqlDbType.NChar
internal static readonly SmiMetaData DefaultNText_NoCollation = new SmiMetaData(SqlDbType.NText, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.NText
internal static readonly SmiMetaData DefaultNVarChar_NoCollation = new SmiMetaData(SqlDbType.NVarChar, MaxUnicodeCharacters, 0, 0, DefaultStringCompareOptions);// SqlDbType.NVarChar
internal static readonly SmiMetaData DefaultReal = new SmiMetaData(SqlDbType.Real, 4, 24, 0, SqlCompareOptions.None); // SqlDbType.Real
internal static readonly SmiMetaData DefaultUniqueIdentifier = new SmiMetaData(SqlDbType.UniqueIdentifier, 16, 0, 0, SqlCompareOptions.None); // SqlDbType.UniqueIdentifier
internal static readonly SmiMetaData DefaultSmallDateTime = new SmiMetaData(SqlDbType.SmallDateTime, 4, 16, 0, SqlCompareOptions.None); // SqlDbType.SmallDateTime
internal static readonly SmiMetaData DefaultSmallInt = new SmiMetaData(SqlDbType.SmallInt, 2, 5, 0, SqlCompareOptions.None); // SqlDbType.SmallInt
internal static readonly SmiMetaData DefaultSmallMoney = new SmiMetaData(SqlDbType.SmallMoney, 4, 10, 4, SqlCompareOptions.None); // SqlDbType.SmallMoney
internal static readonly SmiMetaData DefaultText_NoCollation = new SmiMetaData(SqlDbType.Text, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.Text
internal static readonly SmiMetaData DefaultTimestamp = new SmiMetaData(SqlDbType.Timestamp, 8, 0, 0, SqlCompareOptions.None); // SqlDbType.Timestamp
internal static readonly SmiMetaData DefaultTinyInt = new SmiMetaData(SqlDbType.TinyInt, 1, 3, 0, SqlCompareOptions.None); // SqlDbType.TinyInt
internal static readonly SmiMetaData DefaultVarBinary = new SmiMetaData(SqlDbType.VarBinary, MaxBinaryLength, 0, 0, SqlCompareOptions.None); // SqlDbType.VarBinary
internal static readonly SmiMetaData DefaultVarChar_NoCollation = new SmiMetaData(SqlDbType.VarChar, MaxANSICharacters, 0, 0, DefaultStringCompareOptions);// SqlDbType.VarChar
internal static readonly SmiMetaData DefaultVariant = new SmiMetaData(SqlDbType.Variant, 8016, 0, 0, SqlCompareOptions.None); // SqlDbType.Variant
internal static readonly SmiMetaData DefaultXml = new SmiMetaData(SqlDbType.Xml, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.Xml
internal static readonly SmiMetaData DefaultStructured = new SmiMetaData(SqlDbType.Structured, 0, 0, 0, SqlCompareOptions.None); // SqlDbType.Structured
internal static readonly SmiMetaData DefaultDate = new SmiMetaData(SqlDbType.Date, 3, 10, 0, SqlCompareOptions.None); // SqlDbType.Date
internal static readonly SmiMetaData DefaultTime = new SmiMetaData(SqlDbType.Time, 5, 0, 7, SqlCompareOptions.None); // SqlDbType.Time
internal static readonly SmiMetaData DefaultDateTime2 = new SmiMetaData(SqlDbType.DateTime2, 8, 0, 7, SqlCompareOptions.None); // SqlDbType.DateTime2
internal static readonly SmiMetaData DefaultDateTimeOffset = new SmiMetaData(SqlDbType.DateTimeOffset, 10, 0, 7, SqlCompareOptions.None); // SqlDbType.DateTimeOffset
// No default for generic UDT
internal static SmiMetaData DefaultNVarChar
{
get
{
return new SmiMetaData(
DefaultNVarChar_NoCollation.SqlDbType,
DefaultNVarChar_NoCollation.MaxLength,
DefaultNVarChar_NoCollation.Precision,
DefaultNVarChar_NoCollation.Scale,
CultureInfo.CurrentCulture.LCID,
SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth);
}
}
internal SmiMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions) :
this(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
false,
null,
null)
{
}
// SMI V220 ctor.
internal SmiMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldTypes,
SmiMetaDataPropertyCollection extendedProperties)
{
Debug.Assert(IsSupportedDbType(dbType), "Invalid SqlDbType: " + dbType);
SetDefaultsForType(dbType);
switch (dbType)
{
case SqlDbType.BigInt:
case SqlDbType.Bit:
case SqlDbType.DateTime:
case SqlDbType.Float:
case SqlDbType.Image:
case SqlDbType.Int:
case SqlDbType.Money:
case SqlDbType.Real:
case SqlDbType.SmallDateTime:
case SqlDbType.SmallInt:
case SqlDbType.SmallMoney:
case SqlDbType.Timestamp:
case SqlDbType.TinyInt:
case SqlDbType.UniqueIdentifier:
case SqlDbType.Variant:
case SqlDbType.Xml:
case SqlDbType.Date:
break;
case SqlDbType.Binary:
case SqlDbType.VarBinary:
_maxLength = maxLength;
break;
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.NVarChar:
case SqlDbType.VarChar:
// locale and compare options are not validated until they get to the server
_maxLength = maxLength;
_localeId = localeId;
_compareOptions = compareOptions;
break;
case SqlDbType.NText:
case SqlDbType.Text:
_localeId = localeId;
_compareOptions = compareOptions;
break;
case SqlDbType.Decimal:
Debug.Assert(MinPrecision <= precision && SqlDecimal.MaxPrecision >= precision, "Invalid precision: " + precision);
Debug.Assert(MinScale <= scale && SqlDecimal.MaxScale >= scale, "Invalid scale: " + scale);
Debug.Assert(scale <= precision, "Precision: " + precision + " greater than scale: " + scale);
_precision = precision;
_scale = scale;
_maxLength = s_maxLenFromPrecision[precision - 1];
break;
case SqlDbType.Udt:
throw System.Data.Common.ADP.DbTypeNotSupported(SqlDbType.Udt.ToString());
case SqlDbType.Structured:
if (null != fieldTypes)
{
_fieldMetaData = new System.Collections.ObjectModel.ReadOnlyCollection<SmiExtendedMetaData>(fieldTypes);
}
_isMultiValued = isMultiValued;
_maxLength = _fieldMetaData.Count;
break;
case SqlDbType.Time:
Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale);
_scale = scale;
_maxLength = 5 - s_maxVarTimeLenOffsetFromScale[scale];
break;
case SqlDbType.DateTime2:
Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale);
_scale = scale;
_maxLength = 8 - s_maxVarTimeLenOffsetFromScale[scale];
break;
case SqlDbType.DateTimeOffset:
Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale);
_scale = scale;
_maxLength = 10 - s_maxVarTimeLenOffsetFromScale[scale];
break;
default:
Debug.Assert(false, "How in the world did we get here? :" + dbType);
break;
}
if (null != extendedProperties)
{
extendedProperties.SetReadOnly();
_extendedProperties = extendedProperties;
}
// properties and fields must meet the following conditions at this point:
// 1) not null
// 2) read only
// 3) same number of columns in each list (0 count acceptable for properties that are "unused")
Debug.Assert(null != _extendedProperties && _extendedProperties.IsReadOnly, "SmiMetaData.ctor: _extendedProperties is " + (null != _extendedProperties ? "writable" : "null"));
Debug.Assert(null != _fieldMetaData && _fieldMetaData.IsReadOnly, "SmiMetaData.ctor: _fieldMetaData is " + (null != _fieldMetaData ? "writable" : "null"));
#if DEBUG
((SmiDefaultFieldsProperty)_extendedProperties[SmiPropertySelector.DefaultFields]).CheckCount(_fieldMetaData.Count);
((SmiOrderProperty)_extendedProperties[SmiPropertySelector.SortOrder]).CheckCount(_fieldMetaData.Count);
((SmiUniqueKeyProperty)_extendedProperties[SmiPropertySelector.UniqueKey]).CheckCount(_fieldMetaData.Count);
#endif
}
// Sql-style compare options for character types.
internal SqlCompareOptions CompareOptions
{
get
{
return _compareOptions;
}
}
// LCID for type. 0 for non-character types.
internal long LocaleId
{
get
{
return _localeId;
}
}
// Units of length depend on type.
// NVarChar, NChar, NText: # of Unicode characters
// Everything else: # of bytes
internal long MaxLength
{
get
{
return _maxLength;
}
}
internal byte Precision
{
get
{
return _precision;
}
}
internal byte Scale
{
get
{
return _scale;
}
}
internal SqlDbType SqlDbType
{
get
{
return _databaseType;
}
}
internal bool IsMultiValued
{
get
{
return _isMultiValued;
}
}
// Returns read-only list of field metadata
internal IList<SmiExtendedMetaData> FieldMetaData
{
get
{
return _fieldMetaData;
}
}
// Returns read-only list of extended properties
internal SmiMetaDataPropertyCollection ExtendedProperties
{
get
{
return _extendedProperties;
}
}
internal static bool IsSupportedDbType(SqlDbType dbType)
{
// Hole in SqlDbTypes between Xml and Udt for non-WinFS scenarios.
return (SqlDbType.BigInt <= dbType && SqlDbType.Xml >= dbType) ||
(SqlDbType.Udt <= dbType && SqlDbType.DateTimeOffset >= dbType);
}
// Only correct access point for defaults per SqlDbType.
internal static SmiMetaData GetDefaultForType(SqlDbType dbType)
{
Debug.Assert(IsSupportedDbType(dbType), "Unsupported SqlDbtype: " + dbType);
Debug.Assert(dbType != SqlDbType.Udt, "UDT not supported");
return s_defaultValues[(int)dbType];
}
// Private constructor used only to initialize default instance array elements.
// DO NOT EXPOSE OUTSIDE THIS CLASS!
private SmiMetaData(
SqlDbType sqlDbType,
long maxLength,
byte precision,
byte scale,
SqlCompareOptions compareOptions)
{
_databaseType = sqlDbType;
_maxLength = maxLength;
_precision = precision;
_scale = scale;
_compareOptions = compareOptions;
// defaults are the same for all types for the following attributes.
_localeId = 0;
_isMultiValued = false;
_fieldMetaData = s_emptyFieldList;
_extendedProperties = SmiMetaDataPropertyCollection.EmptyInstance;
}
// static array of default-valued metadata ordered by corresponding SqlDbType.
// NOTE: INDEXED BY SqlDbType ENUM! MUST UPDATE THIS ARRAY WHEN UPDATING SqlDbType!
// ONLY ACCESS THIS GLOBAL FROM GetDefaultForType!
private static SmiMetaData[] s_defaultValues =
{
DefaultBigInt, // SqlDbType.BigInt
DefaultBinary, // SqlDbType.Binary
DefaultBit, // SqlDbType.Bit
DefaultChar_NoCollation, // SqlDbType.Char
DefaultDateTime, // SqlDbType.DateTime
DefaultDecimal, // SqlDbType.Decimal
DefaultFloat, // SqlDbType.Float
DefaultImage, // SqlDbType.Image
DefaultInt, // SqlDbType.Int
DefaultMoney, // SqlDbType.Money
DefaultNChar_NoCollation, // SqlDbType.NChar
DefaultNText_NoCollation, // SqlDbType.NText
DefaultNVarChar_NoCollation, // SqlDbType.NVarChar
DefaultReal, // SqlDbType.Real
DefaultUniqueIdentifier, // SqlDbType.UniqueIdentifier
DefaultSmallDateTime, // SqlDbType.SmallDateTime
DefaultSmallInt, // SqlDbType.SmallInt
DefaultSmallMoney, // SqlDbType.SmallMoney
DefaultText_NoCollation, // SqlDbType.Text
DefaultTimestamp, // SqlDbType.Timestamp
DefaultTinyInt, // SqlDbType.TinyInt
DefaultVarBinary, // SqlDbType.VarBinary
DefaultVarChar_NoCollation, // SqlDbType.VarChar
DefaultVariant, // SqlDbType.Variant
DefaultNVarChar_NoCollation, // Placeholder for value 24
DefaultXml, // SqlDbType.Xml
DefaultNVarChar_NoCollation, // Placeholder for value 26
DefaultNVarChar_NoCollation, // Placeholder for value 27
DefaultNVarChar_NoCollation, // Placeholder for value 28
null, // Generic Udt (not supported)
DefaultStructured, // Generic structured type
DefaultDate, // SqlDbType.Date
DefaultTime, // SqlDbType.Time
DefaultDateTime2, // SqlDbType.DateTime2
DefaultDateTimeOffset, // SqlDbType.DateTimeOffset
};
// Internal setter to be used by constructors only! Modifies state!
private void SetDefaultsForType(SqlDbType dbType)
{
SmiMetaData smdDflt = GetDefaultForType(dbType);
_databaseType = dbType;
_maxLength = smdDflt.MaxLength;
_precision = smdDflt.Precision;
_scale = smdDflt.Scale;
_localeId = smdDflt.LocaleId;
_compareOptions = smdDflt.CompareOptions;
_isMultiValued = smdDflt._isMultiValued;
_fieldMetaData = smdDflt._fieldMetaData; // This is ok due to immutability
_extendedProperties = smdDflt._extendedProperties; // This is ok due to immutability
}
}
// SmiExtendedMetaData
//
// Adds server-specific type extension information to base metadata, but still portable across a specific server.
//
internal class SmiExtendedMetaData : SmiMetaData
{
private string _name; // context-dependent identifier, i.e. parameter name for parameters, column name for columns, etc.
// three-part name for typed xml schema and for udt names
private string _typeSpecificNamePart1;
private string _typeSpecificNamePart2;
private string _typeSpecificNamePart3;
internal SmiExtendedMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3) :
this(
dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
false,
null,
null,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3)
{
}
// SMI V220 ctor.
internal SmiExtendedMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3) :
base(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
isMultiValued,
fieldMetaData,
extendedProperties)
{
Debug.Assert(null == name || MaxNameLength >= name.Length, "Name is too long");
_name = name;
_typeSpecificNamePart1 = typeSpecificNamePart1;
_typeSpecificNamePart2 = typeSpecificNamePart2;
_typeSpecificNamePart3 = typeSpecificNamePart3;
}
internal string Name
{
get
{
return _name;
}
}
internal string TypeSpecificNamePart1
{
get
{
return _typeSpecificNamePart1;
}
}
internal string TypeSpecificNamePart2
{
get
{
return _typeSpecificNamePart2;
}
}
internal string TypeSpecificNamePart3
{
get
{
return _typeSpecificNamePart3;
}
}
}
// SmiParameterMetaData
//
// MetaData class to send parameter definitions to server.
// Sealed because we don't need to derive from it yet.
internal sealed class SmiParameterMetaData : SmiExtendedMetaData
{
private ParameterDirection _direction;
// SMI V220 ctor.
internal SmiParameterMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3,
ParameterDirection direction) :
base(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
isMultiValued,
fieldMetaData,
extendedProperties,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3)
{
Debug.Assert(ParameterDirection.Input == direction
|| ParameterDirection.Output == direction
|| ParameterDirection.InputOutput == direction
|| ParameterDirection.ReturnValue == direction, "Invalid direction: " + direction);
_direction = direction;
}
internal ParameterDirection Direction
{
get
{
return _direction;
}
}
}
// SmiStorageMetaData
//
// This class represents the addition of storage-level attributes to the hierarchy (i.e. attributes from
// underlying table, source variables, or whatever).
//
// Most values use Null (either IsNullable == true or CLR null) to indicate "Not specified" state. Selection
// of which values allow "not specified" determined by backward compatibility.
//
// Maps approximately to TDS' COLMETADATA token with TABNAME and part of COLINFO thrown in.
internal class SmiStorageMetaData : SmiExtendedMetaData
{
// AllowsDBNull is the only value required to be specified.
private bool _allowsDBNull; // could the column return nulls? equivalent to TDS's IsNullable bit
private string _serverName; // underlying column's server
private string _catalogName; // underlying column's database
private string _schemaName; // underlying column's schema
private string _tableName; // underlying column's table
private string _columnName; // underlying column's name
private SqlBoolean _isKey; // Is this one of a set of key columns that uniquely identify an underlying table?
private bool _isIdentity; // Is this from an identity column
private bool _isColumnSet; // Is this column the XML representation of a columnset?
// SMI V220 ctor.
internal SmiStorageMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3,
bool allowsDBNull,
string serverName,
string catalogName,
string schemaName,
string tableName,
string columnName,
SqlBoolean isKey,
bool isIdentity,
bool isColumnSet) :
base(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
isMultiValued,
fieldMetaData,
extendedProperties,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3)
{
_allowsDBNull = allowsDBNull;
_serverName = serverName;
_catalogName = catalogName;
_schemaName = schemaName;
_tableName = tableName;
_columnName = columnName;
_isKey = isKey;
_isIdentity = isIdentity;
_isColumnSet = isColumnSet;
}
internal SqlBoolean IsKey
{
get
{
return _isKey;
}
}
}
// SmiQueryMetaData
//
// Adds Query-specific attributes.
// Sealed since we don't need to extend it for now.
// Maps to full COLMETADATA + COLINFO + TABNAME tokens on TDS.
internal class SmiQueryMetaData : SmiStorageMetaData
{
private bool _isReadOnly;
private SqlBoolean _isExpression;
private SqlBoolean _isAliased;
private SqlBoolean _isHidden;
// SMI V200 ctor.
internal SmiQueryMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3,
bool allowsDBNull,
string serverName,
string catalogName,
string schemaName,
string tableName,
string columnName,
SqlBoolean isKey,
bool isIdentity,
bool isReadOnly,
SqlBoolean isExpression,
SqlBoolean isAliased,
SqlBoolean isHidden) :
this(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
isMultiValued,
fieldMetaData,
extendedProperties,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3,
allowsDBNull,
serverName,
catalogName,
schemaName,
tableName,
columnName,
isKey,
isIdentity,
false,
isReadOnly,
isExpression,
isAliased,
isHidden)
{
}
// SMI V220 ctor.
internal SmiQueryMetaData(
SqlDbType dbType,
long maxLength,
byte precision,
byte scale,
long localeId,
SqlCompareOptions compareOptions,
bool isMultiValued,
IList<SmiExtendedMetaData> fieldMetaData,
SmiMetaDataPropertyCollection extendedProperties,
string name,
string typeSpecificNamePart1,
string typeSpecificNamePart2,
string typeSpecificNamePart3,
bool allowsDBNull,
string serverName,
string catalogName,
string schemaName,
string tableName,
string columnName,
SqlBoolean isKey,
bool isIdentity,
bool isColumnSet,
bool isReadOnly,
SqlBoolean isExpression,
SqlBoolean isAliased,
SqlBoolean isHidden) :
base(dbType,
maxLength,
precision,
scale,
localeId,
compareOptions,
isMultiValued,
fieldMetaData,
extendedProperties,
name,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3,
allowsDBNull,
serverName,
catalogName,
schemaName,
tableName,
columnName,
isKey,
isIdentity,
isColumnSet)
{
_isReadOnly = isReadOnly;
_isExpression = isExpression;
_isAliased = isAliased;
_isHidden = isHidden;
}
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Globalization;
namespace Lucene.Net.Support
{
/// <summary>
/// A simple class for number conversions.
/// </summary>
public static class Number
{
/// <summary>
/// Min radix value.
/// </summary>
public const int MIN_RADIX = 2;
/// <summary>
/// Max radix value.
/// </summary>
public const int MAX_RADIX = 36;
/*public const int CHAR_MIN_CODE_POINT =
public const int CHAR_MAX_CODE_POINT = */
private const string digits = "0123456789abcdefghijklmnopqrstuvwxyz";
/// <summary>
/// Converts a number to System.String.
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public static string ToString(long number)
{
var s = new System.Text.StringBuilder();
if (number == 0)
{
s.Append("0");
}
else
{
if (number < 0)
{
s.Append("-");
number = -number;
}
while (number > 0)
{
char c = digits[(int)number % 36];
s.Insert(0, c);
number = number / 36;
}
}
return s.ToString();
}
/// <summary>
/// Converts a number to System.String.
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
public static System.String ToString(float f)
{
if (((float)(int)f) == f)
{
return ((int)f).ToString() + ".0";
}
else
{
return f.ToString(NumberFormatInfo.InvariantInfo);
}
}
/// <summary>
/// Converts a number to System.String in the specified radix.
/// </summary>
/// <param name="i">A number to be converted.</param>
/// <param name="radix">A radix.</param>
/// <returns>A System.String representation of the number in the specified redix.</returns>
public static String ToString(long i, int radix)
{
if (radix < MIN_RADIX || radix > MAX_RADIX)
radix = 10;
var buf = new char[65];
int charPos = 64;
bool negative = (i < 0);
if (!negative)
{
i = -i;
}
while (i <= -radix)
{
buf[charPos--] = digits[(int)(-(i % radix))];
i = i / radix;
}
buf[charPos] = digits[(int)(-i)];
if (negative)
{
buf[--charPos] = '-';
}
return new System.String(buf, charPos, (65 - charPos));
}
/// <summary>
/// Parses a number in the specified radix.
/// </summary>
/// <param name="s">An input System.String.</param>
/// <param name="radix">A radix.</param>
/// <returns>The parsed number in the specified radix.</returns>
public static long Parse(System.String s, int radix)
{
if (s == null)
{
throw new ArgumentException("null");
}
if (radix < MIN_RADIX)
{
throw new NotSupportedException("radix " + radix +
" less than Number.MIN_RADIX");
}
if (radix > MAX_RADIX)
{
throw new NotSupportedException("radix " + radix +
" greater than Number.MAX_RADIX");
}
long result = 0;
long mult = 1;
s = s.ToLower();
for (int i = s.Length - 1; i >= 0; i--)
{
int weight = digits.IndexOf(s[i]);
if (weight == -1)
throw new FormatException("Invalid number for the specified radix");
result += (weight * mult);
mult *= radix;
}
return result;
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, int bits)
{
return (int)(((uint)number) >> bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, int bits)
{
return (long)(((ulong)number) >> bits);
}
/// <summary>
/// Returns the index of the first bit that is set to true that occurs
/// on or after the specified starting index. If no such bit exists
/// then -1 is returned.
/// </summary>
/// <param name="bits">The BitArray object.</param>
/// <param name="fromIndex">The index to start checking from (inclusive).</param>
/// <returns>The index of the next set bit.</returns>
public static int NextSetBit(System.Collections.BitArray bits, int fromIndex)
{
for (int i = fromIndex; i < bits.Length; i++)
{
if (bits[i] == true)
{
return i;
}
}
return -1;
}
/// <summary>
/// Converts a System.String number to long.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static long ToInt64(System.String s)
{
long number = 0;
long factor;
// handle negative number
if (s.StartsWith("-"))
{
s = s.Substring(1);
factor = -1;
}
else
{
factor = 1;
}
// generate number
for (int i = s.Length - 1; i > -1; i--)
{
int n = digits.IndexOf(s[i]);
// not supporting fractional or scientific notations
if (n < 0)
throw new System.ArgumentException("Invalid or unsupported character in number: " + s[i]);
number += (n * factor);
factor *= 36;
}
return number;
}
public static int NumberOfLeadingZeros(int num)
{
if (num == 0)
return 32;
uint unum = (uint)num;
int count = 0;
int i;
for (i = 0; i < 32; ++i)
{
if ((unum & 0x80000000) == 0x80000000)
break;
count++;
unum <<= 1;
}
return count;
}
public static int NumberOfLeadingZeros(long num)
{
if (num == 0)
return 64;
ulong unum = (ulong)num;
int count = 0;
int i;
for (i = 0; i < 64; ++i)
{
if ((unum & 0x8000000000000000L) == 0x8000000000000000L)
break;
count++;
unum <<= 1;
}
return count;
}
public static int NumberOfTrailingZeros(int num)
{
if (num == 0)
return 32;
uint unum = (uint)num;
int count = 0;
int i;
for (i = 0; i < 32; ++i)
{
if ((unum & 1) == 1)
break;
count++;
unum >>= 1;
}
return count;
}
public static int NumberOfTrailingZeros(long num)
{
if (num == 0)
return 64;
ulong unum = (ulong)num;
int count = 0;
int i;
for (i = 0; i < 64; ++i)
{
if ((unum & 1L) == 1L)
break;
count++;
unum >>= 1;
}
return count;
}
// Returns the number of 1-bits in the number
public static int BitCount(long num)
{
int bitcount = 0;
// To use the > 0 condition
ulong nonNegNum = (ulong) num;
while (nonNegNum > 0)
{
bitcount += (int)(nonNegNum & 0x1);
nonNegNum >>= 1;
}
return bitcount;
}
public static int Signum(long a)
{
return a == 0 ? 0 : (int)(a / Math.Abs(a));
}
public static int Signum(long a, long b)
{
if (a < b)
{
return -1;
}
else if (a > b)
{
return 1;
}
else
{
return 0;
}
}
// Returns the number of 1-bits in the number
public static int BitCount(int num)
{
int bitcount = 0;
while (num > 0)
{
bitcount += (num & 1);
num >>= 1;
}
return bitcount;
}
public static int RotateLeft(int i, int reps)
{
uint val = (uint)i;
return (int)((val << reps) | (val >> (32 - reps)));
}
public static int RotateRight(int i, int reps)
{
uint val = (uint)i;
return (int)((val >> reps) | (val << (32 - reps)));
}
public static string ToBinaryString(int value)
{
var sb = new System.Text.StringBuilder();
var uval = (uint)value;
for (int i = 0; i < 32; i++)
{
if ((uval & 0x80000000) == 0x80000000)
sb.Append('1');
else
sb.Append('0');
uval <<= 1;
}
return sb.ToString();
}
public static float IntBitsToFloat(int value)
{
return BitConverter.ToSingle(BitConverter.GetBytes(value), 0);
}
public static int FloatToRawIntBits(float value)
{
// TODO: does this handle NaNs the same?
return BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
}
public static int FloatToIntBits(float value)
{
if (float.IsNaN(value))
{
return 0x7fc00000;
}
// TODO it is claimed that this could be faster
return BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
}
public static long FloatToLongBits(float value)
{
return BitConverter.ToInt64(BitConverter.GetBytes(value), 0);
}
public static long DoubleToRawLongBits(double value)
{
return BitConverter.DoubleToInt64Bits(value);
}
public static long DoubleToLongBits(double value)
{
if (double.IsNaN(value))
{
return 0x7ff8000000000000L;
}
return BitConverter.DoubleToInt64Bits(value);
}
//Flips the endianness from Little-Endian to Big-Endian
//2 bytes
public static char FlipEndian(char x)
{
return (char)((x & 0xFFU) << 8 | (x & 0xFF00U) >> 8);
}
//2 bytes
public static short FlipEndian(short x)
{
return (short)((x & 0xFFU) << 8 | (x & 0xFF00U) >> 8);
}
//4 bytes
public static int FlipEndian(int x)
{
return (int)((x & 0x000000FFU) << 24 | (x & 0x0000FF00U) << 8 | (x & 0x00FF0000U) >> 8 | (x & 0xFF000000U) >> 24);
}
//8 bytes
public static long FlipEndian(long x)
{
ulong y = (ulong)x;
return (long)(
(y & 0x00000000000000FFUL) << 56 | (y & 0x000000000000FF00UL) << 40 |
(y & 0x0000000000FF0000UL) << 24 | (y & 0x00000000FF000000UL) << 8 |
(y & 0x000000FF00000000UL) >> 8 | (y & 0x0000FF0000000000UL) >> 24 |
(y & 0x00FF000000000000UL) >> 40 | (y & 0xFF00000000000000UL) >> 56);
}
//4 bytes
public static float FlipEndian(float f)
{
int x = FloatToIntBits(f);
return IntBitsToFloat(FlipEndian(x));
}
//8 bytes
public static double FlipEndian(double d)
{
long x = BitConverter.DoubleToInt64Bits(d);
return BitConverter.Int64BitsToDouble(FlipEndian(x));
}
public static bool IsNumber(this object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.ReflectionModel
{
internal class ReflectionComposablePart : ComposablePart, ICompositionElement
{
private readonly ReflectionComposablePartDefinition _definition;
private volatile Dictionary<ImportDefinition, object> _importValues = null;
private volatile Dictionary<ImportDefinition, ImportingItem> _importsCache = null;
private volatile Dictionary<int, ExportingMember> _exportsCache = null;
private volatile bool _invokeImportsSatisfied = true;
private bool _initialCompositionComplete = false;
private volatile object _cachedInstance;
private readonly object _lock = new object();
public ReflectionComposablePart(ReflectionComposablePartDefinition definition)
{
Requires.NotNull(definition, nameof(definition));
_definition = definition;
}
public ReflectionComposablePart(ReflectionComposablePartDefinition definition, object attributedPart)
{
Requires.NotNull(definition, nameof(definition));
Requires.NotNull(attributedPart, nameof(attributedPart));
_definition = definition;
if (attributedPart is ValueType)
{
throw new ArgumentException(SR.ArgumentValueType, nameof(attributedPart));
}
_cachedInstance = attributedPart;
}
protected virtual void EnsureRunning()
{
}
protected void RequiresRunning()
{
EnsureRunning();
}
protected virtual void ReleaseInstanceIfNecessary(object instance)
{
}
private Dictionary<ImportDefinition, object> ImportValues
{
get
{
var value = _importValues;
if (value == null)
{
lock (_lock)
{
value = _importValues;
if (value == null)
{
value = new Dictionary<ImportDefinition, object>();
_importValues = value;
}
}
}
return value;
}
}
private Dictionary<ImportDefinition, ImportingItem> ImportsCache
{
get
{
var value = _importsCache;
if (value == null)
{
lock (_lock)
{
if (value == null)
{
value = new Dictionary<ImportDefinition, ImportingItem>();
_importsCache = value;
}
}
}
return value;
}
}
protected object CachedInstance
{
get
{
lock (_lock)
{
return _cachedInstance;
}
}
}
public ReflectionComposablePartDefinition Definition
{
get
{
RequiresRunning();
return _definition;
}
}
public override IDictionary<string, object> Metadata
{
get
{
RequiresRunning();
return Definition.Metadata;
}
}
public sealed override IEnumerable<ImportDefinition> ImportDefinitions
{
get
{
RequiresRunning();
return Definition.ImportDefinitions;
}
}
public sealed override IEnumerable<ExportDefinition> ExportDefinitions
{
get
{
RequiresRunning();
return Definition.ExportDefinitions;
}
}
string ICompositionElement.DisplayName
{
get { return GetDisplayName(); }
}
ICompositionElement ICompositionElement.Origin
{
get { return Definition; }
}
// This is the ONLY method which is not executed under the ImportEngine composition lock.
// We need to protect all state that is accesses
public override object GetExportedValue(ExportDefinition definition)
{
RequiresRunning();
// given the implementation of the ImportEngine, this iwll be called under a lock if the part is still being composed
// This is only called outside of the lock when the part is fully composed
// based on that we only protect:
// _exportsCache - and thus all calls to GetExportingMemberFromDefinition
// access to _importValues
// access to _initialCompositionComplete
// access to _instance
Requires.NotNull(definition, nameof(definition));
ExportingMember member = null;
lock (_lock)
{
member = GetExportingMemberFromDefinition(definition);
if (member == null)
{
throw ExceptionBuilder.CreateExportDefinitionNotOnThisComposablePart(nameof(definition));
}
EnsureGettable();
}
return GetExportedValue(member);
}
public override void SetImport(ImportDefinition definition, IEnumerable<Export> exports)
{
RequiresRunning();
Requires.NotNull(definition, nameof(definition));
Requires.NotNull(exports, nameof(exports));
ImportingItem item = GetImportingItemFromDefinition(definition);
if (item == null)
{
throw ExceptionBuilder.CreateImportDefinitionNotOnThisComposablePart(nameof(definition));
}
EnsureSettable(definition);
// Avoid walking over exports many times
Export[] exportsAsArray = exports.AsArray();
EnsureCardinality(definition, exportsAsArray);
SetImport(item, exportsAsArray);
}
public override void Activate()
{
RequiresRunning();
SetNonPrerequisiteImports();
// Whenever we are composed/recomposed notify the instance
NotifyImportSatisfied();
lock (_lock)
{
_initialCompositionComplete = true;
_importValues = null;
_importsCache = null;
}
}
public override string ToString()
{
return GetDisplayName();
}
private object GetExportedValue(ExportingMember member)
{
object instance = null;
if (member.RequiresInstance)
{ // Only activate the instance if we actually need to
instance = GetInstanceActivatingIfNeeded();
}
return member.GetExportedValue(instance, _lock);
}
private void SetImport(ImportingItem item, Export[] exports)
{
object value = item.CastExportsToImportType(exports);
lock (_lock)
{
_invokeImportsSatisfied = true;
ImportValues[item.Definition] = value;
}
}
private object GetInstanceActivatingIfNeeded()
{
var cachedInstance = _cachedInstance;
if (cachedInstance != null)
{
return cachedInstance;
}
else
{
ConstructorInfo constructor = null;
object[] arguments = null;
// determine whether activation is required, and collect necessary information for activation
// we need to do that under a lock
lock (_lock)
{
if (!RequiresActivation())
{
return null;
}
constructor = Definition.GetConstructor();
if (constructor == null)
{
throw new ComposablePartException(
SR.Format(
SR.ReflectionModel_PartConstructorMissing,
Definition.GetPartType().FullName),
Definition.ToElement());
}
arguments = GetConstructorArguments();
}
// create instance outside of the lock
object createdInstance = CreateInstance(constructor, arguments);
SetPrerequisiteImports();
// set the created instance
if (_cachedInstance == null)
{
lock (_lock)
{
if (_cachedInstance == null)
{
_cachedInstance = createdInstance;
createdInstance = null;
}
}
}
// if the instance has been already set
if (createdInstance == null)
{
ReleaseInstanceIfNecessary(createdInstance);
}
}
return _cachedInstance;
}
private object[] GetConstructorArguments()
{
ReflectionParameterImportDefinition[] parameterImports = ImportDefinitions.OfType<ReflectionParameterImportDefinition>().ToArray();
object[] arguments = new object[parameterImports.Length];
UseImportedValues(
parameterImports,
(import, definition, value) =>
{
if (definition.Cardinality == ImportCardinality.ZeroOrMore && !import.ImportType.IsAssignableCollectionType)
{
throw new ComposablePartException(
SR.Format(
SR.ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned,
Definition.GetPartType().FullName,
definition.ImportingLazyParameter.Value.Name),
Definition.ToElement());
}
arguments[definition.ImportingLazyParameter.Value.Position] = value;
},
true);
return arguments;
}
// alwayc called under a lock
private bool RequiresActivation()
{
// If we have any imports then we need activation
// (static imports are not supported)
if (ImportDefinitions.Any())
{
return true;
}
// If we have any instance exports, then we also
// need activation.
return ExportDefinitions.Any(definition =>
{
ExportingMember member = GetExportingMemberFromDefinition(definition);
return member.RequiresInstance;
});
}
// this is called under a lock
private void EnsureGettable()
{
// If we're already composed then we know that
// all pre-req imports have been satisfied
if (_initialCompositionComplete)
{
return;
}
// Make sure all pre-req imports have been set
foreach (ImportDefinition definition in ImportDefinitions.Where(definition => definition.IsPrerequisite))
{
if (_importValues == null || !ImportValues.ContainsKey(definition))
{
throw new InvalidOperationException(SR.Format(
SR.InvalidOperation_GetExportedValueBeforePrereqImportSet,
definition.ToElement().DisplayName));
}
}
}
private void EnsureSettable(ImportDefinition definition)
{
lock (_lock)
{
if (_initialCompositionComplete && !definition.IsRecomposable)
{
throw new InvalidOperationException(SR.InvalidOperation_DefinitionCannotBeRecomposed);
}
}
}
private static void EnsureCardinality(ImportDefinition definition, Export[] exports)
{
Requires.NullOrNotNullElements(exports, nameof(exports));
ExportCardinalityCheckResult result = ExportServices.CheckCardinality(definition, exports);
switch (result)
{
case ExportCardinalityCheckResult.NoExports:
throw new ArgumentException(SR.Argument_ExportsEmpty, nameof(exports));
case ExportCardinalityCheckResult.TooManyExports:
throw new ArgumentException(SR.Argument_ExportsTooMany, nameof(exports));
default:
if (result != ExportCardinalityCheckResult.Match)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
break;
}
}
private object CreateInstance(ConstructorInfo constructor, object[] arguments)
{
Exception exception = null;
object instance = null;
try
{
instance = constructor.SafeInvoke(arguments);
}
catch (TypeInitializationException ex)
{
exception = ex;
}
catch (TargetInvocationException ex)
{
exception = ex.InnerException;
}
if (exception != null)
{
throw new ComposablePartException(
SR.Format(
SR.ReflectionModel_PartConstructorThrewException,
Definition.GetPartType().FullName),
Definition.ToElement(),
exception);
}
return instance;
}
private void SetNonPrerequisiteImports()
{
IEnumerable<ImportDefinition> members = ImportDefinitions.Where(import => !import.IsPrerequisite);
// NOTE: Dev10 484204 The validation is turned off for post imports because of it broke declarative composition
UseImportedValues(members, SetExportedValueForImport, false);
}
private void SetPrerequisiteImports()
{
IEnumerable<ImportDefinition> members = ImportDefinitions.Where(import => import.IsPrerequisite);
// NOTE: Dev10 484204 The validation is turned off for post imports because of it broke declarative composition
UseImportedValues(members, SetExportedValueForImport, false);
}
private void SetExportedValueForImport(ImportingItem import, ImportDefinition definition, object value)
{
ImportingMember importMember = (ImportingMember)import;
object instance = GetInstanceActivatingIfNeeded();
importMember.SetExportedValue(instance, value);
}
private void UseImportedValues<TImportDefinition>(IEnumerable<TImportDefinition> definitions, Action<ImportingItem, TImportDefinition, object> useImportValue, bool errorIfMissing)
where TImportDefinition : ImportDefinition
{
var result = CompositionResult.SucceededResult;
foreach (var definition in definitions)
{
ImportingItem import = GetImportingItemFromDefinition(definition);
object value;
if (!TryGetImportValue(definition, out value))
{
if (!errorIfMissing)
{
continue;
}
if (definition.Cardinality == ImportCardinality.ExactlyOne)
{
var error = CompositionError.Create(
CompositionErrorId.ImportNotSetOnPart,
SR.ImportNotSetOnPart,
Definition.GetPartType().FullName,
definition.ToString());
result = result.MergeError(error);
continue;
}
else
{
value = import.CastExportsToImportType(Array.Empty<Export>());
}
}
useImportValue(import, definition, value);
}
result.ThrowOnErrors();
}
private bool TryGetImportValue(ImportDefinition definition, out object value)
{
lock (_lock)
{
if (_importValues != null && ImportValues.TryGetValue(definition, out value))
{
ImportValues.Remove(definition);
return true;
}
}
value = null;
return false;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void NotifyImportSatisfied()
{
if (_invokeImportsSatisfied)
{
IPartImportsSatisfiedNotification notify = GetInstanceActivatingIfNeeded() as IPartImportsSatisfiedNotification;
lock (_lock)
{
if (!_invokeImportsSatisfied)
{
//Already notified on another thread
return;
}
_invokeImportsSatisfied = false;
}
if (notify != null)
{
try
{
notify.OnImportsSatisfied();
}
catch (Exception exception)
{
throw new ComposablePartException(
SR.Format(
SR.ReflectionModel_PartOnImportsSatisfiedThrewException,
Definition.GetPartType().FullName),
Definition.ToElement(),
exception);
}
}
}
}
// this is always called under a lock
private ExportingMember GetExportingMemberFromDefinition(ExportDefinition definition)
{
ExportingMember result;
ReflectionMemberExportDefinition reflectionExport = definition as ReflectionMemberExportDefinition;
if (reflectionExport == null)
{
return null;
}
int exportIndex = reflectionExport.GetIndex();
if (_exportsCache == null)
{
_exportsCache = new Dictionary<int, ExportingMember>();
}
if (!_exportsCache.TryGetValue(exportIndex, out result))
{
result = GetExportingMember(definition);
if (result != null)
{
_exportsCache[exportIndex] = result;
}
}
return result;
}
private ImportingItem GetImportingItemFromDefinition(ImportDefinition definition)
{
ImportingItem result;
if (!ImportsCache.TryGetValue(definition, out result))
{
result = GetImportingItem(definition);
if (result != null)
{
ImportsCache[definition] = result;
}
}
return result;
}
private static ImportingItem GetImportingItem(ImportDefinition definition)
{
ReflectionImportDefinition reflectionDefinition = definition as ReflectionImportDefinition;
if (reflectionDefinition != null)
{
return reflectionDefinition.ToImportingItem();
}
// Don't recognize it
return null;
}
private static ExportingMember GetExportingMember(ExportDefinition definition)
{
ReflectionMemberExportDefinition exportDefinition = definition as ReflectionMemberExportDefinition;
if (exportDefinition != null)
{
return exportDefinition.ToExportingMember();
}
// Don't recognize it
return null;
}
private string GetDisplayName()
{
return _definition.GetPartType().GetDisplayName();
}
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Rasters;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using ArcGISRuntime.Samples.Managers;
namespace ArcGISRuntime.Samples.RasterHillshade
{
[Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("134d60f50e184e8fa56365f44e5ce3fb")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Raster hillshade renderer",
category: "Layers",
description: "Use a hillshade renderer on a raster.",
instructions: "Configure the options for rendering, then tap 'Apply hillshade'.",
tags: new[] { "Visualization", "hillshade", "raster", "shadow", "slope" })]
public class RasterHillshade : Activity
{
// Constant to store a z-factor (conversion constant) applied to the hillshade.
// If needed, this can be used to convert z-values to the same unit as the x/y coordinates or to apply a vertical exaggeration.
private const double ZFactor = 1.0;
// Constants to store the Pixel Size Power and Pixel Size Factor values.
// Use these to account for altitude changes (scale) as the viewer zooms in and out (recommended when using worldwide datasets).
private const double PixelSizePower = 1.0;
private const double PixelSizeFactor = 1.0;
// Constant to store the bit depth (pixel depth), which determines the range of values that the hillshade raster can store.
private const int PixelBitDepth = 8;
// Map view control to show the hillshade
private MapView _myMapView;
// Store a reference to the layer
private RasterLayer _rasterLayer;
// Store a selected slope type
private SlopeType _slopeType = SlopeType.PercentRise;
// TextView controls to show the selected azimuth and altitude values
private TextView _azimuthTextView;
private TextView _altitudeTextView;
// Button to launch the slope type choices menu
private Button _slopeTypeButton;
// Button to apply the renderer.
private Button _applyHillshadeButton;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Raster hillshade";
// Create the layout
CreateLayout();
// Initialize the app
Initialize();
}
private void CreateLayout()
{
// Create a stack layout for the entire page
LinearLayout mainLayout = new LinearLayout(this)
{
Orientation = Orientation.Vertical
};
// Create a button to show the available slope types for the user to choose from
_slopeTypeButton = new Button(this)
{
Text = "Slope type: " + _slopeType.ToString()
};
// Show a popup menu of available slope types when the button is clicked
_slopeTypeButton.Click += (s, e) =>
{
// Get the button that raised the event
Button slopeChoiceButton = s as Button;
// Create menu to show slope options
PopupMenu slopeTypeMenu = new PopupMenu(this, slopeChoiceButton);
slopeTypeMenu.MenuItemClick += (sndr,evt)=>
{
// Get the name of the selected slope type
string selectedSlope = evt.Item.TitleCondensedFormatted.ToString();
// Find and store the corresponding slope type enum
foreach (SlopeType slope in Enum.GetValues(typeof(SlopeType)))
{
if (slope.ToString() == selectedSlope)
{
_slopeType = slope;
_slopeTypeButton.Text = "Slope type: " + selectedSlope;
}
}
};
// Create menu options
foreach (SlopeType slope in Enum.GetValues(typeof(SlopeType)))
{
slopeTypeMenu.Menu.Add(slope.ToString());
}
// Show menu in the view
slopeTypeMenu.Show();
};
// Create a slider (SeekBar) control for selecting an azimuth angle
SeekBar azimuthSlider = new SeekBar(this)
{
// Set the slider width and height
LayoutParameters = new ViewGroup.LayoutParams(350, 60),
// Set a maximum slider value of 360 (minimum is 0)
Max = 360
};
// When the slider changes, show the new value in the label
azimuthSlider.ProgressChanged += (s, e) =>
{
_azimuthTextView.Text = e.Progress.ToString();
};
// Create a slider (SeekBar) control for selecting an altitude angle
SeekBar altitudeSlider = new SeekBar(this)
{
// Set the slider width and height
LayoutParameters = new ViewGroup.LayoutParams(350, 60),
// Set a maximum slider value of 90 (minimum is 0)
Max = 90
};
// When the slider changes, show the new value in the label
altitudeSlider.ProgressChanged += (s, e) =>
{
_altitudeTextView.Text = e.Progress.ToString();
};
// Create labels (TextViews) to show the selected altitude and azimuth values
_altitudeTextView = new TextView(this);
_azimuthTextView = new TextView(this);
// Create a horizontal layout for the altitude slider and text
LinearLayout altitudeControls = new LinearLayout(this);
altitudeControls.SetGravity(GravityFlags.Center);
// Add the altitude selection controls
altitudeControls.AddView(new TextView(this) { Text = "Altitude:" });
altitudeControls.AddView(altitudeSlider);
altitudeControls.AddView(_altitudeTextView);
// Create a horizontal layout for the azimuth slider and text
LinearLayout azimuthControls = new LinearLayout(this);
azimuthControls.SetGravity(GravityFlags.Center);
// Add the azimuth selection controls
azimuthControls.AddView(new TextView(this) { Text = "Azimuth:" });
azimuthControls.AddView(azimuthSlider);
azimuthControls.AddView(_azimuthTextView);
// Create a button to create and apply a hillshade renderer to the raster layer
_applyHillshadeButton = new Button(this)
{
Text = "Apply hillshade"
};
// Handle the click event to apply the hillshade renderer
_applyHillshadeButton.Click += ApplyHillshadeButton_Click;
// Add the slope type button to the layout
mainLayout.AddView(_slopeTypeButton);
// Add the slider controls to the layout
mainLayout.AddView(altitudeControls);
mainLayout.AddView(azimuthControls);
// Set the default values for the azimuth and altitude
altitudeSlider.Progress = 45;
azimuthSlider.Progress = 270;
// Add the apply hillshade renderer button
mainLayout.AddView(_applyHillshadeButton);
// Create the map view
_myMapView = new MapView(this);
// Add the map view to the layout
mainLayout.AddView(_myMapView);
// Set the layout as the sample view
SetContentView(mainLayout);
}
private async void Initialize()
{
// Create a map with a streets basemap
Map map = new Map(BasemapStyle.ArcGISStreets);
// Get the file name for the local raster dataset
string filepath = GetRasterPath();
// Load the raster file
Raster rasterFile = new Raster(filepath);
try
{
// Create and load a new raster layer to show the image
_rasterLayer = new RasterLayer(rasterFile);
await _rasterLayer.LoadAsync();
// Create a viewpoint with the raster's full extent
Viewpoint fullRasterExtent = new Viewpoint(_rasterLayer.FullExtent);
// Set the initial viewpoint for the map
map.InitialViewpoint = fullRasterExtent;
// Add the layer to the map
map.OperationalLayers.Add(_rasterLayer);
// Add the map to the map view
_myMapView.Map = map;
}
catch (Exception e)
{
new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
}
}
private void ApplyHillshadeButton_Click(object sender, EventArgs e)
{
// Get the current azimuth and altitude parameter values
int altitude = 0;
int azimuth = 0;
int.TryParse(_altitudeTextView.Text, out altitude);
int.TryParse(_azimuthTextView.Text, out azimuth);
// Create a hillshade renderer that uses the values selected by the user
HillshadeRenderer hillshadeRenderer = new HillshadeRenderer(altitude, azimuth, ZFactor, _slopeType, PixelSizeFactor, PixelSizePower, PixelBitDepth);
// Apply the new renderer to the raster layer
_rasterLayer.Renderer = hillshadeRenderer;
}
private static string GetRasterPath()
{
return DataManager.GetDataFolder("134d60f50e184e8fa56365f44e5ce3fb", "srtm-hillshade", "srtm.tiff");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase
{
private enum Operation
{
Add,
Set,
Remove,
Last,
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedDictionary<int, bool>();
var actual = ImmutableSortedDictionary<int, bool>.Empty;
int seed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int key;
do
{
key = random.Next();
}
while (expected.ContainsKey(key));
bool value = random.Next() % 2 == 0;
Debug.WriteLine("Adding \"{0}\"={1} to the set.", key, value);
expected.Add(key, value);
actual = actual.Add(key, value);
break;
case Operation.Set:
bool overwrite = expected.Count > 0 && random.Next() % 2 == 0;
if (overwrite)
{
int position = random.Next(expected.Count);
key = expected.Skip(position).First().Key;
}
else
{
do
{
key = random.Next();
}
while (expected.ContainsKey(key));
}
value = random.Next() % 2 == 0;
Debug.WriteLine("Setting \"{0}\"={1} to the set (overwrite={2}).", key, value, overwrite);
expected[key] = value;
actual = actual.SetItem(key, value);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
key = expected.Skip(position).First().Key;
Debug.WriteLine("Removing element \"{0}\" from the set.", key);
Assert.True(expected.Remove(key));
actual = actual.Remove(key);
}
break;
}
Assert.Equal<KeyValuePair<int, bool>>(expected.ToList(), actual.ToList());
}
}
[Fact]
public void AddExistingKeySameValueTest()
{
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft");
AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void AddExistingKeyDifferentValueTest()
{
AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void ToUnorderedTest()
{
var sortedMap = Empty<int, GenericParameterHelper>().AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper(n))));
var unsortedMap = sortedMap.ToImmutableDictionary();
Assert.IsAssignableFrom(typeof(ImmutableDictionary<int, GenericParameterHelper>), unsortedMap);
Assert.Equal(sortedMap.Count, unsortedMap.Count);
Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(sortedMap.ToList(), unsortedMap.ToList());
}
[Fact]
public void SortChangeTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("Johnny"));
Assert.False(map.ContainsKey("johnny"));
var newMap = map.ToImmutableSortedDictionary(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, newMap.Count);
Assert.True(newMap.ContainsKey("Johnny"));
Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive
}
[Fact]
public void InitialBulkAddUniqueTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("c", "d"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
var actual = map.AddRange(uniqueEntries);
Assert.Equal(2, actual.Count);
}
[Fact]
public void InitialBulkAddWithExactDuplicatesTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("a", "b"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
var actual = map.AddRange(uniqueEntries);
Assert.Equal(1, actual.Count);
}
[Fact]
public void ContainsValueTest()
{
this.ContainsValueTestHelper(ImmutableSortedDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper());
}
[Fact]
public void InitialBulkAddWithKeyCollisionTest()
{
var uniqueEntries = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("a", "b"),
new KeyValuePair<string,string>("a", "d"),
};
var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal);
Assert.Throws<ArgumentException>(() => map.AddRange(uniqueEntries));
}
[Fact]
public void Create()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
var dictionary = ImmutableSortedDictionary.Create<string, string>();
Assert.Equal(0, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.Create<string, string>(keyComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.Create(keyComparer, valueComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, valueComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void ToImmutableSortedDictionary()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var valueComparer = StringComparer.CurrentCulture;
ImmutableSortedDictionary<string, string> dictionary = pairs.ToImmutableSortedDictionary();
Assert.Equal(1, dictionary.Count);
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant());
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(Comparer<string>.Default, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer);
dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
Assert.Same(valueComparer, dictionary.ValueComparer);
}
[Fact]
public void WithComparers()
{
var map = ImmutableSortedDictionary.Create<string, string>().Add("a", "1").Add("B", "1");
Assert.Same(Comparer<string>.Default, map.KeyComparer);
Assert.True(map.ContainsKey("a"));
Assert.False(map.ContainsKey("A"));
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
var cultureComparer = StringComparer.CurrentCulture;
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(cultureComparer, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void WithComparersCollisions()
{
// First check where collisions have matching values.
var map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1");
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(1, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.Equal("1", map["a"]);
// Now check where collisions have conflicting values.
map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3");
Assert.Throws<ArgumentException>(() => map.WithComparers(StringComparer.OrdinalIgnoreCase));
// Force all values to be considered equal.
map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Same(EverythingEqual<string>.Default, map.ValueComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void CollisionExceptionMessageContainsKey()
{
var map = ImmutableSortedDictionary.Create<string, string>()
.Add("firstKey", "1").Add("secondKey", "2");
var exception = Assert.Throws<ArgumentException>(() => map.Add("firstKey", "3"));
Assert.Contains("firstKey", exception.Message);
}
[Fact]
public void WithComparersEmptyCollection()
{
var map = ImmutableSortedDictionary.Create<string, string>();
Assert.Same(Comparer<string>.Default, map.KeyComparer);
map = map.WithComparers(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedDictionary.Create<int, int>().Add(3, 5);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedDictionary.Create<string, int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableSortedDictionary.Create<int, int>());
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSortedDictionary.Create<string, string>(), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
}
////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces.
public void EnumerationPerformance()
{
var dictionary = Enumerable.Range(1, 1000).ToImmutableSortedDictionary(k => k, k => k);
var timing = new TimeSpan[3];
var sw = new Stopwatch();
for (int j = 0; j < timing.Length; j++)
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
foreach (var entry in dictionary)
{
}
}
timing[j] = sw.Elapsed;
sw.Reset();
}
string timingText = string.Join(Environment.NewLine, timing);
Debug.WriteLine("Timing:{0}{1}", Environment.NewLine, timingText);
}
////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces.
public void EnumerationPerformance_Empty()
{
var dictionary = ImmutableSortedDictionary<int, int>.Empty;
var timing = new TimeSpan[3];
var sw = new Stopwatch();
for (int j = 0; j < timing.Length; j++)
{
sw.Start();
for (int i = 0; i < 10000; i++)
{
foreach (var entry in dictionary)
{
}
}
timing[j] = sw.Elapsed;
sw.Reset();
}
string timingText = string.Join(Environment.NewLine, timing);
Debug.WriteLine("Timing_Empty:{0}{1}", Environment.NewLine, timingText);
}
protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>()
{
return ImmutableSortedDictionaryTest.Empty<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableSortedDictionary.Create<string, TValue>(comparer);
}
protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).ValueComparer;
}
internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).Root;
}
protected void ContainsValueTestHelper<TKey, TValue>(ImmutableSortedDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsValue(value));
Assert.True(map.Add(key, value).ContainsValue(value));
}
private static IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null)
{
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Text;
namespace System.IO
{
public static partial class Path
{
public static readonly char DirectorySeparatorChar = '\\';
public static readonly char VolumeSeparatorChar = ':';
public static readonly char PathSeparator = ';';
private const string DirectorySeparatorCharAsString = "\\";
private static readonly char[] InvalidFileNameChars =
{
'\"', '<', '>', '|', '\0',
(char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
(char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
(char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
(char)31, ':', '*', '?', '\\', '/'
};
// The max total path is 260, and the max individual component length is 255.
// For example, D:\<256 char file name> isn't legal, even though it's under 260 chars.
internal static readonly int MaxPath = 260;
internal static readonly int MaxLongPath = short.MaxValue;
private static bool IsDirectoryOrVolumeSeparator(char c)
{
return PathInternal.IsDirectorySeparator(c) || VolumeSeparatorChar == c;
}
// Expands the given path to a fully qualified path.
[System.Security.SecuritySafeCritical]
public static string GetFullPath(string path)
{
if (path == null)
throw new ArgumentNullException("path");
string fullPath = NormalizeAndValidatePath(path);
// Emulate FileIOPermissions checks, retained for compatibility (normal invalid characters have already been checked)
if (PathInternal.HasWildCardCharacters(fullPath))
throw new ArgumentException(SR.Argument_InvalidPathChars, "path");
return fullPath;
}
/// <summary>
/// Checks for known bad extended paths (paths that start with \\?\)
/// </summary>
/// <returns>'true' if the path passes validity checks.</returns>
private static bool ValidateExtendedPath(string path)
{
if (path.Length == PathInternal.ExtendedPathPrefix.Length)
{
// Effectively empty and therefore invalid
return false;
}
if (path.StartsWith(PathInternal.UncExtendedPathPrefix, StringComparison.Ordinal))
{
// UNC specific checks
if (path.Length == PathInternal.UncExtendedPathPrefix.Length || path[PathInternal.UncExtendedPathPrefix.Length] == DirectorySeparatorChar)
{
// Effectively empty and therefore invalid (\\?\UNC\ or \\?\UNC\\)
return false;
}
int serverShareSeparator = path.IndexOf(DirectorySeparatorChar, PathInternal.UncExtendedPathPrefix.Length);
if (serverShareSeparator == -1 || serverShareSeparator == path.Length - 1)
{
// Need at least a Server\Share
return false;
}
}
// Segments can't be empty "\\" or contain *just* "." or ".."
char twoBack = '?';
char oneBack = DirectorySeparatorChar;
char currentCharacter;
bool periodSegment = false;
for (int i = PathInternal.ExtendedPathPrefix.Length; i < path.Length; i++)
{
currentCharacter = path[i];
switch (currentCharacter)
{
case '\\':
if (oneBack == DirectorySeparatorChar || periodSegment)
throw new ArgumentException(SR.Arg_PathIllegal);
periodSegment = false;
break;
case '.':
periodSegment = (oneBack == DirectorySeparatorChar || (twoBack == DirectorySeparatorChar && oneBack == '.'));
break;
default:
periodSegment = false;
break;
}
twoBack = oneBack;
oneBack = currentCharacter;
}
if (periodSegment)
{
return false;
}
return true;
}
/// <summary>
/// Normalize the path and check for bad characters or other invalid syntax.
/// </summary>
/// <remarks>
/// The legacy NormalizePath
/// </remarks>
private static string NormalizeAndValidatePath(string path)
{
Debug.Assert(path != null, "path can't be null");
// Embedded null characters are the only invalid character case we want to check up front.
// This is because the nulls will signal the end of the string to Win32 and therefore have
// unpredictable results. Other invalid characters we give a chance to be normalized out.
if (path.IndexOf('\0') != -1)
throw new ArgumentException(SR.Argument_InvalidPathChars, "path");
// Toss out paths with colons that aren't a valid drive specifier.
// Cannot start with a colon and can only be of the form "C:" or "\\?\C:".
// (Note that we used to explicitly check "http:" and "file:"- these are caught by this check now.)
int startIndex = PathInternal.PathStartSkip(path);
bool isExtended = path.Length >= PathInternal.ExtendedPathPrefix.Length + startIndex
&& path.IndexOf(PathInternal.ExtendedPathPrefix, startIndex, PathInternal.ExtendedPathPrefix.Length, StringComparison.Ordinal) >= 0;
if (isExtended)
{
startIndex += PathInternal.ExtendedPathPrefix.Length;
}
// Move past the colon
startIndex += 2;
if ((path.Length > 0 && path[0] == VolumeSeparatorChar)
|| (path.Length >= startIndex && path[startIndex - 1] == VolumeSeparatorChar && !PathInternal.IsValidDriveChar(path[startIndex - 2]))
|| (path.Length > startIndex && path.IndexOf(VolumeSeparatorChar, startIndex) != -1))
{
throw new NotSupportedException(SR.Argument_PathFormatNotSupported);
}
if (isExtended)
{
// If the path is in extended syntax, we don't need to normalize, but we still do some basic validity checks
if (!ValidateExtendedPath(path))
{
throw new ArgumentException(SR.Arg_PathIllegal);
}
// \\?\GLOBALROOT gives access to devices out of the scope of the current user, we
// don't want to allow this for security reasons.
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#nt_namespaces
if (path.StartsWith(@"\\?\globalroot", StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.Arg_PathGlobalRoot);
// Look for illegal path characters.
PathInternal.CheckInvalidPathChars(path);
return path;
}
else
{
// Technically this doesn't matter but we used to throw for this case
if (String.IsNullOrWhiteSpace(path))
throw new ArgumentException(SR.Arg_PathIllegal);
return PathHelper.Normalize(path, checkInvalidCharacters: true, expandShortPaths: true);
}
}
[System.Security.SecuritySafeCritical]
public static string GetTempPath()
{
StringBuilder sb = StringBuilderCache.Acquire(MaxPath);
uint r = Interop.mincore.GetTempPathW(MaxPath, sb);
if (r == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
return GetFullPath(StringBuilderCache.GetStringAndRelease(sb));
}
[System.Security.SecurityCritical]
private static string InternalGetTempFileName(bool checkHost)
{
// checkHost was originally intended for file security checks, but is ignored.
string path = GetTempPath();
StringBuilder sb = StringBuilderCache.Acquire(MaxPath);
uint r = Interop.mincore.GetTempFileNameW(path, "tmp", 0, sb);
if (r == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
return StringBuilderCache.GetStringAndRelease(sb);
}
// Tests if the given path contains a root. A path is considered rooted
// if it starts with a backslash ("\") or a drive letter and a colon (":").
public static bool IsPathRooted(string path)
{
if (path != null)
{
PathInternal.CheckInvalidPathChars(path);
int length = path.Length;
if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])) ||
(length >= 2 && path[1] == VolumeSeparatorChar))
return true;
}
return false;
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null.
public static string GetPathRoot(string path)
{
if (path == null) return null;
PathInternal.CheckInvalidPathChars(path);
// Need to return the normalized directory separator
path = PathInternal.NormalizeDirectorySeparators(path);
int pathRoot = PathInternal.GetRootLength(path);
return pathRoot <= 0 ? string.Empty : path.Substring(0, pathRoot);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ReSharper disable CheckNamespace
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using Validation;
namespace System.Linq
// ReSharper restore CheckNamespace
{
/// <summary>
/// LINQ extension method overrides that offer greater efficiency for <see cref="ImmutableArray{T}"/> than the standard LINQ methods
/// </summary>
public static class ImmutableArrayExtensions
{
#region ImmutableArray<T> extensions
/// <summary>
/// Projects each element of a sequence into a new form.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <typeparam name="TResult">The type of the result element.</typeparam>
/// <param name="immutableArray">The immutable array.</param>
/// <param name="selector">The selector.</param>
[Pure]
public static IEnumerable<TResult> Select<T, TResult>(this ImmutableArray<T> immutableArray, Func<T, TResult> selector)
{
immutableArray.ThrowNullRefIfNotInitialized();
// LINQ Select/Where have optimized treatment for arrays.
// They also do not modify the source arrays or expose them to modifications.
// Therefore we will just apply Select/Where to the underlying this.array array.
return immutableArray.array.Select(selector);
}
/// <summary>
/// Projects each element of a sequence to an <see cref="IEnumerable{T}"/>,
/// flattens the resulting sequences into one sequence, and invokes a result
/// selector function on each element therein.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <paramref name="immutableArray"/>.</typeparam>
/// <typeparam name="TCollection">The type of the intermediate elements collected by <paramref name="collectionSelector"/>.</typeparam>
/// <typeparam name="TResult">The type of the elements of the resulting sequence.</typeparam>
/// <param name="immutableArray">The immutable array.</param>
/// <param name="collectionSelector">A transform function to apply to each element of the input sequence.</param>
/// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> whose elements are the result
/// of invoking the one-to-many transform function <paramref name="collectionSelector"/> on each
/// element of <paramref name="immutableArray"/> and then mapping each of those sequence elements and their
/// corresponding source element to a result element.
/// </returns>
[Pure]
public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(
this ImmutableArray<TSource> immutableArray,
Func<TSource, IEnumerable<TCollection>> collectionSelector,
Func<TSource, TCollection, TResult> resultSelector)
{
immutableArray.ThrowNullRefIfNotInitialized();
if (collectionSelector == null || resultSelector == null)
{
// throw the same exception as would LINQ
return Enumerable.SelectMany(immutableArray, collectionSelector, resultSelector);
}
// This SelectMany overload is used by the C# compiler for a query of the form:
// from i in immutableArray
// from j in anotherCollection
// select Something(i, j);
// SelectMany accepts an IEnumerable<TSource>, and ImmutableArray<TSource> is a struct.
// By having a special implementation of SelectMany that operates on the ImmutableArray's
// underlying array, we can avoid a few allocations, in particular for the boxed
// immutable array object that would be allocated when it's passed as an IEnumerable<T>,
// and for the EnumeratorObject that would be allocated when enumerating the boxed array.
return immutableArray.Length == 0 ?
Enumerable.Empty<TResult>() :
SelectManyIterator(immutableArray, collectionSelector, resultSelector);
}
/// <summary>
/// Filters a sequence of values based on a predicate.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static IEnumerable<T> Where<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
immutableArray.ThrowNullRefIfNotInitialized();
// LINQ Select/Where have optimized treatment for arrays.
// They also do not modify the source arrays or expose them to modifications.
// Therefore we will just apply Select/Where to the underlying this.array array.
return immutableArray.array.Where(predicate);
}
/// <summary>
/// Gets a value indicating whether any elements are in this collection.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static bool Any<T>(this ImmutableArray<T> immutableArray)
{
return immutableArray.Length > 0;
}
/// <summary>
/// Gets a value indicating whether any elements are in this collection
/// that match a given condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="predicate">The predicate.</param>
[Pure]
public static bool Any<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
immutableArray.ThrowNullRefIfNotInitialized();
Requires.NotNull(predicate, "predicate");
foreach (var v in immutableArray.array)
{
if (predicate(v))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets a value indicating whether all elements in this collection
/// match a given condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="predicate">The predicate.</param>
/// <returns>
/// <c>true</c> if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, <c>false</c>.
/// </returns>
[Pure]
public static bool All<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
immutableArray.ThrowNullRefIfNotInitialized();
Requires.NotNull(predicate, "predicate");
foreach (var v in immutableArray.array)
{
if (!predicate(v))
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two sequences are equal according to an equality comparer.
/// </summary>
/// <typeparam name="TDerived">The type of element in the compared array.</typeparam>
/// <typeparam name="TBase">The type of element contained by the collection.</typeparam>
[Pure]
public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, IEqualityComparer<TBase> comparer = null) where TDerived : TBase
{
immutableArray.ThrowNullRefIfNotInitialized();
items.ThrowNullRefIfNotInitialized();
if (object.ReferenceEquals(immutableArray.array, items.array))
{
return true;
}
if (immutableArray.Length != items.Length)
{
return false;
}
if (comparer == null)
{
comparer = EqualityComparer<TBase>.Default;
}
for (int i = 0; i < immutableArray.Length; i++)
{
if (!comparer.Equals(immutableArray.array[i], items.array[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two sequences are equal according to an equality comparer.
/// </summary>
/// <typeparam name="TDerived">The type of element in the compared array.</typeparam>
/// <typeparam name="TBase">The type of element contained by the collection.</typeparam>
[Pure]
public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, IEnumerable<TDerived> items, IEqualityComparer<TBase> comparer = null) where TDerived : TBase
{
Requires.NotNull(items, "items");
if (comparer == null)
{
comparer = EqualityComparer<TBase>.Default;
}
int i = 0;
int n = immutableArray.Length;
foreach (var item in items)
{
if (i == n)
{
return false;
}
if (!comparer.Equals(immutableArray[i], item))
{
return false;
}
i++;
}
return i == n;
}
/// <summary>
/// Determines whether two sequences are equal according to an equality comparer.
/// </summary>
/// <typeparam name="TDerived">The type of element in the compared array.</typeparam>
/// <typeparam name="TBase">The type of element contained by the collection.</typeparam>
[Pure]
public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, Func<TBase, TBase, bool> predicate) where TDerived : TBase
{
Requires.NotNull(predicate, "predicate");
immutableArray.ThrowNullRefIfNotInitialized();
items.ThrowNullRefIfNotInitialized();
if (object.ReferenceEquals(immutableArray.array, items.array))
{
return true;
}
if (immutableArray.Length != items.Length)
{
return false;
}
for (int i = 0, n = immutableArray.Length; i < n; i++)
{
if (!predicate(immutableArray[i], items[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Applies an accumulator function over a sequence.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T Aggregate<T>(this ImmutableArray<T> immutableArray, Func<T, T, T> func)
{
Requires.NotNull(func, "func");
if (immutableArray.Length == 0)
{
return default(T);
}
var result = immutableArray[0];
for (int i = 1, n = immutableArray.Length; i < n; i++)
{
result = func(result, immutableArray[i]);
}
return result;
}
/// <summary>
/// Applies an accumulator function over a sequence.
/// </summary>
/// <typeparam name="TAccumulate">The type of the accumulated value.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static TAccumulate Aggregate<TAccumulate, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func)
{
Requires.NotNull(func, "func");
var result = seed;
foreach (var v in immutableArray.array)
{
result = func(result, v);
}
return result;
}
/// <summary>
/// Applies an accumulator function over a sequence.
/// </summary>
/// <typeparam name="TAccumulate">The type of the accumulated value.</typeparam>
/// <typeparam name="TResult">The type of result returned by the result selector.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static TResult Aggregate<TAccumulate, TResult, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
{
Requires.NotNull(resultSelector, "resultSelector");
return resultSelector(Aggregate(immutableArray, seed, func));
}
/// <summary>
/// Returns the element at a specified index in a sequence.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T ElementAt<T>(this ImmutableArray<T> immutableArray, int index)
{
return immutableArray[index];
}
/// <summary>
/// Returns the element at a specified index in a sequence or a default value if the index is out of range.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T ElementAtOrDefault<T>(this ImmutableArray<T> immutableArray, int index)
{
if (index < 0 || index >= immutableArray.Length)
{
return default(T);
}
return immutableArray[index];
}
/// <summary>
/// Returns the first element in a sequence that satisfies a specified condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T First<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
foreach (var v in immutableArray.array)
{
if (predicate(v))
{
return v;
}
}
// Throw the same exception that LINQ would.
return Enumerable.Empty<T>().First();
}
/// <summary>
/// Returns the first element in a sequence that satisfies a specified condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T First<T>(this ImmutableArray<T> immutableArray)
{
// In the event of an empty array, generate the same exception
// that the linq extension method would.
return immutableArray.Length > 0
? immutableArray[0]
: Enumerable.First(immutableArray.array);
}
/// <summary>
/// Returns the first element of a sequence, or a default value if the sequence contains no elements.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T FirstOrDefault<T>(this ImmutableArray<T> immutableArray)
{
return immutableArray.array.Length > 0 ? immutableArray.array[0] : default(T);
}
/// <summary>
/// Returns the first element of the sequence that satisfies a condition or a default value if no such element is found.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T FirstOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
foreach (var v in immutableArray.array)
{
if (predicate(v))
{
return v;
}
}
return default(T);
}
/// <summary>
/// Returns the last element of a sequence.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T Last<T>(this ImmutableArray<T> immutableArray)
{
// In the event of an empty array, generate the same exception
// that the linq extension method would.
return immutableArray.Length > 0
? immutableArray[immutableArray.Length - 1]
: Enumerable.Last(immutableArray.array);
}
/// <summary>
/// Returns the last element of a sequence that satisfies a specified condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T Last<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
for (int i = immutableArray.Length - 1; i >= 0; i--)
{
if (predicate(immutableArray[i]))
{
return immutableArray[i];
}
}
// Throw the same exception that LINQ would.
return Enumerable.Empty<T>().Last();
}
/// <summary>
/// Returns the last element of a sequence, or a default value if the sequence contains no elements.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T LastOrDefault<T>(this ImmutableArray<T> immutableArray)
{
immutableArray.ThrowNullRefIfNotInitialized();
return immutableArray.array.LastOrDefault();
}
/// <summary>
/// Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T LastOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
for (int i = immutableArray.Length - 1; i >= 0; i--)
{
if (predicate(immutableArray[i]))
{
return immutableArray[i];
}
}
return default(T);
}
/// <summary>
/// Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T Single<T>(this ImmutableArray<T> immutableArray)
{
immutableArray.ThrowNullRefIfNotInitialized();
return immutableArray.array.Single();
}
/// <summary>
/// Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T Single<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
var first = true;
var result = default(T);
foreach (var v in immutableArray.array)
{
if (predicate(v))
{
if (!first)
{
ImmutableArray.TwoElementArray.Single(); // throw the same exception as LINQ would
}
first = false;
result = v;
}
}
if (first)
{
Enumerable.Empty<T>().Single(); // throw the same exception as LINQ would
}
return result;
}
/// <summary>
/// Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
[Pure]
public static T SingleOrDefault<T>(this ImmutableArray<T> immutableArray)
{
immutableArray.ThrowNullRefIfNotInitialized();
return immutableArray.array.SingleOrDefault();
}
/// <summary>
/// Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
[Pure]
public static T SingleOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
{
Requires.NotNull(predicate, "predicate");
var first = true;
var result = default(T);
foreach (var v in immutableArray.array)
{
if (predicate(v))
{
if (!first)
{
ImmutableArray.TwoElementArray.Single(); // throw the same exception as LINQ would
}
first = false;
result = v;
}
}
return result;
}
/// <summary>
/// Creates a dictionary based on the contents of this array.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="keySelector">The key selector.</param>
/// <returns>The newly initialized dictionary.</returns>
[Pure]
public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector)
{
return ToDictionary(immutableArray, keySelector, EqualityComparer<TKey>.Default);
}
/// <summary>
/// Creates a dictionary based on the contents of this array.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TElement">The type of the element.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="keySelector">The key selector.</param>
/// <param name="elementSelector">The element selector.</param>
/// <returns>The newly initialized dictionary.</returns>
[Pure]
public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector)
{
return ToDictionary(immutableArray, keySelector, elementSelector, EqualityComparer<TKey>.Default);
}
/// <summary>
/// Creates a dictionary based on the contents of this array.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="keySelector">The key selector.</param>
/// <param name="comparer">The comparer to initialize the dictionary with.</param>
/// <returns>The newly initialized dictionary.</returns>
[Pure]
public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
Requires.NotNull(keySelector, "keySelector");
var result = new Dictionary<TKey, T>(comparer);
foreach (var v in immutableArray)
{
result.Add(keySelector(v), v);
}
return result;
}
/// <summary>
/// Creates a dictionary based on the contents of this array.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TElement">The type of the element.</typeparam>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <param name="keySelector">The key selector.</param>
/// <param name="elementSelector">The element selector.</param>
/// <param name="comparer">The comparer to initialize the dictionary with.</param>
/// <returns>The newly initialized dictionary.</returns>
[Pure]
public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
Requires.NotNull(keySelector, "keySelector");
Requires.NotNull(elementSelector, "elementSelector");
var result = new Dictionary<TKey, TElement>(immutableArray.Length, comparer);
foreach (var v in immutableArray.array)
{
result.Add(keySelector(v), elementSelector(v));
}
return result;
}
/// <summary>
/// Copies the contents of this array to a mutable array.
/// </summary>
/// <typeparam name="T">The type of element contained by the collection.</typeparam>
/// <param name="immutableArray"></param>
/// <returns>The newly instantiated array.</returns>
[Pure]
public static T[] ToArray<T>(this ImmutableArray<T> immutableArray)
{
immutableArray.ThrowNullRefIfNotInitialized();
if (immutableArray.array.Length == 0)
{
return ImmutableArray<T>.Empty.array;
}
return (T[])immutableArray.array.Clone();
}
#endregion
#region ImmutableArray<T>.Builder extensions
/// <summary>
/// Returns the first element in the collection.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown if the collection is empty.</exception>
[Pure]
public static T First<T>(this ImmutableArray<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
if (!builder.Any())
{
throw new InvalidOperationException();
}
return builder[0];
}
/// <summary>
/// Returns the first element in the collection, or the default value if the collection is empty.
/// </summary>
[Pure]
public static T FirstOrDefault<T>(this ImmutableArray<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
return builder.Any() ? builder[0] : default(T);
}
/// <summary>
/// Returns the last element in the collection.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown if the collection is empty.</exception>
[Pure]
public static T Last<T>(this ImmutableArray<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
if (!builder.Any())
{
throw new InvalidOperationException();
}
return builder[builder.Count - 1];
}
/// <summary>
/// Returns the last element in the collection, or the default value if the collection is empty.
/// </summary>
[Pure]
public static T LastOrDefault<T>(this ImmutableArray<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
return builder.Any() ? builder[builder.Count - 1] : default(T);
}
/// <summary>
/// Returns a value indicating whether this collection contains any elements.
/// </summary>
[Pure]
public static bool Any<T>(this ImmutableArray<T>.Builder builder)
{
Requires.NotNull(builder, "builder");
return builder.Count > 0;
}
#endregion
#region Private Implementation Details
/// <summary>Provides the core iterator implementation of <see cref="SelectMany"/>.</summary>
private static IEnumerable<TResult> SelectManyIterator<TSource, TCollection, TResult>(
this ImmutableArray<TSource> immutableArray,
Func<TSource, IEnumerable<TCollection>> collectionSelector,
Func<TSource, TCollection, TResult> resultSelector)
{
foreach (TSource item in immutableArray.array)
{
foreach (TCollection result in collectionSelector(item))
{
yield return resultSelector(item, result);
}
}
}
#endregion
}
}
| |
using Android.App;
using Android.Content;
using Android.Database;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Lang;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PRAPinnedListView
{
public class PRAListView : ListView, Android.Widget.AbsListView.IOnScrollListener
{
#region Private Fields
// fields used for handling touch events
private Rect mTouchRect = new Rect();
private PointF mTouchPoint = new PointF();
private int mTouchSlop;
private View mTouchTarget;
private MotionEvent mDownEvent;
// fields used for drawing shadow under a pinned section
private GradientDrawable mShadowDrawable;
private int mSectionsDistanceY;
private int mShadowHeight;
PinnedSection mRecycleSection;
PinnedSection mPinnedSection;
int mTranslateY;
//
Android.Widget.AbsListView.IOnScrollListener mDelegateOnScrollListener;
PRADataSetObserver mDataSetObserver = null;
#endregion
#region Constructor
public PRAListView(Context context)
: base(context)
{
InitView();
}
public PRAListView(IntPtr a, JniHandleOwnership b)
: base(a, b)
{
InitView();
}
public PRAListView(Context context, IAttributeSet attrs) :
base(context, attrs)
{
InitView();
}
public PRAListView(Context context, IAttributeSet attrs, int defStyle) :
base(context, attrs, defStyle)
{
InitView();
}
#endregion
#region Init View
private void InitView()
{
mDataSetObserver = new PRADataSetObserver(RecreatePinnedShadow, null);
//
SetOnScrollListener(this);
mTouchSlop = ViewConfiguration.Get(Context).ScaledTouchSlop;
InitShadow(true);
ItemClick -= PRAListView_ItemClick;
ItemClick += PRAListView_ItemClick;
}
void PRAListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
PRAItemClick(this, new PRAListItemClickEventArg<object>(e.Id, e.View, e.Parent, Adapter.GetItem(e.Position).CastBack()));
}
#endregion
#region PRA Event Click
public event EventHandler<PRAListItemClickEventArg<object>> PRAItemClick;
#endregion
#region Set Shadow Visible
public void SetShadowVisible(bool visible)
{
InitShadow(visible);
if (mPinnedSection != null)
{
View v = mPinnedSection.ViewHolder;
Invalidate(v.Left, v.Top, v.Right, v.Bottom + mShadowHeight);
}
}
#endregion
#region Init Shadow
//-- pinned section drawing methods
public void InitShadow(bool visible)
{
if (visible)
{
if (mShadowDrawable == null)
{
mShadowDrawable = new GradientDrawable(GradientDrawable.Orientation.TopBottom,
new int[] { Color.ParseColor("#ffa0a0a0"), Color.ParseColor("#50a0a0a0"), Color.ParseColor("#00a0a0a0") });
mShadowHeight = (int)(8 * Resources.DisplayMetrics.Density);
}
}
else
{
if (mShadowDrawable != null)
{
mShadowDrawable = null;
mShadowHeight = 0;
}
}
}
#endregion
#region Is Item View Type Pinned
public bool IsItemViewTypePinned(IListAdapter adapter, int viewType)
{
if (adapter.GetType().IsAssignableFrom(typeof(HeaderViewListAdapter)))
{
adapter = ((HeaderViewListAdapter)adapter).WrappedAdapter;
}
return ((IPinnedSectionListAdapter)adapter).IsItemViewTypePinned(viewType);
}
#endregion
#region Create Pinned Shadow
/** Create shadow wrapper with a pinned view for a view at given position */
void CreatePinnedShadow(int position)
{
// try to recycle shadow
PinnedSection pinnedShadow = mRecycleSection;
mRecycleSection = null;
// create new shadow, if needed
if (pinnedShadow == null) pinnedShadow = new PinnedSection();
// request new view using recycled view, if such
View pinnedView = Adapter.GetView(position, pinnedShadow.ViewHolder, this);
// read layout parameters
LayoutParams layoutParams = (LayoutParams)pinnedView.LayoutParameters;
if (layoutParams == null)
{
layoutParams = (LayoutParams)GenerateDefaultLayoutParams();
pinnedView.LayoutParameters = layoutParams;
}
MeasureSpecMode heightMode = MeasureSpec.GetMode(layoutParams.Height);
int heightSize = MeasureSpec.GetSize(layoutParams.Height);
if (heightMode == MeasureSpecMode.Unspecified) heightMode = MeasureSpecMode.Exactly;
int maxHeight = Height - ListPaddingTop - ListPaddingBottom;
if (heightSize > maxHeight) heightSize = maxHeight;
// measure & layout
int ws = MeasureSpec.MakeMeasureSpec(Width - ListPaddingLeft - ListPaddingRight, MeasureSpecMode.Exactly);
int hs = MeasureSpec.MakeMeasureSpec(heightSize, heightMode);
pinnedView.Measure(ws, hs);
pinnedView.Layout(0, 0, pinnedView.MeasuredWidth, pinnedView.MeasuredHeight);
mTranslateY = 0;
// initialize pinned shadow
pinnedShadow.ViewHolder = pinnedView;
pinnedShadow.Position = position;
pinnedShadow.ID = Adapter.GetItemId(position);
// store pinned shadow
mPinnedSection = pinnedShadow;
}
#endregion
#region Re Create Pinned Shadow
void RecreatePinnedShadow()
{
DestroyPinnedShadow();
IListAdapter adapter = Adapter;
if (adapter != null && adapter.Count > 0)
{
int firstVisiblePosition = FirstVisiblePosition;
int sectionPosition = FindCurrentSectionPosition(firstVisiblePosition);
if (sectionPosition == -1) return; // no views to pin, exit
EnsureShadowForPosition(sectionPosition,
firstVisiblePosition, LastVisiblePosition - firstVisiblePosition);
}
}
#endregion
#region Destroy Pinned Shadow
void DestroyPinnedShadow()
{
if (mPinnedSection != null)
{
mRecycleSection = mPinnedSection;
mPinnedSection = null;
}
}
#endregion
#region Ensure Shadow For Pins
void EnsureShadowForPosition(int sectionPosition, int firstVisibleItem, int visibleItemCount)
{
if (visibleItemCount < 2)
{ // no need for creating shadow at all, we have a single visible item
DestroyPinnedShadow();
return;
}
if (mPinnedSection != null
&& mPinnedSection.Position != sectionPosition)
{ // invalidate shadow, if required
DestroyPinnedShadow();
}
if (mPinnedSection == null)
{ // create shadow, if empty
CreatePinnedShadow(sectionPosition);
}
// align shadow according to next section position, if needed
int nextPosition = sectionPosition + 1;
if (nextPosition < Count)
{
int nextSectionPosition = FindFirstVisibleSectionPosition(nextPosition,
visibleItemCount - (nextPosition - firstVisibleItem));
if (nextSectionPosition > -1)
{
View nextSectionView = GetChildAt(nextSectionPosition - firstVisibleItem);
int bottom = mPinnedSection.ViewHolder.Bottom + PaddingTop;
mSectionsDistanceY = nextSectionView.Top - bottom;
if (mSectionsDistanceY < 0)
{
// next section overlaps pinned shadow, move it up
mTranslateY = mSectionsDistanceY;
}
else
{
// next section does not overlap with pinned, stick to top
mTranslateY = 0;
}
}
else
{
// no other sections are visible, stick to top
mTranslateY = 0;
mSectionsDistanceY = int.MaxValue;
}
}
}
#endregion
#region First Visible Section Postion
int FindFirstVisibleSectionPosition(int firstVisibleItem, int visibleItemCount)
{
IListAdapter adapter = Adapter;
int adapterDataCount = adapter.Count;
if (LastVisiblePosition >= adapterDataCount) return -1; // dataset has changed, no candidate
if (firstVisibleItem + visibleItemCount >= adapterDataCount)
{//added to prevent index Outofbound (in case)
visibleItemCount = adapterDataCount - firstVisibleItem;
}
for (int childIndex = 0; childIndex < visibleItemCount; childIndex++)
{
int position = firstVisibleItem + childIndex;
int viewType = adapter.GetItemViewType(position);
if (IsItemViewTypePinned(adapter, viewType)) return position;
}
return -1;
}
#endregion
#region Find Current Position
int FindCurrentSectionPosition(int fromPosition)
{
IListAdapter adapter = Adapter;
if (fromPosition >= adapter.Count) return -1; // dataset has changed, no candidate
if (adapter.GetType().IsAssignableFrom(typeof(ISectionIndexer)))
{
// try fast way by asking section indexer
ISectionIndexer indexer = (ISectionIndexer)adapter;
int sectionPosition = indexer.GetSectionForPosition(fromPosition);
int itemPosition = indexer.GetPositionForSection(sectionPosition);
int typeView = adapter.GetItemViewType(itemPosition);
if (IsItemViewTypePinned(adapter, typeView))
{
return itemPosition;
} // else, no luck
}
// try slow way by looking through to the next section item above
for (int position = fromPosition; position >= 0; position--)
{
int viewType = adapter.GetItemViewType(position);
if (IsItemViewTypePinned(adapter, viewType)) return position;
}
return -1; // no candidate found
}
#endregion
#region OnScroll Method
public void OnScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
if (mDelegateOnScrollListener != null)
{ // delegate
mDelegateOnScrollListener.OnScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
//
IListAdapter adapter = Adapter;
if (adapter == null || visibleItemCount == 0) return; // nothing to do
bool isFirstVisibleItemSection = IsItemViewTypePinned(adapter, adapter.GetItemViewType(firstVisibleItem));
if (isFirstVisibleItemSection)
{
View sectionView = GetChildAt(0);
if (sectionView.Top == PaddingTop)
{ // view sticks to the top, no need for pinned shadow
DestroyPinnedShadow();
}
else
{ // section doesn't stick to the top, make sure we have a pinned shadow
EnsureShadowForPosition(firstVisibleItem, firstVisibleItem, visibleItemCount);
}
}
else
{ // section is not at the first visible position
int sectionPosition = FindCurrentSectionPosition(firstVisibleItem);
if (sectionPosition > -1)
{ // we have section position
EnsureShadowForPosition(sectionPosition, firstVisibleItem, visibleItemCount);
}
else
{ // there is no section for the first visible item, destroy shadow
DestroyPinnedShadow();
}
}
}
#endregion
#region OnScroll State Changed
public void OnScrollStateChanged(AbsListView view, ScrollState scrollState)
{
if (mDelegateOnScrollListener != null)
{
mDelegateOnScrollListener.OnScrollStateChanged(view, scrollState);
}
}
#endregion
#region On Set Scroll Listner
public override void SetOnScrollListener(IOnScrollListener l)
{
if (l == this)
{
base.SetOnScrollListener(l);
}
else
{
mDelegateOnScrollListener = l;
}
}
#endregion
#region On Restore Instance State
public override void OnRestoreInstanceState(Android.OS.IParcelable state)
{
base.OnRestoreInstanceState(state);
Post(new RunnableHolder(RecreatePinnedShadow));
}
#endregion
#region Set Item Source
/// <summary>
/// Set list itemsource to adapter to binidng view.
/// </summary>
/// <typeparam name="T">Your modal type.</typeparam>
/// <param name="itemSource">Item collection.</param>
public void SetItemSource<T>(IEnumerable<T> itemSource) where T : IHeaderModel, new()
{
if (itemSource == null)
throw new NullReferenceException("Item source can not be null");
Adapter = new PRAPinnedAdapter<T>(itemSource);
}
#endregion
#region Adapter Property
public override IListAdapter Adapter
{
get
{
return base.Adapter;
}
set
{
base.Adapter = value;
}
}
#endregion
#region On Layout
protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
{
base.OnLayout(changed, left, top, right, bottom);
if (mPinnedSection != null)
{
int parentWidth = right - left - PaddingLeft - PaddingRight;
int shadowWidth = mPinnedSection.ViewHolder.Width;
if (parentWidth != shadowWidth)
{
RecreatePinnedShadow();
}
}
}
#endregion
#region On Dispatch
protected override void DispatchDraw(Canvas canvas)
{
base.DispatchDraw(canvas);
if (mPinnedSection != null)
{
// prepare variables
int pLeft = ListPaddingLeft;
int pTop = ListPaddingTop;
View view = mPinnedSection.ViewHolder;
// draw child
canvas.Save();
int clipHeight = view.Height +
(mShadowDrawable == null ? 0 : System.Math.Min(mShadowHeight, mSectionsDistanceY));
canvas.ClipRect(pLeft, pTop, pLeft + view.Width, pTop + clipHeight);
canvas.Translate(pLeft, pTop + mTranslateY);
DrawChild(canvas, mPinnedSection.ViewHolder, DrawingTime);
if (mShadowDrawable != null && mSectionsDistanceY > 0)
{
mShadowDrawable.SetBounds(mPinnedSection.ViewHolder.Left,
mPinnedSection.ViewHolder.Bottom,
mPinnedSection.ViewHolder.Right,
mPinnedSection.ViewHolder.Bottom + mShadowHeight);
mShadowDrawable.Draw(canvas);
}
canvas.Restore();
}
}
#endregion
#region Dispatched Touch Event
public override bool DispatchTouchEvent(MotionEvent e)
{
float x = e.GetX();
float y = e.GetY();
MotionEventActions action = e.Action;
if (action == MotionEventActions.Down
&& mTouchTarget == null
&& mPinnedSection != null
&& IsPinnedViewTouched(mPinnedSection.ViewHolder, x, y))
{ // create touch target
// user touched pinned view
mTouchTarget = mPinnedSection.ViewHolder;
mTouchPoint.X = x;
mTouchPoint.Y = y;
// copy down event for eventually be used later
mDownEvent = MotionEvent.Obtain(e);
}
if (mTouchTarget != null)
{
if (IsPinnedViewTouched(mTouchTarget, x, y))
{ // forward event to pinned view
mTouchTarget.DispatchTouchEvent(e);
}
if (action == MotionEventActions.Up)
{ // perform onClick on pinned view
base.DispatchTouchEvent(e);
PerformPinnedItemClick();
ClearTouchTarget();
}
else if (action == MotionEventActions.Cancel)
{ // cancel
ClearTouchTarget();
}
else if (action == MotionEventActions.Move)
{
if (System.Math.Abs(y - mTouchPoint.Y) > mTouchSlop)
{
// cancel sequence on touch target
MotionEvent eventM = MotionEvent.Obtain(e);
eventM.Action = MotionEventActions.Cancel;
mTouchTarget.DispatchTouchEvent(eventM);
eventM.Recycle();
// provide correct sequence to super class for further handling
base.DispatchTouchEvent(mDownEvent);
base.DispatchTouchEvent(e);
ClearTouchTarget();
}
}
return true;
}
return base.DispatchTouchEvent(e);
}
#endregion
#region Is Pinned View Touched
private bool IsPinnedViewTouched(View view, float x, float y)
{
view.GetHitRect(mTouchRect);
// by taping top or bottom padding, the list performs on click on a border item.
// we don't add top padding here to keep behavior consistent.
mTouchRect.Top += mTranslateY;
mTouchRect.Bottom += mTranslateY + PaddingTop;
mTouchRect.Left += PaddingLeft;
mTouchRect.Right -= PaddingRight;
return mTouchRect.Contains((int)x, (int)y);
}
#endregion
#region Clear Touch Target
private void ClearTouchTarget()
{
mTouchTarget = null;
if (mDownEvent != null)
{
mDownEvent.Recycle();
mDownEvent = null;
}
}
#endregion
#region Perform Item CLick
private bool PerformPinnedItemClick()
{
if (mPinnedSection == null) return false;
IOnItemClickListener listener = OnItemClickListener;
if (listener != null && Adapter.IsEnabled(mPinnedSection.Position))
{
View view = mPinnedSection.ViewHolder;
PlaySoundEffect(SoundEffects.Click);
if (view != null)
{
view.SendAccessibilityEvent(Android.Views.Accessibility.EventTypes.ViewClicked);
}
listener.OnItemClick(this, view, mPinnedSection.Position, mPinnedSection.ID);
return true;
}
return false;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using d60.Cirqus.Aggregates;
using d60.Cirqus.Commands;
using d60.Cirqus.Config;
using d60.Cirqus.Events;
using d60.Cirqus.Logging;
using d60.Cirqus.Logging.Console;
using d60.Cirqus.MongoDb.Events;
using d60.Cirqus.Serialization;
using d60.Cirqus.Snapshotting;
using d60.Cirqus.Tests.MongoDb;
using d60.Cirqus.Views;
using MongoDB.Driver;
using NUnit.Framework;
namespace d60.Cirqus.Tests.Snapshotting
{
[TestFixture, Category(TestCategories.MongoDb)]
public class TestSnapshottingWithFairlyLongHistory : FixtureBase
{
readonly DefaultDomainTypeNameMapper _domainTypeNameMapper = new DefaultDomainTypeNameMapper();
readonly DefaultCommandMapper _commandMapper = new DefaultCommandMapper();
MongoDatabase _database;
TimeTaker _timeTaker;
protected override void DoSetUp()
{
_database = MongoHelper.InitializeTestDatabase(dropExistingDatabase: true);
CirqusLoggerFactory.Current = new ConsoleLoggerFactory(Logger.Level.Warn);
}
[Test]
public void ProcessOneMoreCommand()
{
var commandProcessor = GetCommandProcessor(true);
commandProcessor.ProcessCommand(new CrushItRealGood("id", 0.1m));
commandProcessor.ProcessCommand(new CrushItRealGood("id", 0.1m));
}
[TestCase(true, 10, 1000)]
[TestCase(false, 10, 1000)]
public void RunTest(bool useCaching, int numberOfRoots, int numberOfCommands)
{
var aggregateRootIds = Enumerable.Range(0, numberOfRoots).Select(i => i.ToString()).ToArray();
var random = new Random(DateTime.Now.GetHashCode());
Func<string> getRandomRootId = () => aggregateRootIds[random.Next(aggregateRootIds.Length)];
var commandProcessor = GetCommandProcessor(useCaching);
var processedCommands = 0L;
TakeTime(string.Format("Processing {0} commands distributed among {1} roots", numberOfCommands, numberOfRoots),
() => Enumerable.Range(0, numberOfCommands)
.Select(i => new CrushItRealGood(getRandomRootId(), 0.0001m))
.ToList()
.ForEach(cmd =>
{
commandProcessor.ProcessCommand(cmd);
Interlocked.Increment(ref processedCommands);
}),
timeSpan => Console.WriteLine("{0} commands processed.... ", Interlocked.Read(ref processedCommands)));
Console.WriteLine(@"Total time spent
hydrating roots: {0:0.0}
loading events: {1:0.0}
saving events: {2:0.0}
caching in use: {3}",
_timeTaker.TimeSpentHydratingAggregateRoots.TotalSeconds,
_timeTaker.TimeSpentLoadingEvents.TotalSeconds,
_timeTaker.TimeSpentSavingEvents.TotalSeconds,
useCaching);
}
CommandProcessor GetCommandProcessor(bool useCaching)
{
var eventStore = new MongoDbEventStore(_database, "events");
_timeTaker = new TimeTaker
{
InnerEventStore = eventStore,
};
var serializer = new JsonDomainEventSerializer();
IAggregateRootRepository aggregateRootRepository = new DefaultAggregateRootRepository(_timeTaker, serializer, _domainTypeNameMapper);
if (useCaching)
{
aggregateRootRepository = new CachingAggregateRootRepositoryDecorator(aggregateRootRepository, new InMemorySnapshotCache { ApproximateMaxNumberOfCacheEntries = 100 }, eventStore, serializer);
}
_timeTaker.InnerAggregateRootRepository = aggregateRootRepository;
var eventDispatcher = new ViewManagerEventDispatcher(_timeTaker, eventStore, serializer, _domainTypeNameMapper);
var commandProcessor = new CommandProcessor(_timeTaker, _timeTaker, eventDispatcher, serializer, _commandMapper, _domainTypeNameMapper, new Options());
RegisterForDisposal(commandProcessor);
return commandProcessor;
}
class TimeTaker : IAggregateRootRepository, IEventStore
{
TimeSpan _timeSpentHydratingAggregateRoots;
TimeSpan _timeSpentLoadingEvents;
TimeSpan _timeSpentSavingEvents;
public IAggregateRootRepository InnerAggregateRootRepository { get; set; }
public IEventStore InnerEventStore { get; set; }
public TimeSpan TimeSpentHydratingAggregateRoots
{
get { return _timeSpentHydratingAggregateRoots; }
}
public TimeSpan TimeSpentLoadingEvents
{
get { return _timeSpentLoadingEvents; }
}
public TimeSpan TimeSpentSavingEvents
{
get { return _timeSpentSavingEvents; }
}
public AggregateRoot Get<TAggregateRoot>(string aggregateRootId, IUnitOfWork unitOfWork, long maxGlobalSequenceNumber = long.MaxValue, bool createIfNotExists = false)
{
var stopwatch = Stopwatch.StartNew();
var aggregateRootInfo = InnerAggregateRootRepository
.Get<TAggregateRoot>(aggregateRootId, unitOfWork, maxGlobalSequenceNumber, createIfNotExists);
_timeSpentHydratingAggregateRoots += stopwatch.Elapsed;
return aggregateRootInfo;
}
public bool Exists(string aggregateRootId, long maxGlobalSequenceNumber = long.MaxValue)
{
return InnerAggregateRootRepository.Exists(aggregateRootId, maxGlobalSequenceNumber);
}
public IEnumerable<EventData> Load(string aggregateRootId, long firstSeq = 0)
{
var stopwatch = Stopwatch.StartNew();
var domainEvents = InnerEventStore.Load(aggregateRootId, firstSeq).ToList();
_timeSpentLoadingEvents += stopwatch.Elapsed;
return domainEvents;
}
public IEnumerable<EventData> Stream(long globalSequenceNumber = 0)
{
return InnerEventStore.Stream(globalSequenceNumber);
}
public long GetNextGlobalSequenceNumber()
{
return InnerEventStore.GetNextGlobalSequenceNumber();
}
public void Save(Guid batchId, IEnumerable<EventData> events)
{
var stopwatch = Stopwatch.StartNew();
InnerEventStore.Save(batchId, events);
_timeSpentSavingEvents += stopwatch.Elapsed;
}
}
public class Beetroot : AggregateRoot, IEmit<BeetrootSquashed>, IEmit<BeetrootCrushed>
{
decimal _structuralStamina = 1;
bool _completelyCrushed;
public void Crush(decimal howMuch)
{
if (_completelyCrushed) return;
Emit(new BeetrootSquashed(howMuch));
if (_structuralStamina > 0) return;
Emit(new BeetrootCrushed());
}
public void Apply(BeetrootSquashed e)
{
_structuralStamina -= e.HowMuch;
}
public void Apply(BeetrootCrushed e)
{
_completelyCrushed = true;
}
}
public class BeetrootSquashed : DomainEvent<Beetroot>
{
public BeetrootSquashed(decimal howMuch)
{
HowMuch = howMuch;
}
public decimal HowMuch { get; private set; }
}
public class BeetrootCrushed : DomainEvent<Beetroot>
{
}
public class CrushItRealGood : Command<Beetroot>
{
public CrushItRealGood(string aggregateRootId, decimal howMuch)
: base(aggregateRootId)
{
HowMuch = howMuch;
}
public decimal HowMuch { get; private set; }
public override void Execute(Beetroot aggregateRoot)
{
aggregateRoot.Crush(HowMuch);
}
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Configuration;
namespace System.Patterns.Configuration
{
/// <summary>
/// A generic hash-based class extending <see cref="T:System.Configuration.ConfigurationElementCollection"/>.
/// This class is used as the basis for all objects in Instinct that provide object wrappers over groupings
/// of configuration settings.
/// </summary>
/// <typeparam name="T">Specific type contained within the generic hash instance.</typeparam>
public class ConfigurationSet<T> : ConfigurationElementCollection
where T : Configuration, new()
{
private AttributeIndex _attributeIndex;
private ConfigurationElementCollectionType _collectionType;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigurationSet<T>"/> class.
/// </summary>
protected ConfigurationSet()
: this(ConfigurationElementCollectionType.AddRemoveClearMap) { }
/// <summary>
/// Initializes a new instance of the <see cref="ConfigurationSet<T>"/> class.
/// </summary>
/// <param name="collectionType">Type of the collection.</param>
protected ConfigurationSet(ConfigurationElementCollectionType collectionType)
{
_collectionType = collectionType;
_attributeIndex = new AttributeIndex(this);
}
/// <summary>
/// Gets or sets the <see cref="System.Configuration.ConfigurationSection"/> or
/// <see cref="System.Configuration.ConfigurationElement"/> instance at the specified index.
/// </summary>
/// <value>
/// An instance of a class that derives from <see cref="System.Configuration.ConfigurationElement"/>
/// </value>
public T this[int index]
{
get { return (T)BaseGet(index); }
set
{
if (BaseGet(index) != null)
BaseRemoveAt(index);
BaseAdd(index, value);
}
}
/// <summary>
/// Gets or sets the <see cref="System.Configuration.ConfigurationSection"/> or
/// <see cref="System.Configuration.ConfigurationElement"/> instance at the specified index.
/// </summary>
/// <value>
/// An instance of a class that derives from <see cref="System.Configuration.ConfigurationElement"/>
/// </value>
public new T this[string name]
{
get { return (T)BaseGet(name); }
}
/// <summary>
/// Adds if undefined.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public T AddIfUndefined(string name)
{
bool isNew;
return AddIfUndefined(name, out isNew);
}
/// <summary>
/// Adds if undefined.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="isNew">if set to <c>true</c> [is new].</param>
/// <returns></returns>
public T AddIfUndefined(string name, out bool isNew)
{
T t = (T)BaseGet(name);
if (t == null)
{
t = (T)CreateNewElement();
t.Name = name;
BaseAdd(t);
isNew = true;
return t;
}
isNew = false;
return t;
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Configuration.ConfigurationElementCollection"/> object is read only.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Configuration.ConfigurationElementCollection"/> object is read only; otherwise, false.
/// </returns>
public override bool IsReadOnly()
{
return false;
}
///// <summary>
///// Gets the property collection.
///// </summary>
///// <value>The property collection.</value>
//public ConfigurationPropertyCollection PropertyCollection
//{
// get { return base.Properties; }
//}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found;
/// otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param>
/// <returns>
/// <c>true</c> if the <see cref="T:Hash`2">Hash</see> contains an element with the specified key; otherwise, <c>false</c>
/// </returns>
public bool TryGetValue(object key, out T value)
{
value = (T)BaseGet(key);
return (value != null);
}
#region Inheriting
/// <summary>
/// Applies the configuration.
/// </summary>
/// <param name="inherit">The inherit.</param>
public void ApplyConfiguration(ConfigurationSet<T> inheritConfiguration)
{
ApplyConfigurationValues(inheritConfiguration);
ApplyConfigurationElements(inheritConfiguration);
}
/// <summary>
/// Applies the configuration values.
/// </summary>
/// <param name="inheritConfiguration">The inherit configuration.</param>
protected virtual void ApplyConfigurationValues(ConfigurationSet<T> inheritConfiguration) { }
/// <summary>
/// Applies the configuration elements.
/// </summary>
/// <param name="inherit">The inherit.</param>
protected virtual void ApplyConfigurationElements(ConfigurationSet<T> inheritConfiguration) { }
/// <summary>
/// Applies the default values.
/// </summary>
protected virtual void ApplyDefaultValues() { }
#endregion
#region ConfigurationElementCollection
/// <summary>
/// Adds a configuration element to the <see cref="T:System.Configuration.ConfigurationElementCollection">ConfigurationElementCollection</see>.
/// </summary>
/// <param name="element">The <see cref="T:System.Configuration.ConfigurationElement"></see> to add.</param>
protected override void BaseAdd(ConfigurationElement element)
{
BaseAdd(element, false);
}
/// <summary>
/// Gets the type of the <see cref="T:System.Configuration.ConfigurationElementCollection">ConfigurationElementCollection</see>
/// returned by accessing <see cref="P:System.Configuration.ConfigurationElementCollectionType.AddRemoveClearMap">AddRemoveClearMap</see>.
/// </summary>
/// <value></value>
/// <returns>The <see cref="T:System.Configuration.ConfigurationElementCollectionType"></see> of this collection.</returns>
public override ConfigurationElementCollectionType CollectionType
{
get { return _collectionType; }
}
/// <summary>
/// When overridden in a derived class, creates a new <see cref="T:System.Configuration.ConfigurationElement">ConfigurationElement</see>
/// of the generic parameter type T.
/// </summary>
/// <returns>
/// A new <see cref="T:System.Configuration.ConfigurationElement"></see>.
/// </returns>
protected override ConfigurationElement CreateNewElement()
{
return new T();
}
/// <summary>
/// Gets the Name for a specified configuration element when overridden in a derived class.
/// </summary>
/// <param name="element">The <see cref="T:System.Configuration.ConfigurationElement"></see> to return the key for.</param>
/// <returns>
/// An <see cref="T:System.Object"></see> that acts as the key for the specified <see cref="T:System.Configuration.ConfigurationElement"></see>.
/// </returns>
protected override object GetElementKey(ConfigurationElement element)
{
return ((T)element).Name;
}
#endregion
#region Attribute
/// <summary>
/// Gets the AttributeIndex of this class.
/// </summary>
/// <value>The attribute.</value>
public Collections.Indexer<string, object> Attribute
{
get { return _attributeIndex; }
}
/// <summary>
/// AttributeIndex
/// </summary>
private class AttributeIndex : Collections.Indexer<string, object>
{
private ConfigurationSet<T> _parent;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigurationHashBase<T>.AttributeIndex"/> class.
/// </summary>
/// <param name="configCollection">The config collection.</param>
public AttributeIndex(ConfigurationSet<T> parent)
{
_parent = parent;
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <value></value>
public override object this[string key]
{
get { return _parent.GetBaseItem(key); }
set { _parent.SetBaseItem(key, value); }
}
}
/// <summary>
/// Gets the item associated with the key provided from the underlying base config collection.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Configuration value.</returns>
protected object GetBaseItem(string key)
{
return base[key];
}
/// <summary>
/// Sets the item associated with the key provided from the underlying base config collection.
/// </summary>
/// <param name="key">The key to use.</param>
/// <param name="value">The value to set.</param>
protected void SetBaseItem(string key, object value)
{
base[key] = value;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApiProxy.TestServer.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
namespace CallButler.Manager.Forms
{
partial class LangageSelectionForm
{
/// <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(LangageSelectionForm));
this.lbAllLanguages = new System.Windows.Forms.ListBox();
this.lbSelectedLanguages = new System.Windows.Forms.ListBox();
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.btnRemoveSelectedLanguage = new System.Windows.Forms.Button();
this.btnRemoveAllLanguages = new System.Windows.Forms.Button();
this.btnAddAllLanguages = new System.Windows.Forms.Button();
this.btnAddSelectedLanguage = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// lbAllLanguages
//
this.lbAllLanguages.AccessibleDescription = null;
this.lbAllLanguages.AccessibleName = null;
resources.ApplyResources(this.lbAllLanguages, "lbAllLanguages");
this.lbAllLanguages.BackgroundImage = null;
this.lbAllLanguages.Font = null;
this.lbAllLanguages.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.lbAllLanguages.FormattingEnabled = true;
this.lbAllLanguages.Name = "lbAllLanguages";
this.lbAllLanguages.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.lbAllLanguages.Sorted = true;
this.lbAllLanguages.SelectedIndexChanged += new System.EventHandler(this.lbAllLanguages_SelectedIndexChanged);
//
// lbSelectedLanguages
//
this.lbSelectedLanguages.AccessibleDescription = null;
this.lbSelectedLanguages.AccessibleName = null;
resources.ApplyResources(this.lbSelectedLanguages, "lbSelectedLanguages");
this.lbSelectedLanguages.BackgroundImage = null;
this.lbSelectedLanguages.Font = null;
this.lbSelectedLanguages.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.lbSelectedLanguages.FormattingEnabled = true;
this.lbSelectedLanguages.Name = "lbSelectedLanguages";
this.lbSelectedLanguages.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.lbSelectedLanguages.Sorted = true;
this.lbSelectedLanguages.SelectedIndexChanged += new System.EventHandler(this.lbSelectedLanguages_SelectedIndexChanged);
//
// btnOK
//
this.btnOK.AccessibleDescription = null;
this.btnOK.AccessibleName = null;
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.BackgroundImage = null;
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Font = null;
this.btnOK.Name = "btnOK";
this.btnOK.UseVisualStyleBackColor = true;
//
// btnCancel
//
this.btnCancel.AccessibleDescription = null;
this.btnCancel.AccessibleName = null;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.BackgroundImage = null;
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Font = null;
this.btnCancel.Name = "btnCancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AccessibleDescription = null;
this.label1.AccessibleName = null;
resources.ApplyResources(this.label1, "label1");
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = null;
this.label1.Name = "label1";
//
// label2
//
this.label2.AccessibleDescription = null;
this.label2.AccessibleName = null;
resources.ApplyResources(this.label2, "label2");
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = null;
this.label2.Name = "label2";
//
// btnRemoveSelectedLanguage
//
this.btnRemoveSelectedLanguage.AccessibleDescription = null;
this.btnRemoveSelectedLanguage.AccessibleName = null;
resources.ApplyResources(this.btnRemoveSelectedLanguage, "btnRemoveSelectedLanguage");
this.btnRemoveSelectedLanguage.BackgroundImage = null;
this.btnRemoveSelectedLanguage.Font = null;
this.btnRemoveSelectedLanguage.Image = global::CallButler.Manager.Properties.Resources.navigate_left_16;
this.btnRemoveSelectedLanguage.Name = "btnRemoveSelectedLanguage";
this.btnRemoveSelectedLanguage.UseVisualStyleBackColor = true;
this.btnRemoveSelectedLanguage.Click += new System.EventHandler(this.btnRemoveSelectedLanguage_Click);
//
// btnRemoveAllLanguages
//
this.btnRemoveAllLanguages.AccessibleDescription = null;
this.btnRemoveAllLanguages.AccessibleName = null;
resources.ApplyResources(this.btnRemoveAllLanguages, "btnRemoveAllLanguages");
this.btnRemoveAllLanguages.BackgroundImage = null;
this.btnRemoveAllLanguages.Font = null;
this.btnRemoveAllLanguages.Image = global::CallButler.Manager.Properties.Resources.navigate_left2_16;
this.btnRemoveAllLanguages.Name = "btnRemoveAllLanguages";
this.btnRemoveAllLanguages.UseVisualStyleBackColor = true;
this.btnRemoveAllLanguages.Click += new System.EventHandler(this.btnRemoveAllLanguages_Click);
//
// btnAddAllLanguages
//
this.btnAddAllLanguages.AccessibleDescription = null;
this.btnAddAllLanguages.AccessibleName = null;
resources.ApplyResources(this.btnAddAllLanguages, "btnAddAllLanguages");
this.btnAddAllLanguages.BackgroundImage = null;
this.btnAddAllLanguages.Font = null;
this.btnAddAllLanguages.Image = global::CallButler.Manager.Properties.Resources.navigate_right2_16;
this.btnAddAllLanguages.Name = "btnAddAllLanguages";
this.btnAddAllLanguages.UseVisualStyleBackColor = true;
this.btnAddAllLanguages.Click += new System.EventHandler(this.btnAddAllLanguages_Click);
//
// btnAddSelectedLanguage
//
this.btnAddSelectedLanguage.AccessibleDescription = null;
this.btnAddSelectedLanguage.AccessibleName = null;
resources.ApplyResources(this.btnAddSelectedLanguage, "btnAddSelectedLanguage");
this.btnAddSelectedLanguage.BackgroundImage = null;
this.btnAddSelectedLanguage.Font = null;
this.btnAddSelectedLanguage.Image = global::CallButler.Manager.Properties.Resources.navigate_right_16;
this.btnAddSelectedLanguage.Name = "btnAddSelectedLanguage";
this.btnAddSelectedLanguage.UseVisualStyleBackColor = true;
this.btnAddSelectedLanguage.Click += new System.EventHandler(this.btnAddSelectedLanguage_Click);
//
// label3
//
this.label3.AccessibleDescription = null;
this.label3.AccessibleName = null;
resources.ApplyResources(this.label3, "label3");
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.Font = null;
this.label3.Name = "label3";
//
// LangageSelectionForm
//
this.AccessibleDescription = null;
this.AccessibleName = null;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.WhiteSmoke;
this.BackgroundImage = null;
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.label3);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.label2);
this.Controls.Add(this.btnRemoveSelectedLanguage);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnRemoveAllLanguages);
this.Controls.Add(this.btnAddAllLanguages);
this.Controls.Add(this.btnAddSelectedLanguage);
this.Controls.Add(this.lbSelectedLanguages);
this.Controls.Add(this.lbAllLanguages);
this.HeaderImage = global::CallButler.Manager.Properties.Resources.earth2_32_shadow;
this.Icon = null;
this.Name = "LangageSelectionForm";
this.Controls.SetChildIndex(this.lbAllLanguages, 0);
this.Controls.SetChildIndex(this.lbSelectedLanguages, 0);
this.Controls.SetChildIndex(this.btnAddSelectedLanguage, 0);
this.Controls.SetChildIndex(this.btnAddAllLanguages, 0);
this.Controls.SetChildIndex(this.btnRemoveAllLanguages, 0);
this.Controls.SetChildIndex(this.label1, 0);
this.Controls.SetChildIndex(this.btnRemoveSelectedLanguage, 0);
this.Controls.SetChildIndex(this.label2, 0);
this.Controls.SetChildIndex(this.btnOK, 0);
this.Controls.SetChildIndex(this.label3, 0);
this.Controls.SetChildIndex(this.btnCancel, 0);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListBox lbAllLanguages;
private System.Windows.Forms.ListBox lbSelectedLanguages;
private System.Windows.Forms.Button btnAddSelectedLanguage;
private System.Windows.Forms.Button btnAddAllLanguages;
private System.Windows.Forms.Button btnRemoveAllLanguages;
private System.Windows.Forms.Button btnRemoveSelectedLanguage;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGame.Extended.TextureAtlases
{
/// <summary>
/// Defines a texture atlas which stores a source image and contains regions specifying its sub-images.
/// </summary>
/// <remarks>
/// <para>
/// Texture atlas (also called a tile map, tile engine, or sprite sheet) is a large image containing a collection,
/// or "atlas", of sub-images, each of which is a texture map for some part of a 2D or 3D model.
/// The sub-textures can be rendered by modifying the texture coordinates of the object's uvmap on the atlas,
/// essentially telling it which part of the image its texture is in.
/// In an application where many small textures are used frequently, it is often more efficient to store the
/// textures in a texture atlas which is treated as a single unit by the graphics hardware.
/// This saves memory and because there are less rendering state changes by binding once, it can be faster to bind
/// one large texture once than to bind many smaller textures as they are drawn.
/// Careful alignment may be needed to avoid bleeding between sub textures when used with mipmapping, and artefacts
/// between tiles for texture compression.
/// </para>
/// </remarks>
public class TextureAtlas : IEnumerable<TextureRegion2D>
{
/// <summary>
/// Initializes a new texture atlas with an empty list of regions.
/// </summary>
/// <param name="name">The asset name of this texture atlas</param>
/// <param name="texture">Source <see cref="Texture2D " /> image used to draw on screen.</param>
public TextureAtlas(string name, Texture2D texture)
{
Name = name;
Texture = texture;
_regionsByName = new Dictionary<string, TextureRegion2D>();
_regionsByIndex = new List<TextureRegion2D>();
}
/// <inheritdoc />
/// <summary>
/// Initializes a new texture atlas and populates it with regions.
/// </summary>
/// <param name="name">The asset name of this texture atlas</param>
/// <param name="texture">Source <see cref="!:Texture2D " /> image used to draw on screen.</param>
/// <param name="regions">A collection of regions to populate the atlas with.</param>
public TextureAtlas(string name, Texture2D texture, Dictionary<string, Rectangle> regions)
: this(name, texture)
{
foreach (var region in regions)
CreateRegion(region.Key, region.Value.X, region.Value.Y, region.Value.Width, region.Value.Height);
}
private readonly Dictionary<string, TextureRegion2D> _regionsByName;
private readonly List<TextureRegion2D> _regionsByIndex;
public string Name { get; }
/// <summary>
/// Gets a source <see cref="Texture2D" /> image.
/// </summary>
public Texture2D Texture { get; }
/// <summary>
/// Gets a list of regions in the <see cref="TextureAtlas" />.
/// </summary>
public IEnumerable<TextureRegion2D> Regions => _regionsByIndex;
/// <summary>
/// Gets the number of regions in the <see cref="TextureAtlas" />.
/// </summary>
public int RegionCount => _regionsByIndex.Count;
public TextureRegion2D this[string name] => GetRegion(name);
public TextureRegion2D this[int index] => GetRegion(index);
/// <summary>
/// Gets the enumerator of the <see cref="TextureAtlas" />' list of regions.
/// </summary>
/// <returns>The <see cref="IEnumerator" /> of regions.</returns>
public IEnumerator<TextureRegion2D> GetEnumerator()
{
return _regionsByIndex.GetEnumerator();
}
/// <summary>
/// Gets the enumerator of the <see cref="TextureAtlas" />' list of regions.
/// </summary>
/// <returns>The <see cref="IEnumerator" /> of regions</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Determines whether the texture atlas contains a region
/// </summary>
/// <param name="name">Name of the texture region.</param>
/// <returns></returns>
public bool ContainsRegion(string name)
{
return _regionsByName.ContainsKey(name);
}
/// <summary>
/// Internal method for adding region
/// </summary>
/// <param name="region">Texture region.</param>
private void AddRegion(TextureRegion2D region)
{
_regionsByIndex.Add(region);
_regionsByName.Add(region.Name, region);
}
/// <summary>
/// Creates a new texture region and adds it to the list of the <see cref="TextureAtlas" />' regions.
/// </summary>
/// <param name="name">Name of the texture region.</param>
/// <param name="x">X coordinate of the region's top left corner.</param>
/// <param name="y">Y coordinate of the region's top left corner.</param>
/// <param name="width">Width of the texture region.</param>
/// <param name="height">Height of the texture region.</param>
/// <returns>Created texture region.</returns>
public TextureRegion2D CreateRegion(string name, int x, int y, int width, int height)
{
if (_regionsByName.ContainsKey(name))
throw new InvalidOperationException($"Region {name} already exists in the texture atlas");
var region = new TextureRegion2D(name, Texture, x, y, width, height);
AddRegion(region);
return region;
}
/// <summary>
/// Creates a new nine patch texture region and adds it to the list of the <see cref="TextureAtlas" />' regions.
/// </summary>
/// <param name="name">Name of the texture region.</param>
/// <param name="x">X coordinate of the region's top left corner.</param>
/// <param name="y">Y coordinate of the region's top left corner.</param>
/// <param name="width">Width of the texture region.</param>
/// <param name="height">Height of the texture region.</param>
/// <param name="thickness">Thickness of the nine patch region.</param>
/// <returns>Created texture region.</returns>
public NinePatchRegion2D CreateNinePatchRegion(string name, int x, int y, int width, int height, Thickness thickness)
{
if (_regionsByName.ContainsKey(name))
throw new InvalidOperationException($"Region {name} already exists in the texture atlas");
var textureRegion = new TextureRegion2D(name, Texture, x, y, width, height);
var ninePatchRegion = new NinePatchRegion2D(textureRegion, thickness);
AddRegion(ninePatchRegion);
return ninePatchRegion;
}
/// <summary>
/// Removes a texture region from the <see cref="TextureAtlas" />
/// </summary>
/// <param name="index">An index of the <see cref="TextureRegion2D" /> in <see cref="Region" /> to remove</param>
public void RemoveRegion(int index)
{
var region = _regionsByIndex[index];
_regionsByIndex.RemoveAt(index);
if(region.Name != null)
_regionsByName.Remove(region.Name);
}
/// <summary>
/// Removes a texture region from the <see cref="TextureAtlas" />
/// </summary>
/// <param name="name">Name of the <see cref="TextureRegion2D" /> to remove</param>
public void RemoveRegion(string name)
{
if (_regionsByName.TryGetValue(name, out var region))
{
_regionsByName.Remove(name);
_regionsByIndex.Remove(region);
}
}
/// <summary>
/// Gets a <see cref="TextureRegion2D" /> from the <see cref="TextureAtlas" />' list.
/// </summary>
/// <param name="index">An index of the <see cref="TextureRegion2D" /> in <see cref="Region" /> to get.</param>
/// <returns>The <see cref="TextureRegion2D" />.</returns>
public TextureRegion2D GetRegion(int index)
{
if (index < 0 || index >= _regionsByIndex.Count)
throw new IndexOutOfRangeException();
return _regionsByIndex[index];
}
/// <summary>
/// Gets a <see cref="TextureRegion2D" /> from the <see cref="TextureAtlas" />' list.
/// </summary>
/// <param name="name">Name of the <see cref="TextureRegion2D" /> to get.</param>
/// <returns>The <see cref="TextureRegion2D" />.</returns>
public TextureRegion2D GetRegion(string name)
{
return GetRegion<TextureRegion2D>(name);
}
/// <summary>
/// Gets a texture region from the <see cref="TextureAtlas" /> of a specified type.
/// This is can be useful if the atlas contains <see cref="NinePatchRegion2D"/>'s.
/// </summary>
/// <typeparam name="T">Type of the region to get</typeparam>
/// <param name="name">Name of the region to get</param>
/// <returns>The texture region</returns>
public T GetRegion<T>(string name) where T : TextureRegion2D
{
if (_regionsByName.TryGetValue(name, out var region))
return (T)region;
throw new KeyNotFoundException(name);
}
/// <summary>
/// Creates a new <see cref="TextureAtlas" /> and populates it with a grid of <see cref="TextureRegion2D" />.
/// </summary>
/// <param name="name">The name of this texture atlas</param>
/// <param name="texture">Source <see cref="Texture2D" /> image used to draw on screen</param>
/// <param name="regionWidth">Width of the <see cref="TextureRegion2D" />.</param>
/// <param name="regionHeight">Height of the <see cref="TextureRegion2D" />.</param>
/// <param name="maxRegionCount">The number of <see cref="TextureRegion2D" /> to create.</param>
/// <param name="margin">Minimum distance of the regions from the border of the source <see cref="Texture2D" /> image.</param>
/// <param name="spacing">Horizontal and vertical space between regions.</param>
/// <returns>A created and populated <see cref="TextureAtlas" />.</returns>
public static TextureAtlas Create(string name, Texture2D texture, int regionWidth, int regionHeight,
int maxRegionCount = int.MaxValue, int margin = 0, int spacing = 0)
{
var textureAtlas = new TextureAtlas(name, texture);
var count = 0;
var width = texture.Width - margin;
var height = texture.Height - margin;
var xIncrement = regionWidth + spacing;
var yIncrement = regionHeight + spacing;
for (var y = margin; y < height; y += yIncrement)
{
for (var x = margin; x < width; x += xIncrement)
{
var regionName = $"{texture.Name ?? "region"}{count}";
textureAtlas.CreateRegion(regionName, x, y, regionWidth, regionHeight);
count++;
if (count >= maxRegionCount)
return textureAtlas;
}
}
return textureAtlas;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Qwack.Core.Basic;
using Qwack.Dates;
using Qwack.Transport.BasicTypes;
namespace Qwack.Core.Instruments.Asset
{
public static class AssetProductFactory
{
public static AsianSwapStrip CreateMonthlyAsianSwap(string period, double strike, string assetId, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection=TradeDirection.Long, Frequency spotLag = new Frequency(), double notional=1, DateGenerationType fixingDateType=DateGenerationType.BusinessDays)
{
var (Start, End) = period.ParsePeriod();
return CreateMonthlyAsianSwap(Start, End, strike, assetId, fixingCalendar, payCalendar, payOffset, currency, tradeDirection, spotLag, notional, fixingDateType);
}
public static AsianSwapStrip CreateMonthlyAsianSwap(DateTime start, DateTime end, double strike, string assetId, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var m = start;
var swaplets = new List<AsianSwap>();
if (start.Month + start.Year * 12 == end.Month + end.Year * 12)
{
var fixingDates = fixingDateType == DateGenerationType.BusinessDays ?
start.BusinessDaysInPeriod(end, fixingCalendar) :
start.FridaysInPeriod(end, fixingCalendar);
swaplets.Add(new AsianSwap
{
AssetId = assetId,
AverageStartDate = start,
AverageEndDate = end,
FixingCalendar = fixingCalendar,
Strike = strike,
FixingDates = fixingDates.ToArray(),
SpotLag = spotLag,
PaymentCalendar = payCalendar,
PaymentLag = payOffset,
PaymentDate = end.AddPeriod(RollType.F, fixingCalendar, payOffset),
PaymentCurrency = currency,
Direction = tradeDirection,
Notional = notional,
FxConversionType = currency.Ccy == "USD" ? FxConversionType.None : FxConversionType.AverageThenConvert
});
}
else
{
while ((m.Month + m.Year * 12) <= (end.Month + end.Year * 12))
{
var fixingDates = fixingDateType == DateGenerationType.BusinessDays ?
m.BusinessDaysInPeriod(m.LastDayOfMonth(), fixingCalendar) :
m.FridaysInPeriod(m.LastDayOfMonth(), fixingCalendar);
swaplets.Add(new AsianSwap
{
AssetId = assetId,
AverageStartDate = m,
AverageEndDate = m.LastDayOfMonth(),
FixingCalendar = fixingCalendar,
Strike = strike,
FixingDates = fixingDates.ToArray(),
SpotLag = spotLag,
PaymentCalendar = payCalendar,
PaymentLag = payOffset,
PaymentDate = m.LastDayOfMonth().AddPeriod(RollType.F, fixingCalendar, payOffset),
PaymentCurrency = currency,
Direction = tradeDirection,
Notional = notional,
FxConversionType = currency.Ccy == "USD" ? FxConversionType.None : FxConversionType.AverageThenConvert
});
m = m.LastDayOfMonth().AddDays(1);
}
}
return new AsianSwapStrip { Swaplets = swaplets.ToArray() };
}
public static AsianSwap CreateTermAsianSwap(string period, double strike, string assetId, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var (Start, End) = period.ParsePeriod();
return CreateTermAsianSwap(Start, End, strike, assetId, fixingCalendar, payCalendar, payOffset, currency, tradeDirection, spotLag, notional, fixingDateType);
}
public static AsianSwap CreateTermAsianSwap(DateTime start, DateTime end, double strike, string assetId, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var payDate = end.AddPeriod(RollType.F, payCalendar, payOffset);
return CreateTermAsianSwap(start, end, strike, assetId, fixingCalendar, payDate, currency, tradeDirection, spotLag, notional, fixingDateType);
}
public static AsianSwap CreateTermAsianSwap(DateTime start, DateTime end, double strike, string assetId, Calendar fixingCalendar, DateTime payDate, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var fixingDates = start == end ? new List<DateTime> { start } :
fixingDateType == DateGenerationType.BusinessDays ?
start.BusinessDaysInPeriod(end, fixingCalendar) :
start.FridaysInPeriod(end, fixingCalendar);
if(!fixingDates.Any() && start==end) //hack for bullet swaps where system returns fixing date on holiday
{
start = start.IfHolidayRollForward(fixingCalendar);
end = start;
fixingDates.Add(start);
}
var swap = new AsianSwap
{
AssetId = assetId,
AverageStartDate = start,
AverageEndDate = end,
FixingCalendar = fixingCalendar,
Strike = strike,
SpotLag = spotLag,
FixingDates = fixingDates.ToArray(),
PaymentDate = payDate,
PaymentCurrency = currency,
Direction = tradeDirection,
Notional = notional,
FxConversionType = currency.Ccy == "USD" ? FxConversionType.None : FxConversionType.AverageThenConvert
};
return swap;
}
public static AsianBasisSwap CreateTermAsianBasisSwap(string period, double strike, string assetIdPay, string assetIdRec, Calendar fixingCalendarPay, Calendar fixingCalendarRec, Calendar payCalendar, Frequency payOffset, Currency currency, Frequency spotLagPay = new Frequency(), Frequency spotLagRec = new Frequency(), double notionalPay = 1, double notionalRec = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var (Start, End) = period.ParsePeriod();
return CreateTermAsianBasisSwap(Start, End, strike, assetIdPay, assetIdRec, fixingCalendarPay, fixingCalendarRec, payCalendar, payOffset, currency, spotLagPay, spotLagRec, notionalPay, notionalRec, fixingDateType);
}
public static AsianBasisSwap CreateTermAsianBasisSwap(DateTime start, DateTime end, double strike, string assetIdPay, string assetIdRec, Calendar fixingCalendarPay, Calendar fixingCalendarRec, Calendar payCalendar, Frequency payOffset, Currency currency, Frequency spotLagPay = new Frequency(), Frequency spotLagRec = new Frequency(), double notionalPay = 1, double notionalRec = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var payDate = end.AddPeriod(RollType.F, payCalendar, payOffset);
return CreateTermAsianBasisSwap(start, end, strike, assetIdPay, assetIdRec, fixingCalendarPay, fixingCalendarRec, payDate, currency, spotLagPay, spotLagRec, notionalPay, notionalRec, fixingDateType);
}
public static AsianBasisSwap CreateTermAsianBasisSwap(DateTime start, DateTime end, double strike, string assetIdPay, string assetIdRec, Calendar fixingCalendarPay, Calendar fixingCalendarRec, DateTime payDate, Currency currency, Frequency spotLagPay = new Frequency(), Frequency spotLagRec = new Frequency(), double notionalPay = 1, double notionalRec = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var swapPay = CreateTermAsianSwap(start, end, -strike, assetIdPay, fixingCalendarPay, payDate, currency, TradeDirection.Long, spotLagPay, notionalPay);
var swapRec = CreateTermAsianSwap(start, end, 0, assetIdRec, fixingCalendarRec, payDate, currency, TradeDirection.Short, spotLagRec, notionalRec);
var swap = new AsianBasisSwap
{
PaySwaplets = new [] {swapPay},
RecSwaplets = new [] {swapRec},
};
return swap;
}
public static AsianBasisSwap CreateBulletBasisSwap(DateTime payFixing, DateTime recFixing, double strike, string assetIdPay, string assetIdRec, Currency currency, double notionalPay, double notionalRec)
{
var payDate = payFixing.Max(recFixing);
var swapPay = new Forward
{
AssetId = assetIdPay,
ExpiryDate = payFixing,
PaymentDate = payDate,
Notional = notionalPay,
Strike = strike,
}.AsBulletSwap();
var swapRec = new Forward
{
AssetId = assetIdRec,
ExpiryDate = recFixing,
PaymentDate = payDate,
Notional = notionalRec,
Strike = 0.0,
}.AsBulletSwap();
var swap = new AsianBasisSwap
{
PaySwaplets = new[] { swapPay },
RecSwaplets = new[] { swapRec },
};
return swap;
}
public static AsianOption CreateAsianOption(string period, double strike, string assetId, OptionType putCall, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var (Start, End) = period.ParsePeriod();
return CreateAsianOption(Start, End, strike, assetId, putCall, fixingCalendar, payCalendar, payOffset, currency, tradeDirection, spotLag, notional, fixingDateType);
}
public static AsianOption CreateAsianOption(DateTime start, DateTime end, double strike, string assetId, OptionType putCall, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var fixingDates = start == end ? new List<DateTime> { start } :
fixingDateType == DateGenerationType.BusinessDays ?
start.BusinessDaysInPeriod(end, fixingCalendar) :
start.FridaysInPeriod(end, fixingCalendar);
return new AsianOption
{
AssetId = assetId,
AverageStartDate = start,
AverageEndDate = end,
FixingCalendar = fixingCalendar,
Strike = strike,
FixingDates = fixingDates.ToArray(),
SpotLag = spotLag,
CallPut = putCall,
PaymentCalendar = payCalendar,
PaymentLag = payOffset,
PaymentDate = end.AddPeriod(RollType.F, fixingCalendar, payOffset),
PaymentCurrency = currency,
Direction = tradeDirection,
Notional = notional,
FxConversionType = currency.Ccy == "USD" ? FxConversionType.None : FxConversionType.AverageThenConvert
};
}
public static AsianOption CreateAsianOption(DateTime start, DateTime end, double strike, string assetId, OptionType putCall, Calendar fixingCalendar, DateTime payDate, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var fixingDates = start==end?new List<DateTime> { start } :
fixingDateType == DateGenerationType.BusinessDays ?
start.BusinessDaysInPeriod(end, fixingCalendar) :
start.FridaysInPeriod(end, fixingCalendar);
return new AsianOption
{
AssetId = assetId,
AverageStartDate = start,
AverageEndDate = end,
FixingCalendar = fixingCalendar,
Strike = strike,
FixingDates = fixingDates.ToArray(),
SpotLag = spotLag,
CallPut = putCall,
PaymentDate = payDate,
PaymentCurrency = currency,
Direction = tradeDirection,
Notional = notional,
FxConversionType = currency.Ccy == "USD" ? FxConversionType.None : FxConversionType.AverageThenConvert
};
}
public static AsianLookbackOption CreateAsianLookbackOption(DateTime start, DateTime end, string assetId, OptionType putCall, Calendar fixingCalendar, DateTime payDate, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var fixingDates = fixingDateType == DateGenerationType.BusinessDays ?
start.BusinessDaysInPeriod(end, fixingCalendar) :
start.FridaysInPeriod(end, fixingCalendar);
return new AsianLookbackOption
{
AssetId = assetId,
ObsStartDate = start,
ObsEndDate = end,
FixingCalendar = fixingCalendar,
FixingDates = fixingDates.ToArray(),
SpotLag = spotLag,
CallPut = putCall,
PaymentDate = payDate,
PaymentCurrency = currency,
Direction = tradeDirection,
Notional = notional,
FxConversionType = currency.Ccy == "USD" ? FxConversionType.None : FxConversionType.AverageThenConvert
};
}
public static AsianLookbackOption CreateAsianLookbackOption(DateTime start, DateTime end, string assetId, OptionType putCall, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var payDate = end.AddPeriod(RollType.F, fixingCalendar, payOffset);
return CreateAsianLookbackOption(start, end, assetId, putCall, fixingCalendar, payDate, currency, tradeDirection, spotLag, notional, fixingDateType);
}
public static AsianLookbackOption CreateAsianLookbackOption(string period, string assetId, OptionType putCall, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var (Start, End) = period.ParsePeriod();
return CreateAsianLookbackOption(Start, End, assetId, putCall, fixingCalendar, payCalendar, payOffset, currency, tradeDirection, spotLag, notional, fixingDateType);
}
public static BackPricingOption CreateBackPricingOption(DateTime start, DateTime end, DateTime decision, string assetId, OptionType putCall, Calendar fixingCalendar, DateTime payDate, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var fixingDates = fixingDateType == DateGenerationType.BusinessDays ?
start.BusinessDaysInPeriod(end, fixingCalendar) :
start.FridaysInPeriod(end, fixingCalendar);
return new BackPricingOption
{
AssetId = assetId,
StartDate = start,
EndDate = end,
DecisionDate = decision,
FixingCalendar = fixingCalendar,
FixingDates = fixingDates.ToArray(),
SpotLag = spotLag,
CallPut = putCall,
PaymentDate = payDate,
SettlementDate = payDate,
PaymentCurrency = currency,
Direction = tradeDirection,
Notional = notional,
FxConversionType = currency.Ccy == "USD" ? FxConversionType.None : FxConversionType.AverageThenConvert
};
}
public static BackPricingOption CreateBackPricingOption(DateTime start, DateTime end, DateTime decision, string assetId, OptionType putCall, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var payDate = end.AddPeriod(RollType.F, fixingCalendar, payOffset);
return CreateBackPricingOption(start, end, decision, assetId, putCall, fixingCalendar, payDate, currency, tradeDirection, spotLag, notional, fixingDateType);
}
public static BackPricingOption CreateBackPricingOption(string period, string assetId, OptionType putCall, Calendar fixingCalendar, Calendar payCalendar, Frequency payOffset, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var (Start, End) = period.ParsePeriod();
return CreateBackPricingOption(Start, End, End, assetId, putCall, fixingCalendar, payCalendar, payOffset, currency, tradeDirection, spotLag, notional, fixingDateType);
}
public static MultiPeriodBackpricingOption CreateMultiPeriodBackPricingOption(Tuple<DateTime,DateTime>[] periodDates, DateTime decision, string assetId, OptionType putCall, Calendar fixingCalendar, DateTime payDate, Currency currency, TradeDirection tradeDirection = TradeDirection.Long, Frequency spotLag = new Frequency(), double notional = 1, DateGenerationType fixingDateType = DateGenerationType.BusinessDays)
{
var fixingDates = fixingDateType == DateGenerationType.BusinessDays ?
periodDates.Select(pd=>pd.Item1.BusinessDaysInPeriod(pd.Item2, fixingCalendar).ToArray()).ToList() :
periodDates.Select(pd => pd.Item1.FridaysInPeriod(pd.Item2, fixingCalendar).ToArray()).ToList();
return new MultiPeriodBackpricingOption
{
AssetId = assetId,
PeriodDates = periodDates,
DecisionDate = decision,
FixingCalendar = fixingCalendar,
FixingDates = fixingDates,
SpotLag = spotLag,
CallPut = putCall,
PaymentDate = payDate,
SettlementDate = payDate,
PaymentCurrency = currency,
Direction = tradeDirection,
Notional = notional,
FxConversionType = currency.Ccy == "USD" ? FxConversionType.None : FxConversionType.AverageThenConvert
};
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace ASC.Mail.Net.FTP.Server
{
#region usings
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
#endregion
/// <summary>
/// FTP Session.
/// </summary>
public class FTP_Session : SocketServerSession
{
#region Members
private readonly FTP_Server m_pServer;
private int m_BadCmdCount;
private string m_CurrentDir = "/";
private bool m_PassiveMode;
private IPEndPoint m_pDataConEndPoint;
private TcpListener m_pPassiveListener;
private string m_RenameFrom = "";
private string m_UserName = "";
#endregion
#region Properties
/// <summary>
/// Gets if sessions is in passive mode.
/// </summary>
public bool PassiveMode
{
get { return m_PassiveMode; }
}
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="sessionID">Session ID.</param>
/// <param name="socket">Server connected socket.</param>
/// <param name="bindInfo">BindInfo what accepted socket.</param>
/// <param name="server">Reference to server.</param>
internal FTP_Session(string sessionID, SocketEx socket, IPBindInfo bindInfo, FTP_Server server)
: base(sessionID, socket, bindInfo, server)
{
m_pServer = server;
// Start session proccessing
StartSession();
}
#endregion
#region Methods
/// <summary>
/// Kill this session.
/// </summary>
public override void Kill()
{
EndSession();
}
#endregion
#region Overrides
/// <summary>
/// Is called by server when session has timed out.
/// </summary>
protected internal override void OnSessionTimeout()
{
try
{
Socket.WriteLine("500 Session timeout, closing transmission channel");
}
catch {}
EndSession();
}
#endregion
#region Utility methods
/// <summary>
/// Starts session.
/// </summary>
private void StartSession()
{
// Add session to session list
m_pServer.AddSession(this);
// Check if ip is allowed to connect this computer
if (m_pServer.OnValidate_IpAddress(LocalEndPoint, RemoteEndPoint))
{
// Notify that server is ready
Socket.WriteLine("220 " + BindInfo.HostName + " FTP server ready");
BeginRecieveCmd();
}
else
{
EndSession();
}
}
/// <summary>
/// Ends session, closes socket.
/// </summary>
private void EndSession()
{
m_pServer.RemoveSession(this);
// Write logs to log file, if needed
if (m_pServer.LogCommands)
{
// m_pLogWriter.AddEntry("//----- Sys: 'Session:'" + this.SessionID + " removed " + DateTime.Now);
// m_pLogWriter.Flush();
Socket.Logger.Flush();
}
if (Socket != null)
{
Socket.Shutdown(SocketShutdown.Both);
Socket.Disconnect();
//this.Socket = null;
}
}
/// <summary>
/// Is called when error occures.
/// </summary>
/// <param name="x"></param>
private void OnError(Exception x)
{
try
{
if (x is SocketException)
{
SocketException xs = (SocketException) x;
// Client disconnected without shutting down
if (xs.ErrorCode == 10054 || xs.ErrorCode == 10053)
{
if (m_pServer.LogCommands)
{
// m_pLogWriter.AddEntry("Client aborted/disconnected",this.SessionID,this.RemoteEndPoint.Address.ToString(),"C");
Socket.Logger.AddTextEntry("Client aborted/disconnected");
}
EndSession();
// Exception handled, return
return;
}
}
m_pServer.OnSysError("", x);
}
catch (Exception ex)
{
m_pServer.OnSysError("", ex);
}
}
/// <summary>
/// Starts recieveing command.
/// </summary>
private void BeginRecieveCmd()
{
MemoryStream strm = new MemoryStream();
Socket.BeginReadLine(strm, 1024, strm, EndRecieveCmd);
}
/// <summary>
/// Is called if command is recieved.
/// </summary>
/// <param name="result"></param>
/// <param name="exception"></param>
/// <param name="count"></param>
/// <param name="tag"></param>
private void EndRecieveCmd(SocketCallBackResult result, long count, Exception exception, object tag)
{
try
{
switch (result)
{
case SocketCallBackResult.Ok:
MemoryStream strm = (MemoryStream) tag;
string cmdLine = Encoding.Default.GetString(strm.ToArray());
// if(m_pServer.LogCommands){
// m_pLogWriter.AddEntry(cmdLine + "<CRLF>",this.SessionID,this.RemoteEndPoint.Address.ToString(),"C");
// }
// Exceute command
if (SwitchCommand(cmdLine))
{
// Session end, close session
EndSession();
}
break;
case SocketCallBackResult.LengthExceeded:
Socket.WriteLine("500 Line too long.");
BeginRecieveCmd();
break;
case SocketCallBackResult.SocketClosed:
EndSession();
break;
case SocketCallBackResult.Exception:
OnError(exception);
break;
}
}
catch (Exception x)
{
OnError(x);
}
}
/// <summary>
/// Parses and executes POP3 commmand.
/// </summary>
/// <param name="commandTxt">FTP command text.</param>
/// <returns>Returns true,if session must be terminated.</returns>
private bool SwitchCommand(string commandTxt)
{
//---- Parse command --------------------------------------------------//
string[] cmdParts = commandTxt.TrimStart().Split(new[] {' '});
string command = cmdParts[0].ToUpper().Trim();
string argsText = Core.GetArgsText(commandTxt, command);
//---------------------------------------------------------------------//
/*
USER <SP> <username> <CRLF>
PASS <SP> <password> <CRLF>
ACCT <SP> <account-information> <CRLF>
CWD <SP> <pathname> <CRLF>
CDUP <CRLF>
SMNT <SP> <pathname> <CRLF>
QUIT <CRLF>
REIN <CRLF>
PORT <SP> <host-port> <CRLF>
PASV <CRLF>
TYPE <SP> <type-code> <CRLF>
STRU <SP> <structure-code> <CRLF>
MODE <SP> <mode-code> <CRLF>
RETR <SP> <pathname> <CRLF>
STOR <SP> <pathname> <CRLF>
STOU <CRLF>
APPE <SP> <pathname> <CRLF>
ALLO <SP> <decimal-integer>
[<SP> R <SP> <decimal-integer>] <CRLF>
REST <SP> <marker> <CRLF>
RNFR <SP> <pathname> <CRLF>
RNTO <SP> <pathname> <CRLF>
ABOR <CRLF>
DELE <SP> <pathname> <CRLF>
RMD <SP> <pathname> <CRLF>
MKD <SP> <pathname> <CRLF>
PWD <CRLF>
LIST [<SP> <pathname>] <CRLF>
NLST [<SP> <pathname>] <CRLF>
SITE <SP> <string> <CRLF>
SYST <CRLF>
STAT [<SP> <pathname>] <CRLF>
HELP [<SP> <string>] <CRLF>
NOOP <CRLF>
*/
switch (command)
{
case "USER":
USER(argsText);
break;
case "PASS":
PASS(argsText);
break;
case "CWD":
CWD(argsText);
break;
case "CDUP":
CDUP(argsText);
break;
// case "REIN":
// break;
case "QUIT":
QUIT();
return true;
case "PORT":
PORT(argsText);
break;
case "PASV":
PASV(argsText);
break;
case "TYPE":
TYPE(argsText);
break;
case "RETR":
RETR(argsText);
break;
case "STOR":
STOR(argsText);
break;
// case "STOU":
// break;
case "APPE":
APPE(argsText);
break;
// case "REST":
// break;
case "RNFR":
RNFR(argsText);
break;
case "RNTO":
RNTO(argsText);
break;
// case "ABOR":
// break;
case "DELE":
DELE(argsText);
break;
case "RMD":
RMD(argsText);
break;
case "MKD":
MKD(argsText);
break;
case "PWD":
PWD();
break;
case "LIST":
LIST(argsText);
break;
case "NLST":
NLST(argsText);
break;
case "SYST":
SYST();
break;
// case "STAT":
// break;
// case "HELP":
// break;
case "NOOP":
NOOP();
break;
case "":
break;
default:
Socket.WriteLine("500 Invalid command " + command);
//---- Check that maximum bad commands count isn't exceeded ---------------//
if (m_BadCmdCount > m_pServer.MaxBadCommands - 1)
{
Socket.WriteLine("421 Too many bad commands, closing transmission channel");
return true;
}
m_BadCmdCount++;
//-------------------------------------------------------------------------//
break;
}
BeginRecieveCmd();
return false;
}
private void USER(string argsText)
{
if (Authenticated)
{
Socket.WriteLine("500 You are already authenticated");
return;
}
if (m_UserName.Length > 0)
{
Socket.WriteLine("500 username is already specified, please specify password");
return;
}
string[] param = argsText.Split(new[] {' '});
// There must be only one parameter - userName
if (argsText.Length > 0 && param.Length == 1)
{
string userName = param[0];
Socket.WriteLine("331 Password required or user:'" + userName + "'");
m_UserName = userName;
}
else
{
Socket.WriteLine("500 Syntax error. Syntax:{USER username}");
}
}
private void PASS(string argsText)
{
if (Authenticated)
{
Socket.WriteLine("500 You are already authenticated");
return;
}
if (m_UserName.Length == 0)
{
Socket.WriteLine("503 please specify username first");
return;
}
string[] param = argsText.Split(new[] {' '});
// There may be only one parameter - password
if (param.Length == 1)
{
string password = param[0];
// Authenticate user
if (m_pServer.OnAuthUser(this, m_UserName, password, "", AuthType.Plain))
{
Socket.WriteLine("230 Password ok");
SetUserName(m_UserName);
}
else
{
Socket.WriteLine("530 UserName or Password is incorrect");
m_UserName = ""; // Reset userName !!!
}
}
else
{
Socket.WriteLine("500 Syntax error. Syntax:{PASS userName}");
}
}
private void CWD(string argsText)
{
/*
This command allows the user to work with a different
directory or dataset for file storage or retrieval without
altering his login or accounting information. Transfer
parameters are similarly unchanged. The argument is a
pathname specifying a directory or other system dependent
file group designator.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
string dir = GetAndNormailizePath(argsText);
//Check if dir exists and is accesssible for this user
if (m_pServer.OnDirExists(this, dir))
{
m_CurrentDir = dir;
Socket.WriteLine("250 CDW command successful.");
}
else
{
Socket.WriteLine("550 System can't find directory '" + dir + "'.");
}
}
private void CDUP(string argsText)
{
/*
This command is a special case of CWD, and is included to
simplify the implementation of programs for transferring
directory trees between operating systems having different
syntaxes for naming the parent directory. The reply codes
shall be identical to the reply codes of CWD.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
// Move dir up if possible
string[] pathParts = m_CurrentDir.Split('/');
if (pathParts.Length > 1)
{
m_CurrentDir = "";
for (int i = 0; i < (pathParts.Length - 2); i++)
{
m_CurrentDir += pathParts[i] + "/";
}
if (m_CurrentDir.Length == 0)
{
m_CurrentDir = "/";
}
}
Socket.WriteLine("250 CDUP command successful.");
}
private void PWD()
{
/*
This command causes the name of the current working
directory to be returned in the reply.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
Socket.WriteLine("257 \"" + m_CurrentDir + "\" is current directory.");
}
private void RETR(string argsText)
{
/*
This command causes the server-DTP to transfer a copy of the
file, specified in the pathname, to the server- or user-DTP
at the other end of the data connection. The status and
contents of the file at the server site shall be unaffected.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
// ToDo: custom errors
//---- See if path accessible
Stream fileStream = null;
try
{
string file = GetAndNormailizePath(argsText);
file = file.Substring(0, file.Length - 1);
fileStream = m_pServer.OnGetFile(this, file);
}
catch
{
Socket.WriteLine("550 Access denied or directory dosen't exist !");
return;
}
Socket socket = GetDataConnection();
if (socket == null)
{
return;
}
try
{
// string file = GetAndNormailizePath(argsText);
// file = file.Substring(0,file.Length - 1);
// using(Stream fileStream = m_pServer.OnGetFile(file)){
if (fileStream != null)
{
// ToDo: bandwidth limiting here
int readed = 1;
while (readed > 0)
{
byte[] data = new byte[10000];
readed = fileStream.Read(data, 0, data.Length);
socket.Send(data, readed, SocketFlags.None);
}
}
// }
socket.Shutdown(SocketShutdown.Both);
socket.Close();
Socket.WriteLine("226 Transfer Complete.");
}
catch
{
Socket.WriteLine("426 Connection closed; transfer aborted.");
}
fileStream.Close();
}
private void STOR(string argsText)
{
/*
This command causes the server-DTP to transfer a copy of the
file, specified in the pathname, to the server- or user-DTP
at the other end of the data connection. The status and
contents of the file at the server site shall be unaffected.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
// ToDo: custom errors
//---- See if path accessible
Stream fileStream = null;
try
{
string file = GetAndNormailizePath(argsText);
file = file.Substring(0, file.Length - 1);
fileStream = m_pServer.OnStoreFile(this, file);
}
catch
{
Socket.WriteLine("550 Access denied or directory dosen't exist !");
return;
}
Socket socket = GetDataConnection();
if (socket == null)
{
return;
}
try
{
string file = GetAndNormailizePath(argsText);
file = file.Substring(0, file.Length - 1);
// using(Stream fileStream = m_pServer.OnStoreFile(file)){
if (fileStream != null)
{
// ToDo: bandwidth limiting here
int readed = 1;
while (readed > 0)
{
byte[] data = new byte[10000];
readed = socket.Receive(data);
fileStream.Write(data, 0, readed);
}
}
// }
socket.Shutdown(SocketShutdown.Both);
socket.Close();
Socket.WriteLine("226 Transfer Complete.");
}
catch
{
// ToDo: report right errors here. eg. DataConnection read time out, ... .
Socket.WriteLine("426 Connection closed; transfer aborted.");
}
fileStream.Close();
}
private void DELE(string argsText)
{
/*
This command causes the file specified in the pathname to be
deleted at the server site. If an extra level of protection
is desired (such as the query, "Do you really wish to
delete?"), it should be provided by the user-FTP process.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
string file = GetAndNormailizePath(argsText);
file = file.Substring(0, file.Length - 1);
m_pServer.OnDeleteFile(this, file);
Socket.WriteLine("250 file deleted.");
}
private void APPE(string argsText)
{
/*
This command causes the server-DTP to accept the data
transferred via the data connection and to store the data in
a file at the server site. If the file specified in the
pathname exists at the server site, then the data shall be
appended to that file; otherwise the file specified in the
pathname shall be created at the server site.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
Socket.WriteLine("500 unimplemented");
}
private void RNFR(string argsText)
{
/*
This command specifies the old pathname of the file which is
to be renamed. This command must be immediately followed by
a "rename to" command specifying the new file pathname.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
string dir = GetAndNormailizePath(argsText);
if (m_pServer.OnDirExists(this, dir) || m_pServer.OnFileExists(this, dir))
{
Socket.WriteLine("350 Please specify destination name.");
m_RenameFrom = dir;
}
else
{
Socket.WriteLine("550 File or directory doesn't exist.");
}
}
private void RNTO(string argsText)
{
/*
This command specifies the new pathname of the file
specified in the immediately preceding "rename from"
command. Together the two commands cause a file to be
renamed.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
if (m_RenameFrom.Length == 0)
{
Socket.WriteLine("503 Bad sequence of commands.");
return;
}
string dir = GetAndNormailizePath(argsText);
if (m_pServer.OnRenameDirFile(this, m_RenameFrom, dir))
{
Socket.WriteLine("250 Directory renamed.");
m_RenameFrom = "";
}
else
{
Socket.WriteLine("550 Error renameing directory or file .");
}
}
private void RMD(string argsText)
{
/*
This command causes the directory specified in the pathname
to be removed as a directory (if the pathname is absolute)
or as a subdirectory of the current working directory (if
the pathname is relative).
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
string dir = GetAndNormailizePath(argsText);
if (m_pServer.OnDeleteDir(this, dir))
{
Socket.WriteLine("250 \"" + dir + "\" directory deleted.");
}
else
{
Socket.WriteLine("550 Directory deletion failed.");
}
}
private void MKD(string argsText)
{
/*
This command causes the directory specified in the pathname
to be created as a directory (if the pathname is absolute)
or as a subdirectory of the current working directory (if
the pathname is relative).
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
string dir = GetAndNormailizePath(argsText);
if (m_pServer.OnCreateDir(this, dir))
{
Socket.WriteLine("257 \"" + dir + "\" directory created.");
}
else
{
Socket.WriteLine("550 Directory creation failed.");
}
}
private void LIST(string argsText)
{
/*
This command causes a list to be sent from the server to the
passive DTP. If the pathname specifies a directory or other
group of files, the server should transfer a list of files
in the specified directory. If the pathname specifies a
file then the server should send current information on the
file. A null argument implies the user's current working or
default directory. The data transfer is over the data
connection in type ASCII or type EBCDIC. (The user must
ensure that the TYPE is appropriately ASCII or EBCDIC).
Since the information on a file may vary widely from system
to system, this information may be hard to use automatically
in a program, but may be quite useful to a human user.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
// ToDo: custom errors
//---- See if path accessible
FileSysEntry_EventArgs eArgs = m_pServer.OnGetDirInfo(this, GetAndNormailizePath(argsText));
if (!eArgs.Validated)
{
Socket.WriteLine("550 Access denied or directory dosen't exist !");
return;
}
DataSet ds = eArgs.DirInfo;
Socket socket = GetDataConnection();
if (socket == null)
{
return;
}
try
{
// string dir = GetAndNormailizePath(argsText);
// DataSet ds = m_pServer.OnGetDirInfo(dir);
foreach (DataRow dr in ds.Tables["DirInfo"].Rows)
{
string name = dr["Name"].ToString();
string date = Convert.ToDateTime(dr["Date"]).ToString("MM-dd-yy hh:mmtt");
bool isDir = Convert.ToBoolean(dr["IsDirectory"]);
if (isDir)
{
socket.Send(Encoding.Default.GetBytes(date + " <DIR> " + name + "\r\n"));
}
else
{
socket.Send(Encoding.Default.GetBytes(date + " " + dr["Size"] + " " + name + "\r\n"));
}
}
socket.Shutdown(SocketShutdown.Both);
socket.Close();
Socket.WriteLine("226 Transfer Complete.");
}
catch
{
Socket.WriteLine("426 Connection closed; transfer aborted.");
}
}
private void NLST(string argsText)
{
/*
This command causes a directory listing to be sent from
server to user site. The pathname should specify a
directory or other system-specific file group descriptor; a
null argument implies the current directory. The server
will return a stream of names of files and no other
information. The data will be transferred in ASCII or
EBCDIC type over the data connection as valid pathname
strings separated by <CRLF> or <NL>. (Again the user must
ensure that the TYPE is correct.) This command is intended
to return information that can be used by a program to
further process the files automatically. For example, in
the implementation of a "multiple get" function.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
//---- See if path accessible
FileSysEntry_EventArgs eArgs = m_pServer.OnGetDirInfo(this, GetAndNormailizePath(argsText));
if (!eArgs.Validated)
{
Socket.WriteLine("550 Access denied or directory dosen't exist !");
return;
}
DataSet ds = eArgs.DirInfo;
Socket socket = GetDataConnection();
if (socket == null)
{
return;
}
try
{
// string dir = GetAndNormailizePath(argsText);
// DataSet ds = m_pServer.OnGetDirInfo(dir);
foreach (DataRow dr in ds.Tables["DirInfo"].Rows)
{
socket.Send(Encoding.Default.GetBytes(dr["Name"] + "\r\n"));
}
socket.Send(Encoding.Default.GetBytes("aaa\r\n"));
socket.Shutdown(SocketShutdown.Both);
socket.Close();
Socket.WriteLine("226 Transfer Complete.");
}
catch
{
Socket.WriteLine("426 Connection closed; transfer aborted.");
}
}
private void TYPE(string argsText)
{
/*
The argument specifies the representation type as described
in the Section on Data Representation and Storage. Several
types take a second parameter. The first parameter is
denoted by a single Telnet character, as is the second
Format parameter for ASCII and EBCDIC; the second parameter
for local byte is a decimal integer to indicate Bytesize.
The parameters are separated by a <SP> (Space, ASCII code
32).
The following codes are assigned for type:
\ /
A - ASCII | | N - Non-print
|-><-| T - Telnet format effectors
E - EBCDIC| | C - Carriage Control (ASA)
/ \
I - Image
L <byte size> - Local byte Byte size
The default representation type is ASCII Non-print. If the
Format parameter is changed, and later just the first
argument is changed, Format then returns to the Non-print
default.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
if (argsText.Trim().ToUpper() == "A" || argsText.Trim().ToUpper() == "I")
{
Socket.WriteLine("200 Type is set to " + argsText + ".");
}
else
{
Socket.WriteLine("500 Invalid type " + argsText + ".");
}
}
private void PORT(string argsText)
{
/*
The argument is a HOST-PORT specification for the data port
to be used in data connection. There are defaults for both
the user and server data ports, and under normal
circumstances this command and its reply are not needed. If
this command is used, the argument is the concatenation of a
32-bit internet host address and a 16-bit TCP port address.
This address information is broken into 8-bit fields and the
value of each field is transmitted as a decimal number (in
character string representation). The fields are separated
by commas. A port command would be:
PORT h1,h2,h3,h4,p1,p2
where h1 is the high order 8 bits of the internet host
address.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
string[] parts = argsText.Split(',');
if (parts.Length != 6)
{
Socket.WriteLine("550 Invalid arguments.");
return;
}
string ip = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];
int port = (Convert.ToInt32(parts[4]) << 8) | Convert.ToInt32(parts[5]);
m_pDataConEndPoint = new IPEndPoint(Dns.GetHostEntry(ip).AddressList[0], port);
Socket.WriteLine("200 PORT Command successful.");
}
private void PASV(string argsText)
{
/*
This command requests the server-DTP to "listen" on a data
port (which is not its default data port) and to wait for a
connection rather than initiate one upon receipt of a
transfer command. The response to this command includes the
host and port address this server is listening on.
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
//--- Find free port -------------------------------//
int port = m_pServer.PassiveStartPort;
while (true)
{
try
{
m_pPassiveListener = new TcpListener(IPAddress.Any, port);
m_pPassiveListener.Start();
// If we reach here then port is free
break;
}
catch {}
port++;
}
//--------------------------------------------------//
// Notify client on what IP and port server is listening client to connect.
// PORT h1,h2,h3,h4,p1,p2
if (m_pServer.PassivePublicIP != null)
{
Socket.WriteLine("227 Entering Passive Mode (" + m_pServer.PassivePublicIP + "," + (port >> 8) +
"," + (port & 255) + ").");
}
else
{
Socket.WriteLine("227 Entering Passive Mode (" + ((IPEndPoint) Socket.LocalEndPoint).Address +
"," + (port >> 8) + "," + (port & 255) + ").");
}
m_PassiveMode = true;
}
private void SYST()
{
/*
This command is used to find out the type of operating
system at the server. The reply shall have as its first
word one of the system names listed in the current version
of the Assigned Numbers document [4].
*/
if (!Authenticated)
{
Socket.WriteLine("530 Please authenticate firtst !");
return;
}
Socket.WriteLine("215 Windows_NT");
}
private void NOOP()
{
/*
This command does not affect any parameters or previously
entered commands. It specifies no action other than that the
server send an OK reply.
*/
Socket.WriteLine("200 OK");
}
private void QUIT()
{
/*
This command terminates a USER and if file transfer is not
in progress, the server closes the control connection. If
file transfer is in progress, the connection will remain
open for result response and the server will then close it.
If the user-process is transferring files for several USERs
but does not wish to close and then reopen connections for
each, then the REIN command should be used instead of QUIT.
An unexpected close on the control connection will cause the
server to take the effective action of an abort (ABOR) and a
logout (QUIT).
*/
Socket.WriteLine("221 FTP server signing off");
}
private string GetAndNormailizePath(string path)
{
// If conatins \, replace with /
string dir = path.Replace("\\", "/");
// If doesn't end with /, append it
if (!dir.EndsWith("/"))
{
dir += "/";
}
// Current path + path wanted if path not starting /
if (!path.StartsWith("/"))
{
dir = m_CurrentDir + dir;
}
//--- Normalize path, eg. /ivx/../test must be /test -----//
ArrayList pathParts = new ArrayList();
string[] p = dir.Split('/');
pathParts.AddRange(p);
for (int i = 0; i < pathParts.Count; i++)
{
if (pathParts[i].ToString() == "..")
{
// Don't let go over root path, eg. /../ - there wanted directory upper root.
// Just skip this movement.
if (i > 0)
{
pathParts.RemoveAt(i - 1);
i--;
}
pathParts.RemoveAt(i);
i--;
}
}
dir = dir.Replace("//", "/");
return dir;
}
private Socket GetDataConnection()
{
Socket socket = null;
try
{
if (m_PassiveMode)
{
//--- Wait ftp client connection ---------------------------//
long startTime = DateTime.Now.Ticks;
// Wait ftp server to connect
while (!m_pPassiveListener.Pending())
{
Thread.Sleep(50);
// Time out after 30 seconds
if ((DateTime.Now.Ticks - startTime)/10000 > 20000)
{
throw new Exception("Ftp server didn't respond !");
}
}
//-----------------------------------------------------------//
socket = m_pPassiveListener.AcceptSocket();
Socket.WriteLine("125 Data connection open, Transfer starting.");
}
else
{
Socket.WriteLine("150 Opening data connection.");
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(m_pDataConEndPoint);
}
}
catch
{
Socket.WriteLine("425 Can't open data connection.");
return null;
}
m_PassiveMode = false;
return socket;
}
#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.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using OpenSim.Region.Physics.Manager;
using PrimMesher;
using OpenMetaverse;
using OpenSim.Region.Physics.ConvexDecompositionDotNet;
namespace OpenSim.Region.Physics.Meshing
{
public class Mesh : IMesh
{
private static MeshDataCache meshCache = new MeshDataCache();
private Dictionary<Vertex, int> m_vertices;
private MeshData _meshData;
public float[] m_normals;
private ulong _meshHash;
private C5.HashSet<IndexedTriangle> _triIndex;
public int VertCount
{
get { return m_vertices.Count; }
}
public Mesh(ulong hashCode, int numVerticies, int numTriangles)
{
_meshHash = hashCode;
m_vertices = new Dictionary<Vertex, int>();
_triIndex = new C5.HashSet<IndexedTriangle>();
_meshData = meshCache.Lease(numTriangles);
if (_meshData == null || _meshData.VertexCapacity < numVerticies || _meshData.TriangleCapacity < numTriangles)
{
_meshData = new MeshData(numVerticies, numTriangles);
}
}
public Mesh Clone()
{
Mesh result = new Mesh(_meshHash, _meshData.VertexCount, _meshData.TriangleCount);
foreach (Triangle t in _meshData.Triangles)
{
result.Add(t.v1.Clone(), t.v2.Clone(), t.v3.Clone());
}
return result;
}
/// <summary>
/// Adds a triangle to the mesh using existing vertex indexes
/// </summary>
/// <param name="v1index"></param>
/// <param name="v2Index"></param>
/// <param name="v3index"></param>
public void Add(int v1index, int v2index, int v3index)
{
this.Add(_meshData.VertexAt(v1index), _meshData.VertexAt(v2index), _meshData.VertexAt(v3index));
}
/// <summary>
/// Adds a triangle to the mesh using absolute vertices
/// </summary>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <param name="v3"></param>
public void Add(Vertex v1, Vertex v2, Vertex v3)
{
//do not include any triangles that have been smashed into lines
if (v1.Equals(v2) || v2.Equals(v3) || v1.Equals(v3))
return;
// If a vertex of the triangle is not yet in the vertices list,
// add it and set its index to the current index count
if (!m_vertices.ContainsKey(v1))
m_vertices[v1] = m_vertices.Count;
if (!m_vertices.ContainsKey(v2))
m_vertices[v2] = m_vertices.Count;
if (!m_vertices.ContainsKey(v3))
m_vertices[v3] = m_vertices.Count;
//do not include any triangles we already have
if (!_triIndex.Add(new IndexedTriangle(m_vertices[v1], m_vertices[v2], m_vertices[v3])))
return;
_meshData.AddTriangle(v1, v2, v3);
}
public void CalcNormals()
{
int iTriangles = _meshData.TriangleCount;
this.m_normals = new float[iTriangles * 3];
int i = 0;
foreach (Triangle t in _meshData.Triangles)
{
float ux, uy, uz;
float vx, vy, vz;
float wx, wy, wz;
ux = t.v1.X;
uy = t.v1.Y;
uz = t.v1.Z;
vx = t.v2.X;
vy = t.v2.Y;
vz = t.v2.Z;
wx = t.v3.X;
wy = t.v3.Y;
wz = t.v3.Z;
// Vectors for edges
float e1x, e1y, e1z;
float e2x, e2y, e2z;
e1x = ux - vx;
e1y = uy - vy;
e1z = uz - vz;
e2x = ux - wx;
e2y = uy - wy;
e2z = uz - wz;
// Cross product for normal
float nx, ny, nz;
nx = e1y * e2z - e1z * e2y;
ny = e1z * e2x - e1x * e2z;
nz = e1x * e2y - e1y * e2x;
// Length
float l = (float)Math.Sqrt(nx * nx + ny * ny + nz * nz);
float lReciprocal = 1.0f / l;
// Normalized "normal"
//nx /= l;
//ny /= l;
//nz /= l;
m_normals[i] = nx * lReciprocal;
m_normals[i + 1] = ny * lReciprocal;
m_normals[i + 2] = nz * lReciprocal;
i += 3;
}
}
public List<Vector3> getVertexList()
{
List<Vector3> result = new List<Vector3>();
foreach (Vertex v in m_vertices.Keys)
{
result.Add(new Vector3(v.X, v.Y, v.Z));
}
return result;
}
public List<float3> getVertexListAsFloat3()
{
List<float3> result = new List<float3>();
foreach (Vertex v in m_vertices.Keys)
{
result.Add(new float3(v.X, v.Y, v.Z));
}
return result;
}
public float[] getVertexListAsFloat()
{
if (m_vertices == null)
throw new NotSupportedException();
float[] result = new float[m_vertices.Count * 3];
foreach (KeyValuePair<Vertex, int> kvp in m_vertices)
{
Vertex v = kvp.Key;
int i = kvp.Value;
result[3 * i + 0] = v.X;
result[3 * i + 1] = v.Y;
result[3 * i + 2] = v.Z;
}
return result;
}
public int[] getIndexListAsIntFlipped()
{
if (_meshData == null)
throw new NotSupportedException();
int[] result = new int[_meshData.TriangleCount * 3];
for (int i = 0; i < _meshData.TriangleCount; i++)
{
Triangle t = _meshData.TriangleAt(i);
result[3 * i + 0] = m_vertices[t.v3];
result[3 * i + 1] = m_vertices[t.v2];
result[3 * i + 2] = m_vertices[t.v1];
}
return result;
}
public int[] getIndexListAsInt()
{
if (_meshData == null)
throw new NotSupportedException();
int[] result = new int[_meshData.TriangleCount * 3];
for (int i = 0; i < _meshData.TriangleCount; i++)
{
Triangle t = _meshData.TriangleAt(i);
result[3 * i + 0] = m_vertices[t.v1];
result[3 * i + 1] = m_vertices[t.v2];
result[3 * i + 2] = m_vertices[t.v3];
}
return result;
}
public List<int> getIndexListAsIntList()
{
if (_meshData == null)
throw new NotSupportedException();
List<int> result = new List<int>(_meshData.TriangleCount * 3);
for (int i = 0; i < _meshData.TriangleCount; i++)
{
Triangle t = _meshData.TriangleAt(i);
result.Add(m_vertices[t.v1]);
result.Add(m_vertices[t.v2]);
result.Add(m_vertices[t.v3]);
}
return result;
}
public List<Tuple<int, int, int>> getTriangleList()
{
List<Tuple<int, int, int>> triangles = new List<Tuple<int, int, int>>();
for (int i = 0; i < _meshData.TriangleCount; i++)
{
Triangle t = _meshData.TriangleAt(i);
int v1 = m_vertices[t.v1];
int v2 = m_vertices[t.v2];
int v3 = m_vertices[t.v3];
triangles.Add(new Tuple<int, int, int>(v1, v2, v3));
}
return triangles;
}
public Vector3[] getVertexListAsArray()
{
Vector3[] vlist = new Vector3[m_vertices.Count];
foreach (KeyValuePair<Vertex, int> kvp in m_vertices)
{
Vertex v = kvp.Key;
int i = kvp.Value;
vlist[i] = v.AsVector();
}
return vlist;
}
/// <summary>
/// frees up the source mesh data to minimize memory - call this method after calling get*Locked() functions
/// </summary>
public void ReleaseSourceMeshData()
{
m_vertices = null;
if (_meshData != null)
{
meshCache.Return(_meshData);
_meshData = null;
}
}
public void Append(IMesh newMesh)
{
if (!(newMesh is Mesh))
return;
foreach (Triangle t in ((Mesh)newMesh)._meshData.Triangles)
{
Add(t.v1, t.v2, t.v3);
}
}
// Do a linear transformation of mesh.
public void TransformLinear(float[,] matrix, float[] offset)
{
foreach (Vertex v in m_vertices.Keys)
{
if (v == null)
continue;
float x, y, z;
x = v.X * matrix[0, 0] + v.Y * matrix[1, 0] + v.Z * matrix[2, 0];
y = v.X * matrix[0, 1] + v.Y * matrix[1, 1] + v.Z * matrix[2, 1];
z = v.X * matrix[0, 2] + v.Y * matrix[1, 2] + v.Z * matrix[2, 2];
v.X = x + offset[0];
v.Y = y + offset[1];
v.Z = z + offset[2];
}
}
public void DumpRaw(String path, String name, String title)
{
if (path == null)
return;
String fileName = name + "_" + title + ".raw";
String completePath = System.IO.Path.Combine(path, fileName);
StreamWriter sw = new StreamWriter(completePath);
foreach (Triangle t in _meshData.Triangles)
{
String s = t.ToStringRaw();
sw.WriteLine(s);
}
sw.Close();
}
public void TrimExcess()
{
}
public void AddMeshVertex(float x, float y, float z)
{
_meshData.AddVertex(x, y, z);
}
public Vertex MeshVertexAt(int index)
{
return _meshData.VertexAt(index);
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using Gtk;
using Moscrif.IDE.Iface;
using Moscrif.IDE.Iface.Entities;
namespace Moscrif.IDE
{
public class SplashScreenForm : Gtk.Window, IDisposable
{
static SplashScreenForm splashScreen;
static ProgressBar progress;
static VBox vbox;
static ColorButton cbBackground;
static ComboBox cbKeyBinding;
static Button btnOk;
// ProgressTracker tracker = new ProgressTracker();
Gdk.Pixbuf bitmap;
static Gtk.Label label;
Gtk.Menu popupColor = new Gtk.Menu();
const string NOTHING ="Nothing";
const string WIN ="Visual Studio";
const string MACOSX ="XCode";
const string JAVA ="Eclipse";
const string VisualC ="Visual C++";
public static SplashScreenForm SplashScreen
{
get {
if (splashScreen == null)
splashScreen = new SplashScreenForm(true);
return splashScreen;
}
}
public SplashScreenForm(bool showSetting) : base(Gtk.WindowType.Toplevel)
{
Console.WriteLine("splash.bild.start-{0}",DateTime.Now);
waitingSplash =showSetting;
AppPaintable = true;
this.Decorated = false;
this.WindowPosition = WindowPosition.Center;
this.TypeHint = Gdk.WindowTypeHint.Splashscreen;
try {
bitmap = new Gdk.Pixbuf(System.IO.Path.Combine( MainClass.Paths.ResDir, "moscrif.png"));
} catch (Exception ex) {
Tool.Logger.Error(ex.Message);
Tool.Logger.Error("Can't load splash screen pixbuf 'moscrif.png'.");
}
progress = new ProgressBar();
progress.Fraction = 0.00;
progress.HeightRequest = 6;
vbox = new VBox();
vbox.BorderWidth = 12;
label = new Gtk.Label();
label.UseMarkup = true;
label.Xalign = 0;
//vbox.PackEnd(progress, false, true, 0);
if(showSetting){
Table table= new Table(3,3,false);
Label lbl1 = new Label("Color Scheme :");
Label lbl2 = new Label("Keybinding :");
table.Attach(lbl1,0,1,0,1,AttachOptions.Shrink,AttachOptions.Shrink,0,0);
table.Attach(lbl2,0,1,1,2,AttachOptions.Shrink,AttachOptions.Shrink,0,0);
cbBackground = new ColorButton();
table.Attach(cbBackground,1,2,0,1,AttachOptions.Fill,AttachOptions.Shrink,0,0);
cbKeyBinding = Gtk.ComboBox.NewText ();//new ComboBox();
cbKeyBinding.Name="cbKeyBinding";
if(MainClass.Settings.BackgroundColor==null){
MainClass.Settings.BackgroundColor = new Moscrif.IDE.Option.Settings.BackgroundColors(218,218,218);
/*if(MainClass.Platform.IsMac)
MainClass.Settings.BackgroundColor = new Moscrif.IDE.Settings.Settings.BackgroundColors(218,218,218);
else
MainClass.Settings.BackgroundColor = new Moscrif.IDE.Settings.Settings.BackgroundColors(224,41,47);
*/
}
cbKeyBinding.AppendText(WIN);
cbKeyBinding.AppendText(MACOSX);
cbKeyBinding.AppendText(JAVA);
cbKeyBinding.AppendText(VisualC);
if(MainClass.Platform.IsMac){
cbKeyBinding.Active = 1;
} else {
cbKeyBinding.Active = 0;
}
Gdk.Pixbuf default_pixbuf = null;
string file = System.IO.Path.Combine(MainClass.Paths.ResDir, "stock-menu.png");
//if (System.IO.File.Exists(file)) {
try {
default_pixbuf = new Gdk.Pixbuf(file);
} catch (Exception ex) {
Tool.Logger.Error(ex.Message);
}
popupColor = new Gtk.Menu();
CreateMenu();
Gtk.Button btnClose = new Gtk.Button(new Gtk.Image(default_pixbuf));
btnClose.TooltipText = MainClass.Languages.Translate("select_color");
btnClose.Relief = Gtk.ReliefStyle.None;
btnClose.CanFocus = false;
btnClose.WidthRequest = btnClose.HeightRequest = 22;
popupColor.AttachToWidget(btnClose,new Gtk.MenuDetachFunc(DetachWidget));
btnClose.Clicked += delegate {
popupColor.Popup(null,null, new Gtk.MenuPositionFunc (GetPosition) ,3,Gtk.Global.CurrentEventTime);
};
table.Attach(btnClose,2,3,0,1, AttachOptions.Shrink, AttachOptions.Shrink, 0, 0);
popupColor.ShowAll();
//}
cbBackground.Color = new Gdk.Color(MainClass.Settings.BackgroundColor.Red,
MainClass.Settings.BackgroundColor.Green,MainClass.Settings.BackgroundColor.Blue);
table.Attach(cbKeyBinding,1,2,1,2,AttachOptions.Fill,AttachOptions.Shrink,0,0);
btnOk = new Gtk.Button();
btnOk.Label = "_Ok";
btnOk.UseUnderline = true;
btnOk.Clicked+= OnButtonOkClicked;
table.Attach(btnOk,0,1,2,3,AttachOptions.Fill,AttachOptions.Shrink,0,0);
vbox.PackEnd(table, false, true, 3);
}
vbox.PackEnd(label, false, true, 3);
this.Add(vbox);
if (bitmap != null)
this.Resize(bitmap.Width, bitmap.Height);
Console.WriteLine("splash.bild.end-{0}",DateTime.Now);
this.ShowAll();
}
protected void OnButtonOkClicked (object sender, System.EventArgs e)
{
MainClass.Settings.BackgroundColor.Red = (byte)cbBackground.Color.Red;
MainClass.Settings.BackgroundColor.Green= (byte)cbBackground.Color.Green;
MainClass.Settings.BackgroundColor.Blue= (byte)cbBackground.Color.Blue;
string active = cbKeyBinding.ActiveText;
string file = System.IO.Path.Combine(MainClass.Paths.SettingDir, "keybinding");
switch (active) {
case WIN:{
KeyBindings.CreateKeyBindingsWin(file);
break;
}
case MACOSX:{
KeyBindings.CreateKeyBindingsMac(file);
break;
}
case JAVA:{
KeyBindings.CreateKeyBindingsJava(file);
break;
}
case VisualC:{
KeyBindings.CreateKeyBindingsVisualC(file);
break;
}
default:
break;
}
MainClass.Settings.SaveSettings();
waitingSplash =false;
}
private void DetachWidget(Gtk.Widget attach_widget, Gtk.Menu menu){}
static void GetPosition(Gtk.Menu menu, out int x, out int y, out bool push_in){
menu.AttachWidget.GdkWindow.GetOrigin(out x, out y);
//Console.WriteLine("GetOrigin -->>> x->{0} ; y->{1}",x,y);
x =menu.AttachWidget.Allocation.X+x;//+menu.AttachWidget.WidthRequest;
y =menu.AttachWidget.Allocation.Y+y+menu.AttachWidget.HeightRequest;
push_in = true;
}
private void CreateMenu(){
Gtk.MenuItem miRed = new Gtk.MenuItem("Red");
miRed.Activated += delegate(object sender, EventArgs e) {
if (sender.GetType() == typeof(Gtk.MenuItem)){
cbBackground.Color = new Gdk.Color(224, 41, 47);
}
};
popupColor.Add(miRed);
Gtk.MenuItem miBlue = new Gtk.MenuItem("Blue");
miBlue.Activated += delegate(object sender, EventArgs e) {
if (sender.GetType() == typeof(Gtk.MenuItem)){
cbBackground.Color = new Gdk.Color(164, 192,222);
}
};
popupColor.Add(miBlue);
Gtk.MenuItem miUbuntu = new Gtk.MenuItem("Ubuntu");
miUbuntu.Activated += delegate(object sender, EventArgs e) {
if (sender.GetType() == typeof(Gtk.MenuItem)){
cbBackground.Color = new Gdk.Color(240, 119,70);
}
};
popupColor.Add(miUbuntu);
Gtk.MenuItem miOsx = new Gtk.MenuItem("Mac");
miOsx.Activated += delegate(object sender, EventArgs e) {
if (sender.GetType() == typeof(Gtk.MenuItem)){
cbBackground.Color = new Gdk.Color(218,218 ,218);
}
};
popupColor.Add(miOsx);
}
protected override void OnDestroyed()
{
base.OnDestroyed();
if (bitmap != null) {
bitmap.Dispose();
bitmap = null;
}
}
protected override bool OnExposeEvent(Gdk.EventExpose evt)
{
if (bitmap != null) {
Gdk.GC gc = Style.LightGC(StateType.Normal);
GdkWindow.DrawPixbuf(gc, bitmap, 0, 0, 0, 0, bitmap.Width, bitmap.Height, Gdk.RgbDither.None, 0,
0);
using (Pango.Layout pl = new Pango.Layout(PangoContext)) {
Pango.FontDescription des = this.Style.FontDescription.Copy();
pl.FontDescription = des;
//pl.SetMarkup("<b><span foreground='#cccccc'>" + BuildVariables.PackageVersionLabel + "</span></b>");
int w, h;
pl.GetPixelSize(out w, out h);
GdkWindow.DrawLayout(gc, bitmap.Width - w - 75, 90, pl);
des.Dispose();
}
}
return base.OnExposeEvent(evt);
}
private bool waitingSplash = false;
public bool WaitingSplash {
get {
return waitingSplash;
}
}
public static void SetProgress(double Percentage)
{
progress.Fraction = Percentage;
RunMainLoop();
}
public void SetMessage(string Message)
{
if (bitmap == null) {
label.Text = Message;
} else {
label.Markup = "<span size='small' foreground='white'>" + Message + "</span>";
}
RunMainLoop();
}
static void RunMainLoop()
{
//DispatchService.RunPendingEvents();
}
/*void IProgressMonitor.BeginTask(string name, int totalWork)
{
tracker.BeginTask(name, totalWork);
SetMessage(tracker.CurrentTask);
}
void IProgressMonitor.BeginStepTask(string name, int totalWork, int stepSize)
{
tracker.BeginStepTask(name, totalWork, stepSize);
SetMessage(tracker.CurrentTask);
}
void IProgressMonitor.EndTask()
{
tracker.EndTask();
SetProgress(tracker.GlobalWork);
SetMessage(tracker.CurrentTask);
}
void IProgressMonitor.Step(int work)
{
tracker.Step(work);
SetProgress(tracker.GlobalWork);
}
TextWriter IProgressMonitor.Log
{
get { return Console.Out; }
}
void IProgressMonitor.ReportWarning(string message)
{
}
void IProgressMonitor.ReportSuccess(string message)
{
}
void IProgressMonitor.ReportError(string message, Exception exception)
{
}
bool IProgressMonitor.IsCancelRequested
{
get { return false; }
}
*/
/*public event MonitorHandler CancelRequested
{
add { }
remove { }
}*/
// The returned IAsyncOperation object must be thread safe
/*IAsyncOperation IProgressMonitor.AsyncOperation
{
get { return null; }
}*/
/* object IProgressMonitor.SyncRoot
{
get { return this; }
}*/
void IDisposable.Dispose()
{
Destroy();
splashScreen = null;
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent( typeof( CharacterJump ) )]
[RequireComponent( typeof( PlayerCollision ) )]
[RequireComponent( typeof( CharacterDirections ) )]
[RequireComponent( typeof( CharacterControls ) )]
public class CharacterMovement : MonoBehaviour {
#region Variables
// Variables for movement
[Tooltip( "Multiplier for how fast character may travel." )]
public float speedFactor = 5;
private float speedCoeff = 1;
private float extForce = 0;
// Variables for turning points
[HideInInspector]
public Vector3 rotationPoint;
[HideInInspector]
public float rotationAdd;
[HideInInspector]
public PositionStates.Rotation endingRotation;
[HideInInspector]
public PositionStates.Direction endingDirection;
[HideInInspector]
public bool rotation = false;
float inTime = 1.2f;
// Script to determine current moving direction of player
[HideInInspector]
public CharacterDirections directions;
// Determine what actions the player wants to complete
[HideInInspector]
public CharacterControls controller;
// Used for Jumping
[Tooltip( "How fast the character jumps in the air." )]
public float jumpSpeed = 10f;
[SerializeField]
private LayerMask[] groundLayers;
[HideInInspector]
public LayerMask m_whatIsGround;
// Used for Climbing
[Tooltip( "How fast the character climbs on walls." )]
public float climbSpeed = 10.0f;
// Used for Physics
[HideInInspector]
public PositionStates.Rotation currentRotation;
[HideInInspector]
public CharacterJump grav;
[HideInInspector]
public PlayerCollision coll;
[HideInInspector]
public Transform groundCheck;
private CapsuleCollider _collider;
// Character States ##################################
[HideInInspector]
public CharacterStates currentState;
// ###################################################
[HideInInspector]
public PlayerInput playerInput;
[HideInInspector]
public Climbing climbing;
// ###################################################
// Camera reference
public Camera mainCam;
private CamFollowObject camFollow;
public ValueFalloff extForceFalloff;
// coroutine queue
protected Queue<int> coroutineQueue = new Queue<int>( );
#endregion
//--------------------------------------------------------------------------------------------------//
//------------------------------------------INITIALIZATION------------------------------------------//
//--------------------------------------------------------------------------------------------------//
void Awake( ) {
currentRotation = PositionStates.Rotation.xPos;
_collider = GetComponent<CapsuleCollider>();
camFollow = mainCam.GetComponent<CamFollowObject>();
playerInput = new PlayerInput( this );
climbing = new Climbing( this );
foreach (LayerMask l in groundLayers)
{
m_whatIsGround = m_whatIsGround | l;
}
directions = GetComponent<CharacterDirections>( );
controller = GetComponent<CharacterControls>( );
groundCheck = transform.Find( "GroundCheck" );
extForceFalloff.valueChangeEvent.AddListener(ExternalForceUpdate);
}
void Start( ) {
PositionStates.GetConstraints( gameObject, currentRotation );
grav = GetComponent<CharacterJump>( );
coll = GetComponent<PlayerCollision>( );
currentState = playerInput;
}
//--------------------------------------------------------------------------------------------------//
//-----------------------------------------STATE FUNCTIONS------------------------------------------//
//--------------------------------------------------------------------------------------------------//
void Update( ) {
currentState.Update( );
if (grav.IsGrounded(groundCheck, m_whatIsGround))
GetComponent<Animator>().speed = GetComponent<Rigidbody>().velocity.magnitude / 10f;
if (Input.GetKeyDown(KeyCode.Space))
Jumping();
}
void FixedUpdate( ) {
currentState.FixedUpdate( );
}
void ExternalForceUpdate(float value)
{
extForce = value;
}
void OnTriggerEnter( Collider other ) {
currentState.OnTriggerEnter( other );
if ( other.tag == "Web" ) {
speedCoeff = 0.5f;
}
}
private void OnTriggerExit( Collider other ) {
currentState.OnTriggerExit( other );
if ( other.tag == "Web" ) {
speedCoeff = 1.0f;
}
}
private void OnTriggerStay( Collider other ) {
currentState.OnTriggerStay( other );
if ( other.CompareTag( "CamManip" ) && other.GetComponent<CameraZone>().cameraState != camFollow.cameraState
&& other.GetComponent<CameraZone>().WithinBounds(_collider)) {
camFollow.UpdateCameraState(other.GetComponent<CameraZone>().cameraState);
}
}
public void StartStateCoroutine( IEnumerator routine ) {
StartCoroutine( routine );
}
//--------------------------------------------------------------------------------------------------//
//-----------------------------------------HELPER FUNCTIONS-----------------------------------------//
//--------------------------------------------------------------------------------------------------//
/// <summary>
/// Automatically moves player based on direction
/// </summary>
/// <param name="dir">Direction of horizontal movement</param>
public void SetHorizontalMovement( PositionStates.Direction dir ) {
float yvel = GetComponent<Rigidbody>( ).velocity.y;
float horVel = (int)dir * speedFactor * speedCoeff;
if ( currentRotation == PositionStates.Rotation.xPos )
GetComponent<Rigidbody>( ).velocity = new Vector3( horVel + extForce, yvel, 0.0f );
else if ( currentRotation == PositionStates.Rotation.zPos )
GetComponent<Rigidbody>( ).velocity = new Vector3( 0.0f, yvel, horVel + extForce );
else if ( currentRotation == PositionStates.Rotation.xNeg )
GetComponent<Rigidbody>( ).velocity = new Vector3( -horVel + extForce, yvel, 0.0f );
else if ( currentRotation == PositionStates.Rotation.zNeg )
GetComponent<Rigidbody>( ).velocity = new Vector3( 0.0f, yvel, -horVel + extForce );
}
/// <summary>
/// Make the character jump
/// </summary>
public void Jumping( ) {
if (grav.IsGrounded( groundCheck, m_whatIsGround ) ) {
GetComponent<Rigidbody>( ).AddForce( new Vector3( 0f, jumpSpeed, 0f ), ForceMode.VelocityChange );
}
}
/// <summary>
/// Constrains the movement and rotation of the character in certain axes.
/// </summary>
public void GetConstraints( ) {
if ( currentRotation == PositionStates.Rotation.xPos ||
currentRotation == PositionStates.Rotation.xNeg )
GetComponent<Rigidbody>( ).constraints =
RigidbodyConstraints.FreezeRotation | RigidbodyConstraints.FreezePositionZ;
else
GetComponent<Rigidbody>( ).constraints =
RigidbodyConstraints.FreezeRotation | RigidbodyConstraints.FreezePositionX;
}
/// <summary>
/// Sets the new plane of rotation and movement for the character.
/// </summary>
/// <param name="newRot">New rotation of character movement.</param>
/// <param name="rPosition">Position of the rotation point.</param>
public void RotatePlane( PositionStates.Rotation newRot, Vector3 rPosition, float degrees ) {
Vector3 tmpVel = GetComponent<Rigidbody>( ).velocity;
GetComponent<Rigidbody>( ).velocity = Vector3.zero;
currentRotation = newRot;
StartCoroutine( RotateObject( gameObject.transform, degrees, .5f, true ) );
StartCoroutine( RotateObject( mainCam.transform, degrees, 1.0f, false ) );
MoveFromRot( newRot, rPosition );
GetComponent<Rigidbody>( ).velocity = new Vector3( tmpVel.z, tmpVel.y, tmpVel.x ); // swap x and z velocities
GetConstraints( );
}
/// <summary>
/// Rotate object around its y axis
/// </summary>
/// <param name="obj">Object to rotate's transform</param>
/// <param name="degrees">How many degrees to rotate object</param>
/// <param name="totalTime">Total time it should take to rotate object</param>
/// <param name="isPlayer">If the object is the player and needs new constraints</param>
IEnumerator RotateObject( Transform obj, float degrees, float totalTime, bool isPlayer ) {
int myCoroutineFrame = Time.frameCount;
coroutineQueue.Enqueue( myCoroutineFrame );
while ( coroutineQueue.Peek( ) != myCoroutineFrame ) {
yield return null;
}
float objRotation = obj.rotation.eulerAngles.y;
if ( isPlayer )
GetComponent<Rigidbody>( ).constraints =
RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;
float rate = Mathf.Abs( degrees ) / totalTime;
float mult = rate;
if ( degrees < 0 )
mult *= -1;
for ( float i = 0.0f; i < Mathf.Abs( degrees ); i += Time.deltaTime * rate ) {
obj.Rotate( 0, mult * Time.deltaTime, 0, Space.Self );
yield return null;
}
obj.rotation = Quaternion.Euler( 0.0f, Mathf.Round( (objRotation + degrees) % 360 ), 0.0f );
coroutineQueue.Dequeue( );
}
/// <summary>
/// Move the player from the point of rotation
/// </summary>
/// <param name="newRot">Ending rotation of the character</param>
/// <param name="rPosition">Position of the rotation point</param>
private void MoveFromRot( PositionStates.Rotation newRot, Vector3 rPosition ) {
if ( newRot == PositionStates.Rotation.xPos )
if ( directions.currDirection == PositionStates.Direction.right )
transform.position = new Vector3( rPosition.x + 0.5f, transform.position.y, rPosition.z );
else
transform.position = new Vector3( rPosition.x - 0.5f, transform.position.y, rPosition.z );
else if ( newRot == PositionStates.Rotation.xNeg )
if ( directions.currDirection == PositionStates.Direction.right )
transform.position = new Vector3( rPosition.x - 0.5f, transform.position.y, rPosition.z );
else
transform.position = new Vector3( rPosition.x + 0.5f, transform.position.y, rPosition.z );
else if ( newRot == PositionStates.Rotation.zPos )
if ( directions.currDirection == PositionStates.Direction.right )
transform.position = new Vector3( rPosition.x, transform.position.y, rPosition.z + 0.5f );
else
transform.position = new Vector3( rPosition.x, transform.position.y, rPosition.z - 0.5f );
else if ( newRot == PositionStates.Rotation.zNeg )
if ( directions.currDirection == PositionStates.Direction.right )
transform.position = new Vector3( rPosition.x, transform.position.y, rPosition.z - 0.5f );
else
transform.position = new Vector3( rPosition.x, transform.position.y, rPosition.z + 0.5f );
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 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.Framework.Api;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
/// <summary>
/// TestCaseAttribute is used to mark parameterized test cases
/// and provide them with their arguments.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited=false)]
public class TestCaseAttribute : DataAttribute, ITestCaseData, ITestCaseSource
{
#region Instance variables
private object[] arguments;
// NOTE: Ignore unsupressed warning about exceptionData in .NET 1.1 build
private ExpectedExceptionData exceptionData;
private object expectedResult;
private bool hasExpectedResult;
private IPropertyBag properties;
private RunState runState;
#endregion
#region Constructors
/// <summary>
/// Construct a TestCaseAttribute with a list of arguments.
/// This constructor is not CLS-Compliant
/// </summary>
/// <param name="arguments"></param>
public TestCaseAttribute(params object[] arguments)
{
this.runState = RunState.Runnable;
if (arguments == null)
this.arguments = new object[] { null };
else
this.arguments = arguments;
}
/// <summary>
/// Construct a TestCaseAttribute with a single argument
/// </summary>
/// <param name="arg"></param>
public TestCaseAttribute(object arg)
{
this.runState = RunState.Runnable;
this.arguments = new object[] { arg };
}
/// <summary>
/// Construct a TestCaseAttribute with a two arguments
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
public TestCaseAttribute(object arg1, object arg2)
{
this.runState = RunState.Runnable;
this.arguments = new object[] { arg1, arg2 };
}
/// <summary>
/// Construct a TestCaseAttribute with a three arguments
/// </summary>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <param name="arg3"></param>
public TestCaseAttribute(object arg1, object arg2, object arg3)
{
this.runState = RunState.Runnable;
this.arguments = new object[] { arg1, arg2, arg3 };
}
#endregion
#region Properties
/// <summary>
/// Gets the list of arguments to a test case
/// </summary>
public object[] Arguments
{
get { return arguments; }
}
/// <summary>
/// Gets or sets the expected result.
/// </summary>
/// <value>The result.</value>
public object ExpectedResult
{
get { return expectedResult; }
set
{
expectedResult = value;
hasExpectedResult = true;
}
}
/// <summary>
/// Gets the expected result (alias for use
/// by NUnit 2.6.x runners and for use
/// in legacy code. Remove the setter
/// after a time.)
/// </summary>
[Obsolete("Use ExpectedResult")]
public object Result
{
get { return ExpectedResult; }
set { ExpectedResult = value; }
}
/// <summary>
/// Returns true if the expected result has been set
/// </summary>
public bool HasExpectedResult
{
get { return hasExpectedResult; }
}
/// <summary>
/// Gets data about any expected exception for this test case.
/// </summary>
public ExpectedExceptionData ExceptionData
{
get { return exceptionData; }
}
/// <summary>
/// Gets or sets the expected exception.
/// </summary>
/// <value>The expected exception.</value>
public Type ExpectedException
{
get { return exceptionData.ExpectedExceptionType; }
set { exceptionData.ExpectedExceptionType = value; }
}
/// <summary>
/// Gets or sets the name the expected exception.
/// </summary>
/// <value>The expected name of the exception.</value>
public string ExpectedExceptionName
{
get { return exceptionData.ExpectedExceptionName; }
set { exceptionData.ExpectedExceptionName = value; }
}
/// <summary>
/// Gets or sets the expected message of the expected exception
/// </summary>
/// <value>The expected message of the exception.</value>
public string ExpectedMessage
{
get { return exceptionData.ExpectedMessage; }
set { exceptionData.ExpectedMessage = value; }
}
/// <summary>
/// Gets or sets the type of match to be performed on the expected message
/// </summary>
public MessageMatch MatchType
{
get { return exceptionData.MatchType; }
set { exceptionData.MatchType = value; }
}
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>The description.</value>
public string Description
{
get { return this.Properties.Get(PropertyNames.Description) as string; }
set { this.Properties.Set(PropertyNames.Description, value); }
}
private string testName;
/// <summary>
/// Gets or sets the name of the test.
/// </summary>
/// <value>The name of the test.</value>
public string TestName
{
get { return testName; }
set { testName = value; }
}
/// <summary>
/// Gets or sets the ignored status of the test
/// </summary>
public bool Ignore
{
get { return this.RunState == RunState.Ignored; }
set { this.runState = value ? RunState.Ignored : RunState.Runnable; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestCaseAttribute"/> is explicit.
/// </summary>
/// <value>
/// <c>true</c> if explicit; otherwise, <c>false</c>.
/// </value>
public bool Explicit
{
get { return this.RunState == RunState.Explicit; }
set { this.runState = value ? RunState.Explicit : RunState.Runnable; }
}
/// <summary>
/// Gets the RunState of this test case.
/// </summary>
public RunState RunState
{
get { return runState; }
}
/// <summary>
/// Gets or sets the reason for not running the test.
/// </summary>
/// <value>The reason.</value>
public string Reason
{
get { return this.Properties.Get(PropertyNames.SkipReason) as string; }
set { this.Properties.Set(PropertyNames.SkipReason, value); }
}
/// <summary>
/// Gets or sets the ignore reason. When set to a non-null
/// non-empty value, the test is marked as ignored.
/// </summary>
/// <value>The ignore reason.</value>
public string IgnoreReason
{
get { return this.Reason; }
set
{
this.runState = RunState.Ignored;
this.Reason = value;
}
}
/// <summary>
/// Gets and sets the category for this fixture.
/// May be a comma-separated list of categories.
/// </summary>
public string Category
{
get { return Properties.Get(PropertyNames.Category) as string; }
set
{
foreach (string cat in value.Split(new char[] { ',' }) )
Properties.Add(PropertyNames.Category, cat);
}
}
/// <summary>
/// Gets a list of categories for this fixture
/// </summary>
public IList Categories
{
get { return Properties[PropertyNames.Category] as IList; }
}
/// <summary>
/// NYI
/// </summary>
public IPropertyBag Properties
{
get
{
if (properties == null)
properties = new PropertyBag();
return properties;
}
}
#endregion
#region ITestCaseSource Members
/// <summary>
/// Returns an collection containing a single ITestCaseData item,
/// constructed from the arguments provided in the constructor and
/// possibly converted to match the specified method.
/// </summary>
/// <param name="method">The method for which data is being provided</param>
/// <returns></returns>
#if CLR_2_0 || CLR_4_0
public System.Collections.Generic.IEnumerable<ITestCaseData> GetTestCasesFor(System.Reflection.MethodInfo method)
#else
public System.Collections.IEnumerable GetTestCasesFor(System.Reflection.MethodInfo method)
#endif
{
ParameterSet parms;
try
{
ParameterInfo[] parameters = method.GetParameters();
int argsNeeded = parameters.Length;
int argsProvided = Arguments.Length;
parms = new ParameterSet(this);
// Special handling for params arguments
if (argsNeeded > 0 && argsProvided >= argsNeeded - 1)
{
ParameterInfo lastParameter = parameters[argsNeeded - 1];
Type lastParameterType = lastParameter.ParameterType;
Type elementType = lastParameterType.GetElementType();
if (lastParameterType.IsArray && lastParameter.IsDefined(typeof(ParamArrayAttribute), false))
{
if (argsProvided == argsNeeded)
{
Type lastArgumentType = parms.Arguments[argsProvided - 1].GetType();
if (!lastParameterType.IsAssignableFrom(lastArgumentType))
{
Array array = Array.CreateInstance(elementType, 1);
array.SetValue(parms.Arguments[argsProvided - 1], 0);
parms.Arguments[argsProvided - 1] = array;
}
}
else
{
object[] newArglist = new object[argsNeeded];
for (int i = 0; i < argsNeeded && i < argsProvided; i++)
newArglist[i] = parms.Arguments[i];
int length = argsProvided - argsNeeded + 1;
Array array = Array.CreateInstance(elementType, length);
for (int i = 0; i < length; i++)
array.SetValue(parms.Arguments[argsNeeded + i - 1], i);
newArglist[argsNeeded - 1] = array;
parms.Arguments = newArglist;
argsProvided = argsNeeded;
}
}
}
//if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
// parms.Arguments = new object[]{parms.Arguments};
// Special handling when sole argument is an object[]
if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[]))
{
if (argsProvided > 1 ||
argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[]))
{
parms.Arguments = new object[] { parms.Arguments };
}
}
if (argsProvided == argsNeeded)
PerformSpecialConversions(parms.Arguments, parameters);
}
catch (Exception ex)
{
parms = new ParameterSet(ex);
}
return new ITestCaseData[] { parms };
}
#endregion
#region Helper Methods
/// <summary>
/// Performs several special conversions allowed by NUnit in order to
/// permit arguments with types that cannot be used in the constructor
/// of an Attribute such as TestCaseAttribute or to simplify their use.
/// </summary>
/// <param name="arglist">The arguments to be converted</param>
/// <param name="parameters">The ParameterInfo array for the method</param>
private static void PerformSpecialConversions(object[] arglist, ParameterInfo[] parameters)
{
for (int i = 0; i < arglist.Length; i++)
{
object arg = arglist[i];
Type targetType = parameters[i].ParameterType;
if (arg == null)
continue;
if (arg is SpecialValue && (SpecialValue)arg == SpecialValue.Null)
{
arglist[i] = null;
continue;
}
if (targetType.IsAssignableFrom(arg.GetType()))
continue;
if (arg is DBNull)
{
arglist[i] = null;
continue;
}
bool convert = false;
if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte))
convert = arg is int;
else
if (targetType == typeof(decimal))
convert = arg is double || arg is string || arg is int;
else
if (targetType == typeof(DateTime) || targetType == typeof(TimeSpan))
convert = arg is string;
if (convert)
arglist[i] = Convert.ChangeType(arg, targetType, System.Globalization.CultureInfo.InvariantCulture);
}
}
#endregion
}
}
| |
// 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.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;
AddInternal(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),
}
}
}
}
}
});
if (score.Date != default)
AddInternal(new PlayedOnText(score.Date));
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))
{
scoreCounter.FadeIn();
scoreCounter.Current = scoreManager.GetBindableTotalScore(score);
double delay = 0;
foreach (var stat in statisticDisplays)
{
using (BeginDelayedSequence(delay))
stat.Appear();
delay += 200;
}
}
if (!withFlair)
FinishTransforms(true);
});
}
public class PlayedOnText : OsuSpriteText
{
public PlayedOnText(DateTimeOffset time)
{
Anchor = Anchor.BottomCentre;
Origin = Anchor.BottomCentre;
Font = OsuFont.GetFont(size: 10, weight: FontWeight.SemiBold);
Text = $"Played on {time.ToLocalTime():d MMMM yyyy HH:mm}";
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ProfilePropertySettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Configuration {
using System;
using System.Xml;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections;
using System.IO;
using System.Text;
using System.Web.Util;
using System.Security.Permissions;
// ProfilePropertySettingsCollection
public sealed class ProfilePropertySettings : ConfigurationElement {
private static ConfigurationPropertyCollection _properties;
private static readonly ConfigurationProperty _propName =
new ConfigurationProperty("name",
typeof(string),
null,
null,
ProfilePropertyNameValidator.SingletonInstance,
ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey);
private static readonly ConfigurationProperty _propReadOnly =
new ConfigurationProperty("readOnly",
typeof(bool),
false,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propSerializeAs =
new ConfigurationProperty("serializeAs",
typeof(SerializationMode),
SerializationMode.ProviderSpecific,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propProviderName =
new ConfigurationProperty("provider",
typeof(string),
"",
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDefaultValue =
new ConfigurationProperty("defaultValue",
typeof(string),
"",
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propType =
new ConfigurationProperty("type",
typeof(string),
"string",
ConfigurationPropertyOptions.IsTypeStringTransformationRequired);
private static readonly ConfigurationProperty _propAllowAnonymous =
new ConfigurationProperty("allowAnonymous",
typeof(bool),
false,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCustomProviderData =
new ConfigurationProperty("customProviderData",
typeof(string),
"",
ConfigurationPropertyOptions.None);
static ProfilePropertySettings() {
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add(_propName);
_properties.Add(_propReadOnly);
_properties.Add(_propSerializeAs);
_properties.Add(_propProviderName);
_properties.Add(_propDefaultValue);
_properties.Add(_propType);
_properties.Add(_propAllowAnonymous);
_properties.Add(_propCustomProviderData);
}
private Type _type;
private SettingsProvider _providerInternal;
internal ProfilePropertySettings() {
}
public ProfilePropertySettings(string name) {
Name = name;
}
public ProfilePropertySettings(string name, bool readOnly, SerializationMode serializeAs,
string providerName, string defaultValue, string profileType,
bool allowAnonymous, string customProviderData) {
Name = name;
ReadOnly = readOnly;
SerializeAs = serializeAs;
Provider = providerName;
DefaultValue = defaultValue;
Type = profileType;
AllowAnonymous = allowAnonymous;
CustomProviderData = customProviderData;
}
protected override ConfigurationPropertyCollection Properties {
get {
return _properties;
}
}
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name {
get {
return (string)base[_propName];
}
set {
base[_propName] = value;
}
}
[ConfigurationProperty("readOnly", DefaultValue = false)]
public bool ReadOnly {
get {
return (bool)base[_propReadOnly];
}
set {
base[_propReadOnly] = value;
}
}
[ConfigurationProperty("serializeAs", DefaultValue = SerializationMode.ProviderSpecific)]
public SerializationMode SerializeAs {
get {
return (SerializationMode)base[_propSerializeAs];
}
set {
base[_propSerializeAs] = value;
}
}
[ConfigurationProperty("provider", DefaultValue = "")]
public string Provider {
get {
return (string)base[_propProviderName];
}
set {
base[_propProviderName] = value;
}
}
internal SettingsProvider ProviderInternal {
get {
return _providerInternal;
}
set {
_providerInternal = value;
}
}
[ConfigurationProperty("defaultValue", DefaultValue = "")]
public string DefaultValue {
get {
return (string)base[_propDefaultValue];
}
set {
base[_propDefaultValue] = value;
}
}
[ConfigurationProperty("type", DefaultValue = "string")]
public string Type {
get {
return (string)base[_propType];
}
set {
base[_propType] = value;
}
}
internal Type TypeInternal {
get {
return _type;
}
set {
_type = value;
}
}
[ConfigurationProperty("allowAnonymous", DefaultValue = false)]
public bool AllowAnonymous {
get {
return (bool)base[_propAllowAnonymous];
}
set {
base[_propAllowAnonymous] = value;
}
}
[ConfigurationProperty("customProviderData", DefaultValue = "")]
public string CustomProviderData {
get {
return (string)base[_propCustomProviderData];
}
set {
base[_propCustomProviderData] = value;
}
}
} // class ProfilePropertySettings
}
| |
using cogsburger;
using Newtonsoft.Json;
using NJsonSchema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using Xunit;
using Cogs.SimpleTypes;
using Cogs.DataAnnotations;
namespace Cogs.Tests.Integration
{
public class IntegrationTests
{
[Fact]
public async void CsharpWritesValidJson()
{
Hamburger hamburger = new Hamburger
{
ID = Guid.NewGuid().ToString(),
Description = "Large Special",
HamburgerName = "Four Corners Burger",
Date = new DateTime(2017, 9, 2),
DateTime = new DateTimeOffset(new DateTime(2017, 9, 2, 13, 23, 32), new TimeSpan(+1, 0, 0))
};
Hamburger hamburger2 = new Hamburger
{
ID = Guid.NewGuid().ToString(),
Description = "small Special",
HamburgerName = "Five Corners Burger",
};
MultilingualString describe = new MultilingualString
{
Language = "eng",
Content = "Just a normal cow"
};
GMonth monthG = new GMonth(9, "Z");
GDay dayG = new GDay(6, "+09:00");
GMonthDay mDay = new GMonthDay(6, 9, "-12:00");
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
Name = "Cow",
LingualDescription = new List<MultilingualString> { describe },
CountryOfOrigin = "USA",
Date = new DateTime(2017, 6, 9),
Time = new DateTimeOffset(2017, 6, 9, 2, 32, 32, new TimeSpan(+1, 0, 0)),
GMonthDay = mDay
};
List<decimal> heights = new List<decimal> { 5, 5 };
GYearMonth GYM = new GYearMonth(2017, 06, "Z");
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
Name = "Sesame seed bun",
Description = "freshly baked daily!",
Size = new Dimensions { Width = 6, Length = 5.00, Height = heights },
Gyearmonth = GYM
};
Bread bread2 = new Bread
{
ID = Guid.NewGuid().ToString(),
Name = "Sepcial Bun",
Description = " a special bun never had before!",
Size = new Dimensions { Width = 5, Length = 5.00, Height = heights },
Gyearmonth = GYM
};
Roll roll = new Roll
{
ID = Guid.NewGuid().ToString(),
Name = "Sesame seed bun",
Description = "A nice bun"
};
Condiment condiment = new Condiment
{
ID = Guid.NewGuid().ToString(),
Name = "mustard",
Description = "special mustard",
IsSpecial = true
};
Condiment condiment2 = new Condiment
{
ID = Guid.NewGuid().ToString(),
Name = "ketchup",
Description = "normal ketchup",
IsSpecial = false
};
MeatPatty meatPatty = new MeatPatty
{
ID = Guid.NewGuid().ToString()
};
MeatPatty meatPatty2 = new MeatPatty
{
ID = Guid.NewGuid().ToString()
};
VeggiePatty veggiePatty = new VeggiePatty
{
ID = Guid.NewGuid().ToString(),
VegetableUsed = new List<string> { "red beans", "black beans" }
};
VeggiePatty veggiePatty2 = new VeggiePatty
{
ID = Guid.NewGuid().ToString(),
VegetableUsed = new List<string> { "garbonzo beans" }
};
hamburger.Enclosure = roll;
hamburger2.Enclosure = bread;
hamburger.Patty = new List<Protein>
{
meatPatty,
meatPatty2
};
hamburger2.Patty = new List<Protein> { veggiePatty };
ItemContainer container = new ItemContainer();
ItemContainer container2 = new ItemContainer();
ItemContainer container3 = new ItemContainer();
ItemContainer container4 = new ItemContainer();
//container
container.TopLevelReferences.Add(hamburger);
container.Items.Add(bread);
container.Items.Add(hamburger);
container.Items.Add(roll);
container.Items.Add(meatPatty);
container.Items.Add(meatPatty2);
//container 2
container2.Items.Add(bread2);
container2.Items.Add(meatPatty);
//container 3
container3.Items.Add(condiment);
container3.Items.Add(condiment2);
//container 4
container4.TopLevelReferences.Add(hamburger2);
container4.Items.Add(hamburger2);
container4.Items.Add(animal);
container4.Items.Add(veggiePatty);
container4.Items.Add(veggiePatty2);
container4.Items.Add(bread);
// evaluation
string schemaPath = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), ".."), ".."), ".."), "..");
string jsonSchema = File.ReadAllText(Path.Combine(Path.Combine(schemaPath, "generated"), "jsonSchema.json"));
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None
};
JsonSchema4 schema = await JsonSchema4.FromJsonAsync(jsonSchema);
var containers = new ItemContainer[] { container, container2, container3, container4 };
for (int i = 0; i < 4; i++)
{
// test serializing
string json = JsonConvert.SerializeObject(containers[i]);
var errors = schema.Validate(json);
Assert.Empty(errors);
// test parsing
ItemContainer newContainer = JsonConvert.DeserializeObject<ItemContainer>(json);
var newJson = JsonConvert.SerializeObject(newContainer);
errors = schema.Validate(newJson);
Assert.Empty(errors);
// check that outputs are the same
Assert.Equal(json, newJson);
}
}
[Fact]
public async void JsonCreatesOneInstancePerIdentifiedItem()
{
Hamburger hamburger = new Hamburger
{
ID = Guid.NewGuid().ToString(),
Description = "Large Special",
HamburgerName = "Four Corners Burger"
};
MeatPatty beef = new MeatPatty()
{
ID = Guid.NewGuid().ToString()
};
hamburger.Patty.Add(beef);
hamburger.Patty.Add(beef);
ItemContainer container = new ItemContainer();
container.Items.Add(hamburger);
container.Items.Add(beef);
container.TopLevelReferences.Add(hamburger);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.NotEmpty(container2.TopLevelReferences);
Assert.IsType<Hamburger>(container2.Items[0]);
Assert.IsType<MeatPatty>(container2.Items[1]);
Hamburger hamburger2 = container2.Items.First() as Hamburger;
Assert.True(Object.ReferenceEquals(container2.Items[1], hamburger2.Patty[0]));
Assert.True(Object.ReferenceEquals(hamburger2.Patty[0], hamburger2.Patty[1]));
Assert.True(Object.ReferenceEquals(hamburger2, container2.TopLevelReferences[0]));
}
[Fact]
public async void SimpleTypeGMonthYear()
{
ItemContainer container = new ItemContainer();
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
Gyearmonth = new GYearMonth(9, 24, "-06:00")
};
container.Items.Add(bread);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Bread>(container2.Items.First());
Bread bread2 = container2.Items.First() as Bread;
Assert.Equal(bread.Gyearmonth, bread2.Gyearmonth);
}
[Fact]
public async void SimpleTypeGMonthYearWithoutTimezone()
{
ItemContainer container = new ItemContainer();
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
Gyearmonth = new GYearMonth(9, 24, null)
};
container.Items.Add(bread);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Bread>(container2.Items.First());
Bread bread2 = container2.Items.First() as Bread;
Assert.Equal(bread.Gyearmonth, bread2.Gyearmonth);
}
[Fact]
public async void SimpleTypeGMonthYearList()
{
ItemContainer container = new ItemContainer();
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
GYearMonthList = new List<GYearMonth>()
{
new GYearMonth(9, 24, null),
new GYearMonth(12, 93, "+09:00")
}
};
container.Items.Add(bread);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Bread>(container2.Items.First());
Bread bread2 = container2.Items.First() as Bread;
Assert.Equal(bread.GYearMonthList.Count, bread2.GYearMonthList.Count);
Assert.Equal(bread.GYearMonthList[0], bread2.GYearMonthList[0]);
Assert.Equal(bread.GYearMonthList[1], bread2.GYearMonthList[1]);
}
[Fact]
public async void SimpleTypeBoolean()
{
ItemContainer container = new ItemContainer();
Roll roll = new Roll
{
ID = Guid.NewGuid().ToString(),
SesameSeeds = true
};
container.Items.Add(roll);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Roll>(container2.Items.First());
Roll roll2 = container2.Items.First() as Roll;
Assert.Equal(roll.SesameSeeds, roll2.SesameSeeds);
}
[Fact]
public async void SimpleTypeDuration()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
Duration = new TimeSpan(10000000)
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.Duration, animal2.Duration);
}
[Fact]
public async void SimpleTypeDurationList()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
Durations = new List<TimeSpan>()
{
new TimeSpan(10000000),
new TimeSpan(0)
}
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.Durations.Count, animal2.Durations.Count);
Assert.Equal(animal.Durations[0], animal.Durations[0]);
Assert.Equal(animal.Durations[1], animal.Durations[1]);
}
[Fact]
public async void SimpleTypeDate()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
Date = new DateTime(2017, 9, 2)
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.Date.Date, animal2.Date.Date);
}
[Fact]
public async void SimpleTypeDateList()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
Dates = new List<DateTimeOffset>()
{
new DateTime(2017, 9, 2),
new DateTime(1,1,1),
new DateTime(1562, 8, 23, 5, 12, 46)
}
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.Dates.Count, animal2.Dates.Count);
for (int i = 0; i < animal.Dates.Count; i++)
{
Assert.Equal(animal.Dates[i].Date, animal2.Dates[i].Date);
}
}
[Fact]
public async void SimpleTypeDateTime()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
DateTime = new DateTimeOffset(new DateTime(2017, 9, 2, 13, 23, 32), new TimeSpan(-1, 0, 0))
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.DateTime, animal2.DateTime);
}
[Fact]
public async void SimpleTypeDateTimeList()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
DateTimes = new List<DateTimeOffset>()
{
new DateTimeOffset(new DateTime(2017, 9, 2, 13, 23, 32), new TimeSpan(+1, 0, 0)),
new DateTimeOffset(1,1,1,0,0,0, new TimeSpan())
}
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.DateTimes.Count, animal2.DateTimes.Count);
Assert.Equal(animal.DateTimes[0], animal2.DateTimes[0]);
Assert.Equal(animal.DateTimes[1], animal2.DateTimes[1]);
}
[Fact]
public async void SimpleTypeTime()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
Time = new DateTimeOffset(2017, 6, 9, 2, 32, 32, new TimeSpan())
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.Time.TimeOfDay, animal2.Time.TimeOfDay);
}
[Fact]
public async void SimpleTypeTimeList()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
Times = new List<DateTimeOffset>
{
new DateTimeOffset(2017, 6, 9, 2, 32, 32, new TimeSpan()),
new DateTimeOffset(1996, 8, 23, 4, 32, 3, new TimeSpan())
}
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.Times.Count, animal2.Times.Count);
for (int i = 0; i < animal.Times.Count; i++)
{
Assert.Equal(animal.Times[i].TimeOfDay, animal2.Times[i].TimeOfDay);
}
}
[Fact]
public async void SimpleTypeGyear()
{
ItemContainer container = new ItemContainer();
VeggiePatty patty = new VeggiePatty
{
ID = Guid.NewGuid().ToString(),
GYear = new GYear(9, "Z")
};
container.Items.Add(patty);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<VeggiePatty>(container2.Items.First());
VeggiePatty patty2 = container2.Items.First() as VeggiePatty;
Assert.Equal(patty.GYear, patty2.GYear);
}
[Fact]
public async void SimpleTypeGyearWithoutTimeZone()
{
ItemContainer container = new ItemContainer();
VeggiePatty patty = new VeggiePatty
{
ID = Guid.NewGuid().ToString(),
GYear = new GYear(9)
};
container.Items.Add(patty);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<VeggiePatty>(container2.Items.First());
VeggiePatty patty2 = container2.Items.First() as VeggiePatty;
Assert.Equal(patty.GYear, patty2.GYear);
}
[Fact]
public async void SimpleTypeGyearList()
{
ItemContainer container = new ItemContainer();
Cheese cheese = new Cheese
{
ID = Guid.NewGuid().ToString(),
Years = new List<GYear>()
{
new GYear(2017, "+09:00"),
new GYear(1996, null)
}
};
container.Items.Add(cheese);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Cheese>(container2.Items.First());
Cheese cheese2 = container2.Items.First() as Cheese;
Assert.Equal(cheese.Years.Count, cheese2.Years.Count);
for (int i = 0; i < cheese.Years.Count; i++)
{
Assert.Equal(cheese.Years[i], cheese2.Years[i]);
Assert.Equal(cheese.Years[i], cheese2.Years[i]);
}
}
[Fact]
public async void SimpleTypeGMonthDay()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
GMonthDay = new GMonthDay(9, 3, "Z")
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.GMonthDay, animal2.GMonthDay);
}
[Fact]
public async void SimpleTypeGMonthDayWithoutTimeZone()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
GMonthDay = new GMonthDay(9, 3, null)
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.GMonthDay, animal2.GMonthDay);
}
[Fact]
public async void SimpleTypeGMonthDayList()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
GMonthDays = new List<GMonthDay>()
{
new GMonthDay(9, 3, null),
new GMonthDay(0, 0, "-09:00")
}
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.GMonthDays.Count, animal2.GMonthDays.Count);
Assert.Equal(animal.GMonthDays[0], animal2.GMonthDays[0]);
Assert.Equal(animal.GMonthDays[1], animal2.GMonthDays[1]);
}
[Fact]
public async void SimpleTypeGDay()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
GDay = new GDay(15, "+10:00")
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.GDay, animal2.GDay);
}
[Fact]
public async void SimpleTypeGDayWithoutTimeZone()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
GDay = new GDay(15, null)
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.GDay, animal2.GDay);
}
[Fact]
public async void SimpleTypeGDayList()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
GDays = new List<GDay>()
{
new GDay(15, null),
new GDay(0, "Z")
}
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.GDays.Count, animal2.GDays.Count);
Assert.Equal(animal.GDays[0], animal2.GDays[0]);
Assert.Equal(animal.GDays[1], animal2.GDays[1]);
}
[Fact]
public async void SimpleTypeGMonth()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
GMonth = new GMonth(2, "+01:00")
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.GMonth, animal2.GMonth);
}
[Fact]
public async void SimpleTypeGMonthWihtoutTimeZone()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
GMonth = new GMonth(2, null)
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.GMonth, animal2.GMonth);
}
[Fact]
public async void SimpleTypeGMonthList()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
GMonths = new List<GMonth>()
{
new GMonth(2, null),
new GMonth(8, "Z")
}
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.GMonths.Count, animal2.GMonths.Count);
Assert.Equal(animal.GMonths[0], animal2.GMonths[0]);
Assert.Equal(animal.GMonths[1], animal2.GMonths[1]);
}
[Fact]
public async void SimpleTypeAnyURI()
{
ItemContainer container = new ItemContainer();
Condiment condiment = new Condiment
{
ID = Guid.NewGuid().ToString(),
AnyURI = new Uri("http://www.colectica.com/")
};
container.Items.Add(condiment);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Condiment>(container2.Items.First());
Condiment condiment2 = container2.Items.First() as Condiment;
Assert.Equal(condiment.AnyURI, condiment2.AnyURI);
}
[Fact]
public void DateTimeOffsetSerialization()
{
string format = @"yyyy-MM-dd\THH:mm:ss.FFFFFFFK";
DateTimeOffset offset1 = new DateTimeOffset(2017, 12, 12, 5, 33, 45, 899, new TimeSpan(-4, -30, 0));
string offsetFormat1 = offset1.ToString(format);
string json1 = JsonConvert.SerializeObject(offset1);
Assert.Equal("\"" + offsetFormat1 + "\"", json1);
DateTimeOffset offset2 = JsonConvert.DeserializeObject<DateTimeOffset>(json1);
Assert.Equal(offset1, offset2);
}
[Fact]
public async void SimpleTypeString()
{
ItemContainer container = new ItemContainer();
Condiment condiment = new Condiment
{
ID = Guid.NewGuid().ToString(),
Description = @"My
Description"
};
container.Items.Add(condiment);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Condiment>(container2.Items.First());
Condiment condiment2 = container2.Items.First() as Condiment;
Assert.Equal(condiment.Description, condiment2.Description);
}
[Fact]
public async void SimpleTypeAnyURIList()
{
ItemContainer container = new ItemContainer();
Condiment condiment = new Condiment
{
ID = Guid.NewGuid().ToString(),
Uris = new List<Uri>
{
new Uri("http://www.colectica.com/"),
new Uri("https://github.com/Colectica/cogs")
}
};
container.Items.Add(condiment);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Condiment>(container2.Items.First());
Condiment condiment2 = container2.Items.First() as Condiment;
Assert.Equal(condiment.Uris.Count, condiment2.Uris.Count);
Assert.Equal(condiment.Uris[0], condiment2.Uris[0]);
Assert.Equal(condiment.Uris[1], condiment2.Uris[1]);
}
[Fact]
public async void SimpleTypeLanguage()
{
ItemContainer container = new ItemContainer();
Cheese cheese = new Cheese
{
ID = Guid.NewGuid().ToString(),
Language = "en"
};
container.Items.Add(cheese);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Cheese>(container2.Items.First());
Cheese cheese2 = container2.Items.First() as Cheese;
Assert.Equal(cheese.Language, cheese2.Language);
}
[Fact]
public async void SimpleTypeCogsDateDateTime()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
CDate = new CogsDate(new DateTimeOffset(new DateTime(1996, 8, 23, 4, 37, 4),
new TimeSpan(+3, 0, 0)), false)
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.CDate.GetValue(), animal2.CDate.GetValue());
}
[Fact]
public async void SimpleTypeCogsDateDate()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
CDate = new CogsDate(new DateTime(2017, 9, 2), true)
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.CDate.GetValue(), animal2.CDate.GetValue());
}
[Fact]
public async void SimpleTypeCogsDateYearMonth()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
CDate = new CogsDate(new GYearMonth(2017, 7, "Z"))
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.CDate.GetValue(), animal2.CDate.GetValue());
}
[Fact]
public async void SimpleTypeCogsDateYearMonthNoTimeZone()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
CDate = new CogsDate(new GYearMonth(2017, 7, null))
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.CDate.GetValue(), animal2.CDate.GetValue());
}
[Fact]
public async void SimpleTypeCogsDateYear()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
CDate = new CogsDate(new GYear(2017, "Z"))
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.CDate.GetValue(), animal2.CDate.GetValue());
}
[Fact]
public async void SimpleTypeCogsDateYearNoTimeZone()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
CDate = new CogsDate(new GYear(2017, null))
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.CDate.GetValue(), animal2.CDate.GetValue());
}
[Fact]
public async void SimpleTypeCogsDateDuration()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
CDate = new CogsDate(new TimeSpan(1562))
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.Equal(animal.CDate.GetValue(), animal2.CDate.GetValue());
}
[Fact]
public async void SimpleTypeCogsDateList()
{
ItemContainer container = new ItemContainer();
Condiment condiment = new Condiment
{
ID = Guid.NewGuid().ToString(),
CDates = new List<CogsDate>
{
new CogsDate(new TimeSpan(1562)),
new CogsDate(new GYear(2017, "+01:00")),
new CogsDate(new DateTimeOffset(new DateTime(1996, 8, 23, 4, 37, 4),
new TimeSpan(+3, 0, 0)), false),
new CogsDate(new DateTime(2017, 9, 2), true),
new CogsDate(new GYearMonth(2017, 7, "+02:00")),
new CogsDate(new GYearMonth(2017, 7, null)),
new CogsDate(new GYear(2017, null))
},
Description = "Dates"
};
container.Items.Add(condiment);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Condiment>(container2.Items.First());
Condiment condiment2 = container2.Items.First() as Condiment;
Assert.Equal(condiment.CDates.Count, condiment2.CDates.Count);
for (int i = 0; i < condiment.CDates.Count; i++)
{
Assert.Equal(condiment.CDates[i].GetValue(), condiment2.CDates[i].GetValue());
}
}
[Fact]
public async void ReusableToItem()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString()
};
container.Items.Add(animal);
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
Size = new Dimensions
{
Creature = animal
}
};
container.Items.Add(bread);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Bread>(container2.Items[1]);
Bread bread2 = container2.Items[1] as Bread;
Assert.Equal(bread.Size.Creature.ID, bread2.Size.Creature.ID);
}
[Fact]
public async void ReusabletoSimple()
{
ItemContainer container = new ItemContainer();
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
Size = new Dimensions
{
CogsDate = new CogsDate(new TimeSpan(10000000))
}
};
container.Items.Add(bread);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Bread>(container2.Items.First());
Bread bread2 = container2.Items.First() as Bread;
Assert.Equal(bread.Size.CogsDate.GetValue(), bread2.Size.CogsDate.GetValue());
}
[Fact]
public async void ReusabletoSimpleList()
{
ItemContainer container = new ItemContainer();
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
GYearMonthList = new List<GYearMonth>()
{
new GYearMonth(2017, 7 , null),
new GYearMonth(1996, 8, "+01:00")
}
};
container.Items.Add(bread);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Bread>(container2.Items.First());
Bread bread2 = container2.Items.First() as Bread;
Assert.Equal(bread.GYearMonthList.Count, bread2.GYearMonthList.Count);
Assert.Equal(bread.GYearMonthList[0], bread2.GYearMonthList[0]);
Assert.Equal(bread.GYearMonthList[1], bread2.GYearMonthList[1]);
}
[Fact]
public async void NestedReusableItem()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString()
};
container.Items.Add(animal);
Part sirloin = new Part()
{
PartName = "Sirloin",
SubComponents = new List<Part>()
{
new Part()
{
PartName = "Tenderloin",
SubComponents = new List<Part>()
{
new Part()
{
PartName = "marbled wagyu"
}
}
}
}
};
animal.MeatPieces.Add(sirloin);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.NotEmpty(animal2.MeatPieces);
Assert.NotNull(animal2.MeatPieces[0]);
Assert.NotEmpty(animal2.MeatPieces[0].SubComponents);
Assert.NotNull(animal2.MeatPieces[0].SubComponents[0]);
Assert.NotEmpty(animal2.MeatPieces[0].SubComponents[0].SubComponents);
Assert.NotNull(animal2.MeatPieces[0].SubComponents[0].SubComponents[0]);
}
[Fact]
public async void NestedReusableItemLists()
{
ItemContainer container = new ItemContainer();
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString()
};
container.Items.Add(animal);
Part sirloin = new Part()
{
PartName = "Sirloin",
SubComponents = new List<Part>()
{
new Part()
{
PartName = "Tenderloin",
SubComponents = new List<Part>()
{
new Part()
{
PartName = "marbled wagyu"
},
new Part()
{
PartName = "blood"
}
}
}
}
};
animal.MeatPieces.Add(sirloin);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items.First() as Animal;
Assert.NotEmpty(animal2.MeatPieces);
Assert.NotNull(animal2.MeatPieces[0]);
Assert.NotEmpty(animal2.MeatPieces[0].SubComponents);
Assert.NotNull(animal2.MeatPieces[0].SubComponents[0]);
Assert.NotEmpty(animal2.MeatPieces[0].SubComponents[0].SubComponents);
Assert.NotNull(animal2.MeatPieces[0].SubComponents[0].SubComponents[0]);
}
[Fact]
public void ListsInReusableItemsAreInitialized()
{
Part sirloin = new Part();
Assert.NotNull(sirloin.SubComponents);
}
[Fact]
public void ListsInItemsAreInitialized()
{
Animal cow = new Animal();
Assert.NotNull(cow.Times);
}
[Fact]
public async void ListOfReusableType()
{
ItemContainer container = new ItemContainer();
MultilingualString describe1 = new MultilingualString
{
Content = "This is in english UK",
Language = "eng-uk"
};
MultilingualString describe2 = new MultilingualString
{
Content = "This is in english US",
Language = "eng-sub"
};
Animal animal = new Animal
{
ID = Guid.NewGuid().ToString(),
LingualDescription = new List<MultilingualString>() {describe1, describe2 }
};
container.Items.Add(animal);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Animal>(container2.Items.First());
Animal animal2 = container2.Items[0] as Animal;
for(int i = 0; i < animal.LingualDescription.Count; i++)
{
Assert.Equal(animal.LingualDescription[0].Content, animal2.LingualDescription[0].Content);
Assert.Equal(animal.LingualDescription[0].Language, animal2.LingualDescription[0].Language);
}
}
[Fact]
public async void ListOfSimpleTypeGyear()
{
ItemContainer container = new ItemContainer();
GYear year1 = new GYear(1997, "+09:00");
GYear year2 = new GYear(2002, "+09:00");
GYear year3 = new GYear(2017, "Z");
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
Gyear = new List<GYear>() { year1, year2, year3 }
};
container.Items.Add(bread);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Bread>(container2.Items.First());
Bread bread2 = container2.Items.First() as Bread;
for(int i = 0; i < bread.Gyear.Count;i++)
{
Assert.Equal(bread.Gyear[i], bread2.Gyear[i]);
}
}
[Fact]
public async void ListOfSimpleTypeGMonth()
{
ItemContainer container = new ItemContainer();
GMonth month1 = new GMonth(6, "Z");
GMonth month2 = new GMonth(9, "+09:00");
GMonth month3 = new GMonth(17, "+01:00");
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
Gmonth = new List<GMonth>() { month1, month2, month3 }
};
container.Items.Add(bread);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Bread>(container2.Items.First());
Bread bread2 = container2.Items.First() as Bread;
for (int i = 0; i < bread.Gmonth.Count; i++)
{
Assert.Equal(bread.Gmonth[i], bread2.Gmonth[i]);
}
}
[Fact]
public async void ListOfSimpleTypeGDay()
{
ItemContainer container = new ItemContainer();
GDay day1 = new GDay(1, "Z");
GDay day2 = new GDay(9, "+09:00");
GDay day3 = new GDay(12, "-01:00");
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
Gday = new List<GDay>() { day1, day2, day3 }
};
container.Items.Add(bread);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Bread>(container2.Items.First());
Bread bread2 = container2.Items.First() as Bread;
for (int i = 0; i < bread.Gday.Count; i++)
{
Assert.Equal(bread.Gday[i], bread2.Gday[i]);
}
}
[Fact]
public async void ListOfSimpleTypeGMonthDay()
{
ItemContainer container = new ItemContainer();
GMonthDay day1 = new GMonthDay(1, 2, "+09:00");
GMonthDay day2 = new GMonthDay(9, 12, "Z");
GMonthDay day3 = new GMonthDay(12, 23, "+00:00");
Bread bread = new Bread
{
ID = Guid.NewGuid().ToString(),
GMonthDay = new List<GMonthDay>() { day1, day2, day3 }
};
container.Items.Add(bread);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Bread>(container2.Items.First());
Bread bread2 = container2.Items.First() as Bread;
for (int i = 0; i < bread.Gday.Count; i++)
{
Assert.Equal(bread.Gday[i], bread2.Gday[i]);
}
}
[Fact]
public async void ListOfSimpleTypeGYearMonth()
{
ItemContainer container = new ItemContainer();
GYearMonth ym1 = new GYearMonth(1996, 2, "Z");
GYearMonth ym2 = new GYearMonth(2002, 9, "+03:00");
GYearMonth ym3 = new GYearMonth(2017, 12, "+02:00");
Roll roll = new Roll
{
ID = Guid.NewGuid().ToString(),
GYearMonth = new List<GYearMonth>() { ym1, ym2, ym3 }
};
container.Items.Add(roll);
JsonSchema4 schema = await GetJsonSchema();
string json = JsonConvert.SerializeObject(container);
var errors = schema.Validate(json);
Assert.Empty(errors);
ItemContainer container2 = JsonConvert.DeserializeObject<ItemContainer>(json);
string json2 = JsonConvert.SerializeObject(container2);
Assert.Equal(json, json2);
Assert.NotEmpty(container2.Items);
Assert.IsType<Roll>(container2.Items.First());
Roll roll2 = container2.Items.First() as Roll;
for(int i = 0; i < roll.GYearMonth.Count; i++)
{
Assert.Equal(roll.GYearMonth[i], roll2.GYearMonth[i]);
}
}
private async Task<JsonSchema4> GetJsonSchema()
{
// TODO build the json schema into the generated assembly as a resource
string schemaPath = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "generated", "jsonSchema.json");
string jsonSchema = File.ReadAllText(schemaPath);
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None
};
JsonSchema4 schema = await JsonSchema4.FromJsonAsync(jsonSchema);
return schema;
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the ImportImage operation.
/// Import single or multi-volume disk images or EBS snapshots into an Amazon Machine
/// Image (AMI).
/// </summary>
public partial class ImportImageRequest : AmazonEC2Request
{
private string _architecture;
private ClientData _clientData;
private string _clientToken;
private string _description;
private List<ImageDiskContainer> _diskContainers = new List<ImageDiskContainer>();
private string _hypervisor;
private string _licenseType;
private string _platform;
private string _roleName;
/// <summary>
/// Gets and sets the property Architecture.
/// <para>
/// The architecture of the virtual machine.
/// </para>
///
/// <para>
/// Valid values: <code>i386</code> | <code>x86_64</code>
/// </para>
/// </summary>
public string Architecture
{
get { return this._architecture; }
set { this._architecture = value; }
}
// Check to see if Architecture property is set
internal bool IsSetArchitecture()
{
return this._architecture != null;
}
/// <summary>
/// Gets and sets the property ClientData.
/// <para>
/// The client-specific data.
/// </para>
/// </summary>
public ClientData ClientData
{
get { return this._clientData; }
set { this._clientData = value; }
}
// Check to see if ClientData property is set
internal bool IsSetClientData()
{
return this._clientData != null;
}
/// <summary>
/// Gets and sets the property ClientToken.
/// <para>
/// The token to enable idempotency for VM import requests.
/// </para>
/// </summary>
public string ClientToken
{
get { return this._clientToken; }
set { this._clientToken = value; }
}
// Check to see if ClientToken property is set
internal bool IsSetClientToken()
{
return this._clientToken != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A description string for the import image task.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property DiskContainers.
/// <para>
/// Information about the disk containers.
/// </para>
/// </summary>
public List<ImageDiskContainer> DiskContainers
{
get { return this._diskContainers; }
set { this._diskContainers = value; }
}
// Check to see if DiskContainers property is set
internal bool IsSetDiskContainers()
{
return this._diskContainers != null && this._diskContainers.Count > 0;
}
/// <summary>
/// Gets and sets the property Hypervisor.
/// <para>
/// The target hypervisor platform.
/// </para>
///
/// <para>
/// Valid values: <code>xen</code>
/// </para>
/// </summary>
public string Hypervisor
{
get { return this._hypervisor; }
set { this._hypervisor = value; }
}
// Check to see if Hypervisor property is set
internal bool IsSetHypervisor()
{
return this._hypervisor != null;
}
/// <summary>
/// Gets and sets the property LicenseType.
/// <para>
/// The license type to be used for the Amazon Machine Image (AMI) after importing.
/// </para>
///
/// <para>
/// <b>Note:</b> You may only use BYOL if you have existing licenses with rights to use
/// these licenses in a third party cloud like AWS. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/VMImportPrerequisites.html">VM
/// Import/Export Prerequisites</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </para>
///
/// <para>
/// Valid values: <code>AWS</code> | <code>BYOL</code>
/// </para>
/// </summary>
public string LicenseType
{
get { return this._licenseType; }
set { this._licenseType = value; }
}
// Check to see if LicenseType property is set
internal bool IsSetLicenseType()
{
return this._licenseType != null;
}
/// <summary>
/// Gets and sets the property Platform.
/// <para>
/// The operating system of the virtual machine.
/// </para>
///
/// <para>
/// Valid values: <code>Windows</code> | <code>Linux</code>
/// </para>
/// </summary>
public string Platform
{
get { return this._platform; }
set { this._platform = value; }
}
// Check to see if Platform property is set
internal bool IsSetPlatform()
{
return this._platform != null;
}
/// <summary>
/// Gets and sets the property RoleName.
/// <para>
/// The name of the role to use when not using the default role, 'vmimport'.
/// </para>
/// </summary>
public string RoleName
{
get { return this._roleName; }
set { this._roleName = value; }
}
// Check to see if RoleName property is set
internal bool IsSetRoleName()
{
return this._roleName != null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
// TODO: Once we upgrade to C# 6, remove all of these and simply import the libcurl class.
using CURLcode = Interop.libcurl.CURLcode;
using CURLINFO = Interop.libcurl.CURLINFO;
using CURLMcode = Interop.libcurl.CURLMcode;
using CURLoption = Interop.libcurl.CURLoption;
using SafeCurlMultiHandle = Interop.libcurl.SafeCurlMultiHandle;
using size_t = System.UInt64; // TODO: IntPtr
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
/// <summary>Provides a multi handle and the associated processing for all requests on the handle.</summary>
private sealed class MultiAgent
{
private static readonly Interop.libcurl.curl_readwrite_callback s_receiveHeadersCallback = CurlReceiveHeadersCallback;
private static readonly Interop.libcurl.curl_readwrite_callback s_sendCallback = CurlSendCallback;
private static readonly Interop.libcurl.seek_callback s_seekCallback = CurlSeekCallback;
private static readonly Interop.libcurl.curl_readwrite_callback s_receiveBodyCallback = CurlReceiveBodyCallback;
/// <summary>
/// A collection of not-yet-processed incoming requests for work to be done
/// by this multi agent. This can include making new requests, canceling
/// active requests, or unpausing active requests.
/// Protected by a lock on <see cref="_incomingRequests"/>.
/// </summary>
private readonly Queue<IncomingRequest> _incomingRequests = new Queue<IncomingRequest>();
/// <summary>Map of activeOperations, indexed by a GCHandle ptr.</summary>
private readonly Dictionary<IntPtr, ActiveRequest> _activeOperations = new Dictionary<IntPtr, ActiveRequest>();
/// <summary>
/// Lazily-initialized buffer used to transfer data from a request content stream to libcurl.
/// This buffer may be shared amongst all of the connections associated with
/// this multi agent, as long as those operations are performed synchronously on the thread
/// associated with the multi handle. Asynchronous operation must use a separate buffer.
/// </summary>
private byte[] _transferBuffer;
/// <summary>
/// Special file descriptor used to wake-up curl_multi_wait calls. This is the read
/// end of a pipe, with the write end written to when work is queued or when cancellation
/// is requested. This is only valid while the worker is executing.
/// </summary>
private int _wakeupRequestedPipeFd;
/// <summary>
/// Write end of the pipe connected to <see cref="_wakeupRequestedPipeFd"/>.
/// This is only valid while the worker is executing.
/// </summary>
private int _requestWakeupPipeFd;
/// <summary>
/// Task for the currently running worker, or null if there is no current worker.
/// Protected by a lock on <see cref="_incomingRequests"/>.
/// </summary>
private Task _runningWorker;
/// <summary>Queues a request for the multi handle to process.</summary>
public void Queue(IncomingRequest request)
{
lock (_incomingRequests)
{
// Add the request, then initiate processing.
_incomingRequests.Enqueue(request);
EnsureWorkerIsRunning();
}
}
/// <summary>Gets the ID of the currently running worker, or null if there isn't one.</summary>
internal int? RunningWorkerId { get { return _runningWorker != null ? (int?)_runningWorker.Id : null; } }
/// <summary>Schedules the processing worker if one hasn't already been scheduled.</summary>
private void EnsureWorkerIsRunning()
{
Debug.Assert(Monitor.IsEntered(_incomingRequests), "Needs to be called under _incomingRequests lock");
if (_runningWorker == null)
{
VerboseTrace("MultiAgent worker queued");
// Create pipe used to forcefully wake up curl_multi_wait calls when something important changes.
// This is created here rather than in Process so that the pipe is available immediately
// for subsequent queue calls to use.
Debug.Assert(_wakeupRequestedPipeFd == 0, "Read pipe should have been cleared");
Debug.Assert(_requestWakeupPipeFd == 0, "Write pipe should have been cleared");
unsafe
{
int* fds = stackalloc int[2];
while (Interop.CheckIo(Interop.Sys.Pipe(fds))) ;
_wakeupRequestedPipeFd = fds[Interop.Sys.ReadEndOfPipe];
_requestWakeupPipeFd = fds[Interop.Sys.WriteEndOfPipe];
}
// Kick off the processing task. It's "DenyChildAttach" to avoid any surprises if
// code happens to create attached tasks, and it's LongRunning because this thread
// is likely going to sit around for a while in a wait loop (and the more requests
// are concurrently issued to the same agent, the longer the thread will be around).
const TaskCreationOptions Options = TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning;
_runningWorker = new Task(s =>
{
VerboseTrace("MultiAgent worker starting");
var thisRef = (MultiAgent)s;
try
{
// Do the actual processing
thisRef.WorkerLoop();
}
catch (Exception exc)
{
Debug.Fail("Unexpected exception from processing loop: " + exc.ToString());
}
finally
{
VerboseTrace("MultiAgent worker shutting down");
lock (thisRef._incomingRequests)
{
// Close our wakeup pipe (ignore close errors).
// This is done while holding the lock to prevent
// subsequent Queue calls to see an improperly configured
// set of descriptors.
Interop.Sys.Close(thisRef._wakeupRequestedPipeFd);
thisRef._wakeupRequestedPipeFd = 0;
Interop.Sys.Close(thisRef._requestWakeupPipeFd);
thisRef._requestWakeupPipeFd = 0;
// In the time between we stopped processing and now,
// more requests could have been added. If they were
// kick off another processing loop.
thisRef._runningWorker = null;
if (thisRef._incomingRequests.Count > 0)
{
thisRef.EnsureWorkerIsRunning();
}
}
}
}, this, CancellationToken.None, Options);
_runningWorker.Start(TaskScheduler.Default); // started after _runningWorker field set to avoid race conditions
}
else // _workerRunning == true
{
// The worker is already running. If there are already queued requests, we're done.
// However, if there aren't any queued requests, Process could be blocked inside of
// curl_multi_wait, and we want to make sure it wakes up to see that there additional
// requests waiting to be handled. So we write to the wakeup pipe.
Debug.Assert(_incomingRequests.Count >= 1, "We just queued a request, so the count should be at least 1");
if (_incomingRequests.Count == 1)
{
RequestWakeup();
}
}
}
/// <summary>Write a byte to the wakeup pipe.</summary>
private void RequestWakeup()
{
unsafe
{
VerboseTrace("Writing to wakeup pipe");
byte b = 1;
while ((Interop.CheckIo((long)Interop.Sys.Write(_requestWakeupPipeFd, &b, 1)))) ;
}
}
/// <summary>Clears data from the wakeup pipe.</summary>
/// <remarks>
/// This must only be called when we know there's data to be read.
/// The MultiAgent could easily deadlock if it's called when there's no data in the pipe.
/// </remarks>
private unsafe void ReadFromWakeupPipeWhenKnownToContainData()
{
// It's possible but unlikely that there will be tons of extra data in the pipe,
// more than we end up reading out here (it's unlikely because we only write a byte to the pipe when
// transitioning from 0 to 1 incoming request). In that unlikely event, the worst
// case will be that the next one or more waits will wake up immediately, with each one
// subsequently clearing out more of the pipe.
const int ClearBufferSize = 64; // sufficiently large to clear the pipe in any normal case
byte* clearBuf = stackalloc byte[ClearBufferSize];
int bytesRead;
while (Interop.CheckIo(bytesRead = Interop.Sys.Read(_wakeupRequestedPipeFd, clearBuf, ClearBufferSize))) ;
VerboseTraceIf(bytesRead > 1, "Read more than one byte from wakeup pipe: " + bytesRead);
}
/// <summary>Requests that libcurl unpause the connection associated with this request.</summary>
internal void RequestUnpause(EasyRequest easy)
{
VerboseTrace(easy: easy);
Queue(new IncomingRequest { Easy = easy, Type = IncomingRequestType.Unpause });
}
private void WorkerLoop()
{
Debug.Assert(!Monitor.IsEntered(_incomingRequests), "No locks should be held while invoking Process");
Debug.Assert(_runningWorker != null && _runningWorker.Id == Task.CurrentId, "This is the worker, so it must be running");
Debug.Assert(_wakeupRequestedPipeFd != 0, "Should have a valid pipe for wake ups");
// Create the multi handle to use for this round of processing. This one handle will be used
// to service all easy requests currently available and all those that come in while
// we're processing other requests. Once the work quiesces and there are no more requests
// to process, this multi handle will be released as the worker goes away. The next
// time a request arrives and a new worker is spun up, a new multi handle will be created.
SafeCurlMultiHandle multiHandle = Interop.libcurl.curl_multi_init();
if (multiHandle.IsInvalid)
{
throw CreateHttpRequestException();
}
// Clear our active operations table. This should already be clear, either because
// all previous operations completed without unexpected exception, or in the case of an
// unexpected exception we should have cleaned up gracefully anyway. But just in case...
Debug.Assert(_activeOperations.Count == 0, "We shouldn't have any active operations when starting processing.");
_activeOperations.Clear();
bool endingSuccessfully = false;
try
{
// Continue processing as long as there are any active operations
while (true)
{
// First handle any requests in the incoming requests queue.
while (true)
{
IncomingRequest request;
lock (_incomingRequests)
{
if (_incomingRequests.Count == 0) break;
request = _incomingRequests.Dequeue();
}
HandleIncomingRequest(multiHandle, request);
}
// If we have no active operations, we're done.
if (_activeOperations.Count == 0)
{
endingSuccessfully = true;
return;
}
// We have one or more active operations. Run any work that needs to be run.
int running_handles;
ThrowIfCURLMError(Interop.libcurl.curl_multi_perform(multiHandle, out running_handles));
// Complete and remove any requests that have finished being processed.
int pendingMessages;
IntPtr messagePtr;
while ((messagePtr = Interop.libcurl.curl_multi_info_read(multiHandle, out pendingMessages)) != IntPtr.Zero)
{
Interop.libcurl.CURLMsg message = Marshal.PtrToStructure<Interop.libcurl.CURLMsg>(messagePtr);
Debug.Assert(message.msg == Interop.libcurl.CURLMSG.CURLMSG_DONE, "CURLMSG_DONE is supposed to be the only message type");
IntPtr gcHandlePtr;
ActiveRequest completedOperation;
if (message.msg == Interop.libcurl.CURLMSG.CURLMSG_DONE)
{
int getInfoResult = Interop.libcurl.curl_easy_getinfo(message.easy_handle, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr);
Debug.Assert(getInfoResult == CURLcode.CURLE_OK, "Failed to get info on a completing easy handle");
if (getInfoResult == CURLcode.CURLE_OK)
{
bool gotActiveOp = _activeOperations.TryGetValue(gcHandlePtr, out completedOperation);
Debug.Assert(gotActiveOp, "Expected to find GCHandle ptr in active operations table");
if (gotActiveOp)
{
DeactivateActiveRequest(multiHandle, completedOperation.Easy, gcHandlePtr, completedOperation.CancellationRegistration);
FinishRequest(completedOperation.Easy, message.result);
}
}
}
}
// Wait for more things to do. Even with our cancellation mechanism, we specify a timeout so that
// just in case something goes wrong we can recover gracefully. This timeout is relatively long.
// Note, though, that libcurl has its own internal timeout, which can be requested separately
// via curl_multi_timeout, but which is used implicitly by curl_multi_wait if it's shorter
// than the value we provide.
const int FailsafeTimeoutMilliseconds = 1000;
int numFds;
unsafe
{
Interop.libcurl.curl_waitfd extraFds = new Interop.libcurl.curl_waitfd {
fd = _wakeupRequestedPipeFd,
events = Interop.libcurl.CURL_WAIT_POLLIN,
revents = 0
};
ThrowIfCURLMError(Interop.libcurl.curl_multi_wait(multiHandle, &extraFds, 1, FailsafeTimeoutMilliseconds, out numFds));
if ((extraFds.revents & Interop.libcurl.CURL_WAIT_POLLIN) != 0)
{
// We woke up (at least in part) because a wake-up was requested.
// Read the data out of the pipe to clear it.
Debug.Assert(numFds >= 1, "numFds should have been at least one, as the extraFd was set");
VerboseTrace("curl_multi_wait wake-up notification");
ReadFromWakeupPipeWhenKnownToContainData();
}
VerboseTraceIf(numFds == 0, "curl_multi_wait timeout");
}
// PERF NOTE: curl_multi_wait uses poll (assuming it's available), which is O(N) in terms of the number of fds
// being waited on. If this ends up being a scalability bottleneck, we can look into using the curl_multi_socket_*
// APIs, which would let us switch to using epoll by being notified when sockets file descriptors are added or
// removed and configuring the epoll context with EPOLL_CTL_ADD/DEL, which at the expense of a lot of additional
// complexity would let us turn the O(N) operation into an O(1) operation. The additional complexity would come
// not only in the form of additional callbacks and managing the socket collection, but also in the form of timer
// management, which is necessary when using the curl_multi_socket_* APIs and which we avoid by using just
// curl_multi_wait/perform.
}
}
finally
{
// If we got an unexpected exception, something very bad happened. We may have some
// operations that we initiated but that weren't completed. Make sure to clean up any
// such operations, failing them and releasing their resources.
if (_activeOperations.Count > 0)
{
Debug.Assert(!endingSuccessfully, "We should only have remaining operations if we got an unexpected exception");
foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations)
{
ActiveRequest failingOperation = pair.Value;
IntPtr failingOperationGcHandle = pair.Key;
DeactivateActiveRequest(multiHandle, failingOperation.Easy, failingOperationGcHandle, failingOperation.CancellationRegistration);
// Complete the operation's task and clean up any of its resources
failingOperation.Easy.FailRequest(CreateHttpRequestException());
failingOperation.Easy.Cleanup(); // no active processing remains, so cleanup
}
// Clear the table.
_activeOperations.Clear();
}
// Finally, dispose of the multi handle.
multiHandle.Dispose();
}
}
private void HandleIncomingRequest(SafeCurlMultiHandle multiHandle, IncomingRequest request)
{
Debug.Assert(!Monitor.IsEntered(_incomingRequests), "Incoming requests lock should only be held while accessing the queue");
VerboseTrace("Type: " + request.Type, easy: request.Easy);
EasyRequest easy = request.Easy;
switch (request.Type)
{
case IncomingRequestType.New:
ActivateNewRequest(multiHandle, easy);
break;
case IncomingRequestType.Cancel:
Debug.Assert(easy._associatedMultiAgent == this, "Should only cancel associated easy requests");
Debug.Assert(easy._cancellationToken.IsCancellationRequested, "Cancellation should have been requested");
FindAndFailActiveRequest(multiHandle, easy, new OperationCanceledException(easy._cancellationToken));
break;
case IncomingRequestType.Unpause:
Debug.Assert(easy._associatedMultiAgent == this, "Should only unpause associated easy requests");
if (!easy._easyHandle.IsClosed)
{
IntPtr gcHandlePtr;
ActiveRequest ar;
Debug.Assert(FindActiveRequest(easy, out gcHandlePtr, out ar), "Couldn't find active request for unpause");
int unpauseResult = Interop.libcurl.curl_easy_pause(easy._easyHandle, Interop.libcurl.CURLPAUSE_CONT);
if (unpauseResult != CURLcode.CURLE_OK)
{
FindAndFailActiveRequest(multiHandle, easy, new CurlException(unpauseResult, isMulti: false));
}
}
break;
default:
Debug.Fail("Invalid request type: " + request.Type);
break;
}
}
private void ActivateNewRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy)
{
Debug.Assert(easy != null, "We should never get a null request");
Debug.Assert(easy._associatedMultiAgent == null, "New requests should not be associated with an agent yet");
// If cancellation has been requested, complete the request proactively
if (easy._cancellationToken.IsCancellationRequested)
{
easy.FailRequest(new OperationCanceledException(easy._cancellationToken));
easy.Cleanup(); // no active processing remains, so cleanup
return;
}
// Otherwise, configure it. Most of the configuration was already done when the EasyRequest
// was created, but there's additional configuration we need to do specific to this
// multi agent, specifically telling the easy request about its own GCHandle and setting
// up callbacks for data processing. Once it's configured, add it to the multi handle.
GCHandle gcHandle = GCHandle.Alloc(easy);
IntPtr gcHandlePtr = GCHandle.ToIntPtr(gcHandle);
try
{
easy._associatedMultiAgent = this;
easy.SetCurlOption(CURLoption.CURLOPT_PRIVATE, gcHandlePtr);
SetCurlCallbacks(easy, gcHandlePtr);
ThrowIfCURLMError(Interop.libcurl.curl_multi_add_handle(multiHandle, easy._easyHandle));
}
catch (Exception exc)
{
gcHandle.Free();
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so cleanup
return;
}
// And if cancellation can be requested, hook up a cancellation callback.
// This callback will put the easy request back into the queue, which will
// ensure that a wake-up request has been issued. When we pull
// the easy request out of the request queue, we'll see that it's already
// associated with this agent, meaning that it's a cancellation request,
// and we'll deal with it appropriately.
var cancellationReg = default(CancellationTokenRegistration);
if (easy._cancellationToken.CanBeCanceled)
{
cancellationReg = easy._cancellationToken.Register(s =>
{
var state = (Tuple<MultiAgent, EasyRequest>)s;
state.Item1.Queue(new IncomingRequest { Easy = state.Item2, Type = IncomingRequestType.Cancel });
}, Tuple.Create<MultiAgent, EasyRequest>(this, easy));
}
// Finally, add it to our map.
_activeOperations.Add(
gcHandlePtr,
new ActiveRequest { Easy = easy, CancellationRegistration = cancellationReg });
}
private void DeactivateActiveRequest(
SafeCurlMultiHandle multiHandle, EasyRequest easy,
IntPtr gcHandlePtr, CancellationTokenRegistration cancellationRegistration)
{
// Remove the operation from the multi handle so we can shut down the multi handle cleanly
int removeResult = Interop.libcurl.curl_multi_remove_handle(multiHandle, easy._easyHandle);
Debug.Assert(removeResult == CURLMcode.CURLM_OK, "Failed to remove easy handle"); // ignore cleanup errors in release
// Release the associated GCHandle so that it's not kept alive forever
if (gcHandlePtr != IntPtr.Zero)
{
try
{
GCHandle.FromIntPtr(gcHandlePtr).Free();
_activeOperations.Remove(gcHandlePtr);
}
catch (InvalidOperationException)
{
Debug.Fail("Couldn't get/free the GCHandle for an active operation while shutting down due to failure");
}
}
// Undo cancellation registration
cancellationRegistration.Dispose();
}
private bool FindActiveRequest(EasyRequest easy, out IntPtr gcHandlePtr, out ActiveRequest activeRequest)
{
// We maintain an IntPtr=>ActiveRequest mapping, which makes it cheap to look-up by GCHandle ptr but
// expensive to look up by EasyRequest. If we find this becoming a bottleneck, we can add a reverse
// map that stores the other direction as well.
foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations)
{
if (pair.Value.Easy == easy)
{
gcHandlePtr = pair.Key;
activeRequest = pair.Value;
return true;
}
}
gcHandlePtr = IntPtr.Zero;
activeRequest = default(ActiveRequest);
return false;
}
private void FindAndFailActiveRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy, Exception error)
{
VerboseTrace("Error: " + error.Message, easy: easy);
IntPtr gcHandlePtr;
ActiveRequest activeRequest;
if (FindActiveRequest(easy, out gcHandlePtr, out activeRequest))
{
DeactivateActiveRequest(multiHandle, easy, gcHandlePtr, activeRequest.CancellationRegistration);
easy.FailRequest(error);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
else
{
Debug.Assert(easy.Task.IsCompleted, "We should only not be able to find the request if it failed or we started to send back the response.");
}
}
private void FinishRequest(EasyRequest completedOperation, int messageResult)
{
VerboseTrace("messageResult: " + messageResult, easy: completedOperation);
if (completedOperation._responseMessage.StatusCode != HttpStatusCode.Unauthorized)
{
if (completedOperation._handler.PreAuthenticate)
{
ulong availedAuth;
if (Interop.libcurl.curl_easy_getinfo(completedOperation._easyHandle, CURLINFO.CURLINFO_HTTPAUTH_AVAIL, out availedAuth) == CURLcode.CURLE_OK)
{
// TODO: fix locking in AddCredentialToCache
completedOperation._handler.AddCredentialToCache(
completedOperation._requestMessage.RequestUri, availedAuth, completedOperation._networkCredential);
}
// Ignore errors: no need to fail for the sake of putting the credentials into the cache
}
completedOperation._handler.AddResponseCookies(
completedOperation._requestMessage.RequestUri, completedOperation._responseMessage);
}
switch (messageResult)
{
case CURLcode.CURLE_OK:
completedOperation.EnsureResponseMessagePublished();
break;
default:
completedOperation.FailRequest(CreateHttpRequestException(new CurlException(messageResult, isMulti: false)));
break;
}
// At this point, we've completed processing the entire request, either due to error
// or due to completing the entire response.
completedOperation.Cleanup();
}
private static size_t CurlReceiveHeadersCallback(IntPtr buffer, size_t size, size_t nitems, IntPtr context)
{
CurlHandler.VerboseTrace("size: " + size + ", nitems: " + nitems);
size *= nitems;
if (size == 0)
{
return 0;
}
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
try
{
// The callback is invoked once per header; multi-line headers get merged into a single line.
string responseHeader = Marshal.PtrToStringAnsi(buffer).Trim();
HttpResponseMessage response = easy._responseMessage;
if (!TryParseStatusLine(response, responseHeader, easy))
{
int colonIndex = responseHeader.IndexOf(':');
// Skip malformed header lines that are missing the colon character.
if (colonIndex > 0)
{
string headerName = responseHeader.Substring(0, colonIndex);
string headerValue = responseHeader.Substring(colonIndex + 1);
if (!response.Headers.TryAddWithoutValidation(headerName, headerValue))
{
response.Content.Headers.TryAddWithoutValidation(headerName, headerValue);
}
else if (easy._isRedirect && string.Equals(headerName, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase))
{
HandleRedirectLocationHeader(easy, headerValue);
}
}
}
return size;
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Returing a value other than size fails the callback and forces
// request completion with an error
return size - 1;
}
private static size_t CurlReceiveBodyCallback(
IntPtr buffer, size_t size, size_t nitems, IntPtr context)
{
CurlHandler.VerboseTrace("size: " + size + ", nitems: " + nitems);
size *= nitems;
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
try
{
if (!(easy.Task.IsCanceled || easy.Task.IsFaulted))
{
// Complete the task if it hasn't already been. This will make the
// stream available to consumers. A previous write callback
// may have already completed the task to publish the response.
easy.EnsureResponseMessagePublished();
// Try to transfer the data to a reader. This will return either the
// amount of data transferred (equal to the amount requested
// to be transferred), or it will return a pause request.
return easy._responseMessage.ResponseStream.TransferDataToStream(buffer, (long)size);
}
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Returing a value other than size fails the callback and forces
// request completion with an error.
CurlHandler.VerboseTrace("Error: returning a bad size to abort the request");
return (size > 0) ? size - 1 : 1;
}
private static size_t CurlSendCallback(IntPtr buffer, size_t size, size_t nitems, IntPtr context)
{
CurlHandler.VerboseTrace("size: " + size + ", nitems: " + nitems);
int length = checked((int)(size * nitems));
Debug.Assert(length <= RequestBufferSize, "length " + length + " should not be larger than RequestBufferSize " + RequestBufferSize);
if (length == 0)
{
return 0;
}
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
Debug.Assert(easy._requestContentStream != null, "We should only be in the send callback if we have a request content stream");
Debug.Assert(easy._associatedMultiAgent != null, "The request should be associated with a multi agent.");
// Transfer data from the request's content stream to libcurl
try
{
if (easy._requestContentStream is MemoryStream)
{
// If the request content stream is a memory stream (a very common case, as it's the default
// stream type used by the base HttpContent type), then we can simply perform the read synchronously
// knowing that it won't block.
return (size_t)TransferDataFromRequestMemoryStream(buffer, length, easy);
}
else
{
// Otherwise, we need to be concerned about blocking, due to this being called from the only thread able to
// service the multi agent (a multi handle can only be accessed by one thread at a time). The whole
// operation, across potentially many callbacks, will be performed asynchronously: we issue the request
// asynchronously, and if it's not completed immediately, we pause the connection until the data
// is ready to be consumed by libcurl.
return TransferDataFromRequestStream(buffer, length, easy);
}
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Something went wrong.
return Interop.libcurl.CURL_READFUNC_ABORT;
}
/// <summary>
/// Transfers up to <paramref name="length"/> data from the <paramref name="easy"/>'s
/// request content memory stream to the buffer.
/// </summary>
/// <returns>The number of bytes transferred.</returns>
private static int TransferDataFromRequestMemoryStream(IntPtr buffer, int length, EasyRequest easy)
{
Debug.Assert(easy._requestContentStream is MemoryStream, "Must only be used when the request stream is a memory stream");
Debug.Assert(easy._sendTransferState == null, "We should never have initialized the transfer state if the request stream is in memory");
MultiAgent multi = easy._associatedMultiAgent;
byte[] arr = multi._transferBuffer ?? (multi._transferBuffer = new byte[RequestBufferSize]);
int numBytes = easy._requestContentStream.Read(arr, 0, Math.Min(arr.Length, length));
Debug.Assert(numBytes >= 0 && numBytes <= length, "Read more bytes than requested");
if (numBytes > 0)
{
Marshal.Copy(arr, 0, buffer, numBytes);
}
multi.VerboseTrace("Transferred " + numBytes + " from memory stream", easy: easy);
return numBytes;
}
/// <summary>
/// Transfers up to <paramref name="length"/> data from the <paramref name="easy"/>'s
/// request content (non-memory) stream to the buffer.
/// </summary>
/// <returns>The number of bytes transferred.</returns>
private static size_t TransferDataFromRequestStream(IntPtr buffer, int length, EasyRequest easy)
{
Debug.Assert(!(easy._requestContentStream is MemoryStream), "Memory streams should use TransferFromRequestMemoryStreamToBuffer.");
MultiAgent multi = easy._associatedMultiAgent;
// First check to see whether there's any data available from a previous asynchronous read request.
// If there is, the transfer state's Task field will be non-null, with its Result representing
// the number of bytes read. The Buffer will then contain all of that read data. If the Count
// is 0, then this is the first time we're checking that Task, and so we populate the Count
// from that read result. After that, we can transfer as much data remains between Offset and
// Count. Multiple callbacks may pull from that one read.
EasyRequest.SendTransferState sts = easy._sendTransferState;
if (sts != null)
{
// Is there a previous read that may still have data to be consumed?
if (sts._task != null)
{
Debug.Assert(sts._task.IsCompleted, "The task must have completed if we're getting called back.");
// Determine how many bytes were read on the last asynchronous read.
// If nothing was read, then we're done and can simply return 0 to indicate
// the end of the stream.
int bytesRead = sts._task.GetAwaiter().GetResult(); // will throw if read failed
Debug.Assert(bytesRead >= 0 && bytesRead <= sts._buffer.Length, "ReadAsync returned an invalid result length: " + bytesRead);
if (bytesRead == 0)
{
multi.VerboseTrace("End of stream from stored task", easy: easy);
sts.SetTaskOffsetCount(null, 0, 0);
return 0;
}
// If Count is still 0, then this is the first time after the task completed
// that we're examining the data: transfer the bytesRead to the Count.
if (sts._count == 0)
{
multi.VerboseTrace("ReadAsync completed with bytes: " + bytesRead, easy: easy);
sts._count = bytesRead;
}
// Now Offset and Count are both accurate. Determine how much data we can copy to libcurl...
int availableData = sts._count - sts._offset;
Debug.Assert(availableData > 0, "There must be some data still available.");
// ... and copy as much of that as libcurl will allow.
int bytesToCopy = Math.Min(availableData, length);
Marshal.Copy(sts._buffer, sts._offset, buffer, bytesToCopy);
multi.VerboseTrace("Copied " + bytesToCopy + " bytes from request stream", easy: easy);
// Update the offset. If we've gone through all of the data, reset the state
// so that the next time we're called back we'll do a new read.
sts._offset += bytesToCopy;
Debug.Assert(sts._offset <= sts._count, "Offset should never exceed count");
if (sts._offset == sts._count)
{
sts.SetTaskOffsetCount(null, 0, 0);
}
// Return the amount of data copied
Debug.Assert(bytesToCopy > 0, "We should never return 0 bytes here.");
return (size_t)bytesToCopy;
}
// sts was non-null but sts.Task was null, meaning there was no previous task/data
// from which to satisfy any of this request.
}
else // sts == null
{
// Allocate a transfer state object to use for the remainder of this request.
easy._sendTransferState = sts = new EasyRequest.SendTransferState();
}
Debug.Assert(sts != null, "By this point we should have a transfer object");
Debug.Assert(sts._task == null, "There shouldn't be a task now.");
Debug.Assert(sts._count == 0, "Count should be zero.");
Debug.Assert(sts._offset == 0, "Offset should be zero.");
// If we get here, there was no previously read data available to copy.
// Initiate a new asynchronous read.
Task<int> asyncRead = easy._requestContentStream.ReadAsync(
sts._buffer, 0, Math.Min(sts._buffer.Length, length), easy._cancellationToken);
Debug.Assert(asyncRead != null, "Badly implemented stream returned a null task from ReadAsync");
// Even though it's "Async", it's possible this read could complete synchronously or extremely quickly.
// Check to see if it did, in which case we can also satisfy the libcurl request synchronously in this callback.
if (asyncRead.IsCompleted)
{
multi.VerboseTrace("ReadAsync completed immediately", easy: easy);
// Get the amount of data read.
int bytesRead = asyncRead.GetAwaiter().GetResult(); // will throw if read failed
if (bytesRead == 0)
{
multi.VerboseTrace("End of stream from quick returning ReadAsync", easy: easy);
return 0;
}
// Copy as much as we can.
int bytesToCopy = Math.Min(bytesRead, length);
Debug.Assert(bytesToCopy > 0 && bytesToCopy <= sts._buffer.Length, "ReadAsync quickly returned an invalid result length: " + bytesToCopy);
Marshal.Copy(sts._buffer, 0, buffer, bytesToCopy);
multi.VerboseTrace("Copied " + bytesToCopy + " from quick returning ReadAsync", easy: easy);
// If we read more than we were able to copy, stash it away for the next read.
if (bytesToCopy < bytesRead)
{
multi.VerboseTrace("Stashing away " + (bytesRead - bytesToCopy) + " bytes for next read.", easy: easy);
sts.SetTaskOffsetCount(asyncRead, bytesToCopy, bytesRead);
}
// Return the number of bytes read.
return (size_t)bytesToCopy;
}
// Otherwise, the read completed asynchronously. Store the task, and hook up a continuation
// such that the connection will be unpaused once the task completes.
sts.SetTaskOffsetCount(asyncRead, 0, 0);
asyncRead.ContinueWith((t, s) =>
{
EasyRequest easyRef = (EasyRequest)s;
easyRef._associatedMultiAgent.RequestUnpause(easyRef);
}, easy, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
// Then pause the connection.
multi.VerboseTrace("Pausing the connection", easy: easy);
return Interop.libcurl.CURL_READFUNC_PAUSE;
}
private static int CurlSeekCallback(IntPtr context, long offset, int origin)
{
CurlHandler.VerboseTrace("offset: " + offset + ", origin: " + origin);
EasyRequest easy;
if (TryGetEasyRequestFromContext(context, out easy))
{
try
{
if (easy._requestContentStream.CanSeek)
{
easy._requestContentStream.Seek(offset, (SeekOrigin)origin);
return Interop.libcurl.CURL_SEEKFUNC.CURL_SEEKFUNC_OK;
}
else
{
return Interop.libcurl.CURL_SEEKFUNC.CURL_SEEKFUNC_CANTSEEK;
}
}
catch (Exception ex)
{
easy.FailRequest(ex); // cleanup will be handled by main processing loop
}
}
// Something went wrong
return Interop.libcurl.CURL_SEEKFUNC.CURL_SEEKFUNC_FAIL;
}
private static bool TryGetEasyRequestFromContext(IntPtr context, out EasyRequest easy)
{
// Get the EasyRequest from the context
try
{
GCHandle handle = GCHandle.FromIntPtr(context);
easy = (EasyRequest)handle.Target;
Debug.Assert(easy != null, "Expected non-null EasyRequest in GCHandle");
return easy != null;
}
catch (InvalidCastException)
{
Debug.Fail("EasyRequest wasn't the GCHandle's Target");
}
catch (InvalidOperationException)
{
Debug.Fail("Invalid GCHandle");
}
easy = null;
return false;
}
private static void SetCurlCallbacks(EasyRequest easy, IntPtr easyGCHandle)
{
// Add callback for processing headers
easy.SetCurlOption(CURLoption.CURLOPT_HEADERFUNCTION, s_receiveHeadersCallback);
easy.SetCurlOption(CURLoption.CURLOPT_HEADERDATA, easyGCHandle);
// If we're sending data as part of the request, add callbacks for sending request data
if (easy._requestMessage.Content != null)
{
easy.SetCurlOption(CURLoption.CURLOPT_READFUNCTION, s_sendCallback);
easy.SetCurlOption(CURLoption.CURLOPT_READDATA, easyGCHandle);
easy.SetCurlOption(CURLoption.CURLOPT_SEEKFUNCTION, s_seekCallback);
easy.SetCurlOption(CURLoption.CURLOPT_SEEKDATA, easyGCHandle);
}
// If we're expecting any data in response, add a callback for receiving body data
if (easy._requestMessage.Method != HttpMethod.Head)
{
easy.SetCurlOption(CURLoption.CURLOPT_WRITEFUNCTION, s_receiveBodyCallback);
easy.SetCurlOption(CURLoption.CURLOPT_WRITEDATA, easyGCHandle);
}
}
[Conditional(VerboseDebuggingConditional)]
private void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null)
{
CurlHandler.VerboseTrace(text, memberName, easy, agent: this);
}
[Conditional(VerboseDebuggingConditional)]
private void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null)
{
if (condition)
{
CurlHandler.VerboseTrace(text, memberName, easy, agent: this);
}
}
/// <summary>Represents an active request currently being processed by the agent.</summary>
private struct ActiveRequest
{
public EasyRequest Easy;
public CancellationTokenRegistration CancellationRegistration;
}
/// <summary>Represents an incoming request to be processed by the agent.</summary>
internal struct IncomingRequest
{
public IncomingRequestType Type;
public EasyRequest Easy;
}
/// <summary>The type of an incoming request to be processed by the agent.</summary>
internal enum IncomingRequestType : byte
{
/// <summary>A new request that's never been submitted to an agent.</summary>
New,
/// <summary>A request to cancel a request previously submitted to the agent.</summary>
Cancel,
/// <summary>A request to unpause the connection associated with a request previously submitted to the agent.</summary>
Unpause
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
//using System.Text.RegularExpressions;
namespace angeldnd.dap {
[System.AttributeUsage(System.AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class DapTypeByName: System.Attribute {
}
[System.AttributeUsage(System.AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class DapTypeByFullName: System.Attribute {
}
[System.AttributeUsage(System.AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class DapType: System.Attribute {
public static string GetDapType(Type type) {
object[] attribs = type._GetCustomAttributes(false);
foreach (var attr in attribs) {
if (attr is DapTypeByName) {
return type.Name;
}
if (attr is DapTypeByFullName) {
return type.FullName;
}
if (attr is DapType) {
return ((DapType)attr).Type;
}
}
return null;
}
public readonly string Type;
public DapType(string type) {
Type = type;
}
}
[System.AttributeUsage(System.AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class DapVarType: DapType {
public static Type GetDapVarType(Type type) {
object[] attribs = type._GetCustomAttributes(false);
foreach (var attr in attribs) {
if (attr is DapVarType) {
return ((DapVarType)attr).VarType;
}
}
return null;
}
public readonly Type VarType;
public DapVarType(string type, Type varType) : base(type) {
VarType = varType;
}
}
[System.AttributeUsage(System.AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class DapPriority: System.Attribute {
public static int GetPriority(Type type) {
object[] attribs = type._GetCustomAttributes(false);
foreach (var attr in attribs) {
if (attr is DapPriority) {
return ((DapPriority)attr).Priority;
}
}
return 0;
}
public readonly int Priority;
public DapPriority(int priority) {
Priority = priority;
}
}
[System.AttributeUsage(System.AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class DapOrder: System.Attribute {
public static int GetOrder(Type type) {
object[] attribs = type._GetCustomAttributes(false);
foreach (var attr in attribs) {
if (attr is DapOrder) {
return ((DapOrder)attr).Order;
}
}
return 0;
}
public static void SortByOrder<T>(List<T> objs) {
Dictionary<T, int> orders = new Dictionary<T, int>();
foreach (T obj in objs) {
orders[obj] = GetOrder(obj.GetType());
}
objs.Sort((T a, T b) => {
int orderA = orders[a];
int orderB = orders[b];
if (orderA == orderB) {
return a.GetType().FullName.CompareTo(b.GetType().FullName);
} else {
return orderA.CompareTo(orderB);
}
});
}
public readonly int Order;
public DapOrder(int order) {
Order = order;
}
}
[System.AttributeUsage(System.AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class DapParam : System.Attribute {
public const string DefaultSuffix = "_Default";
public static string GetDefaultFieldName(string fieldName) {
return string.Format("{0}{1}", fieldName, DefaultSuffix);
}
public static DapParam GetDapParam(FieldInfo field) {
object[] attribs = field._GetCustomAttributes(false);
foreach (var attr in attribs) {
if (attr is DapParam) {
return (DapParam)attr;
}
}
return null;
}
public readonly System.Type ParamType;
public readonly bool Optional;
public DapParam(System.Type t, bool optional) {
ParamType = t;
Optional = optional;
}
public DapParam(System.Type t) : this(t, false) {}
}
public static class DataDapParamExtension {
private static FieldInfo GetFieldInfo(Type type, string fieldName) {
FieldInfo field = type.GetField(fieldName,
BindingFlags.Public | BindingFlags.Static);
if (field == null) {
Log.Error("public static field not found: {0}.{1}", type.FullName, fieldName);
}
return field;
}
private static bool GetParamHint(Type type, string fieldName, ref string key, ref string hint) {
FieldInfo field = type.GetField(fieldName,
BindingFlags.Public | BindingFlags.Static);
if (field == null) {
return false;
}
DapParam dapParam = DapParam.GetDapParam(field);
if (dapParam == null) {
Log.Error("DapParam attribute not found: {0}.{1}", type.FullName, fieldName);
return false;
}
key = field.GetValue(null).ToString();
hint = string.Format("{0}", dapParam.ParamType.FullName);
if (dapParam.Optional) {
FieldInfo defaultField = type.GetField(DapParam.GetDefaultFieldName(fieldName),
BindingFlags.Public | BindingFlags.Static);
if (defaultField == null) {
hint = string.Format("{0} = N/A", hint);
} else {
hint = string.Format("{0} = {1}", hint, defaultField.GetValue(null));
}
}
return true;
}
public static Data AddParamHint(this Data data, Type type, string fieldName) {
string key = null, hint = null;
if (GetParamHint(type, fieldName, ref key, ref hint)) {
data.SetString(key, hint);
}
return data;
}
public static Data AddOneOfParamHint(this Data data, Type type, params string[] fieldNames) {
string key = "";
string hint = "";
foreach (string fieldName in fieldNames) {
string oneKey = null, oneHint = null;
if (GetParamHint(type, fieldName, ref oneKey, ref oneHint)) {
if (!string.IsNullOrEmpty(key)) {
key += " | ";
hint += ", ";
}
key += oneKey;
hint += oneHint;
}
}
if (!string.IsNullOrEmpty(key)) {
data.SetString(key, hint);
}
return data;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Google.ProtocolBuffers;
using grpc.testing;
using Grpc.Auth;
using Grpc.Core;
using Grpc.Core.Utils;
using NUnit.Framework;
using Google.Apis.Auth.OAuth2;
namespace Grpc.IntegrationTesting
{
public class InteropClient
{
private const string ServiceAccountUser = "155450119199-3psnrh1sdr3d8cpj1v46naggf81mhdnk@developer.gserviceaccount.com";
private const string ComputeEngineUser = "155450119199-r5aaqa2vqoa9g5mv2m6s3m1l293rlmel@developer.gserviceaccount.com";
private const string AuthScope = "https://www.googleapis.com/auth/xapi.zoo";
private const string AuthScopeResponse = "xapi.zoo";
private class ClientOptions
{
public bool help;
public string serverHost = "127.0.0.1";
public string serverHostOverride = TestCredentials.DefaultHostOverride;
public int? serverPort;
public string testCase = "large_unary";
public bool useTls;
public bool useTestCa;
}
ClientOptions options;
private InteropClient(ClientOptions options)
{
this.options = options;
}
public static void Run(string[] args)
{
Console.WriteLine("gRPC C# interop testing client");
ClientOptions options = ParseArguments(args);
if (options.serverHost == null || !options.serverPort.HasValue || options.testCase == null)
{
Console.WriteLine("Missing required argument.");
Console.WriteLine();
options.help = true;
}
if (options.help)
{
Console.WriteLine("Usage:");
Console.WriteLine(" --server_host=HOSTNAME");
Console.WriteLine(" --server_host_override=HOSTNAME");
Console.WriteLine(" --server_port=PORT");
Console.WriteLine(" --test_case=TESTCASE");
Console.WriteLine(" --use_tls=BOOLEAN");
Console.WriteLine(" --use_test_ca=BOOLEAN");
Console.WriteLine();
Environment.Exit(1);
}
var interopClient = new InteropClient(options);
interopClient.Run().Wait();
}
private async Task Run()
{
Credentials credentials = null;
if (options.useTls)
{
credentials = TestCredentials.CreateTestClientCredentials(options.useTestCa);
}
List<ChannelOption> channelOptions = null;
if (!string.IsNullOrEmpty(options.serverHostOverride))
{
channelOptions = new List<ChannelOption>
{
new ChannelOption(ChannelOptions.SslTargetNameOverride, options.serverHostOverride)
};
}
using (Channel channel = new Channel(options.serverHost, options.serverPort.Value, credentials, channelOptions))
{
TestService.TestServiceClient client = new TestService.TestServiceClient(channel);
await RunTestCaseAsync(options.testCase, client);
}
GrpcEnvironment.Shutdown();
}
private async Task RunTestCaseAsync(string testCase, TestService.TestServiceClient client)
{
switch (testCase)
{
case "empty_unary":
RunEmptyUnary(client);
break;
case "large_unary":
RunLargeUnary(client);
break;
case "client_streaming":
await RunClientStreamingAsync(client);
break;
case "server_streaming":
await RunServerStreamingAsync(client);
break;
case "ping_pong":
await RunPingPongAsync(client);
break;
case "empty_stream":
await RunEmptyStreamAsync(client);
break;
case "service_account_creds":
await RunServiceAccountCredsAsync(client);
break;
case "compute_engine_creds":
await RunComputeEngineCredsAsync(client);
break;
case "jwt_token_creds":
await RunJwtTokenCredsAsync(client);
break;
case "oauth2_auth_token":
await RunOAuth2AuthTokenAsync(client);
break;
case "per_rpc_creds":
await RunPerRpcCredsAsync(client);
break;
case "cancel_after_begin":
await RunCancelAfterBeginAsync(client);
break;
case "cancel_after_first_response":
await RunCancelAfterFirstResponseAsync(client);
break;
case "benchmark_empty_unary":
RunBenchmarkEmptyUnary(client);
break;
default:
throw new ArgumentException("Unknown test case " + testCase);
}
}
public static void RunEmptyUnary(TestService.ITestServiceClient client)
{
Console.WriteLine("running empty_unary");
var response = client.EmptyCall(Empty.DefaultInstance);
Assert.IsNotNull(response);
Console.WriteLine("Passed!");
}
public static void RunLargeUnary(TestService.ITestServiceClient client)
{
Console.WriteLine("running large_unary");
var request = SimpleRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.SetResponseSize(314159)
.SetPayload(CreateZerosPayload(271828))
.Build();
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Console.WriteLine("Passed!");
}
public static async Task RunClientStreamingAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running client_streaming");
var bodySizes = new List<int> { 27182, 8, 1828, 45904 }.ConvertAll((size) => StreamingInputCallRequest.CreateBuilder().SetPayload(CreateZerosPayload(size)).Build());
using (var call = client.StreamingInputCall())
{
await call.RequestStream.WriteAllAsync(bodySizes);
var response = await call.ResponseAsync;
Assert.AreEqual(74922, response.AggregatedPayloadSize);
}
Console.WriteLine("Passed!");
}
public static async Task RunServerStreamingAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running server_streaming");
var bodySizes = new List<int> { 31415, 9, 2653, 58979 };
var request = StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddRangeResponseParameters(bodySizes.ConvertAll(
(size) => ResponseParameters.CreateBuilder().SetSize(size).Build()))
.Build();
using (var call = client.StreamingOutputCall(request))
{
var responseList = await call.ResponseStream.ToListAsync();
foreach (var res in responseList)
{
Assert.AreEqual(PayloadType.COMPRESSABLE, res.Payload.Type);
}
CollectionAssert.AreEqual(bodySizes, responseList.ConvertAll((item) => item.Payload.Body.Length));
}
Console.WriteLine("Passed!");
}
public static async Task RunPingPongAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running ping_pong");
using (var call = client.FullDuplexCall())
{
await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(31415))
.SetPayload(CreateZerosPayload(27182)).Build());
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(9))
.SetPayload(CreateZerosPayload(8)).Build());
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(9, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(2653))
.SetPayload(CreateZerosPayload(1828)).Build());
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(2653, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(58979))
.SetPayload(CreateZerosPayload(45904)).Build());
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(58979, call.ResponseStream.Current.Payload.Body.Length);
await call.RequestStream.CompleteAsync();
Assert.IsFalse(await call.ResponseStream.MoveNext());
}
Console.WriteLine("Passed!");
}
public static async Task RunEmptyStreamAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running empty_stream");
using (var call = client.FullDuplexCall())
{
await call.RequestStream.CompleteAsync();
var responseList = await call.ResponseStream.ToListAsync();
Assert.AreEqual(0, responseList.Count);
}
Console.WriteLine("Passed!");
}
public static async Task RunServiceAccountCredsAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running service_account_creds");
var credential = await GoogleCredential.GetApplicationDefaultAsync();
credential = credential.CreateScoped(new[] { AuthScope });
client.HeaderInterceptor = OAuth2Interceptors.FromCredential(credential);
var request = SimpleRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.SetResponseSize(314159)
.SetPayload(CreateZerosPayload(271828))
.SetFillUsername(true)
.SetFillOauthScope(true)
.Build();
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Assert.AreEqual(AuthScopeResponse, response.OauthScope);
Assert.AreEqual(ServiceAccountUser, response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunComputeEngineCredsAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running compute_engine_creds");
var credential = await GoogleCredential.GetApplicationDefaultAsync();
Assert.IsFalse(credential.IsCreateScopedRequired);
client.HeaderInterceptor = OAuth2Interceptors.FromCredential(credential);
var request = SimpleRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.SetResponseSize(314159)
.SetPayload(CreateZerosPayload(271828))
.SetFillUsername(true)
.SetFillOauthScope(true)
.Build();
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Assert.AreEqual(AuthScopeResponse, response.OauthScope);
Assert.AreEqual(ComputeEngineUser, response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunJwtTokenCredsAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running jwt_token_creds");
var credential = await GoogleCredential.GetApplicationDefaultAsync();
// check this a credential with scope support, but don't add the scope.
Assert.IsTrue(credential.IsCreateScopedRequired);
client.HeaderInterceptor = OAuth2Interceptors.FromCredential(credential);
var request = SimpleRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.SetResponseSize(314159)
.SetPayload(CreateZerosPayload(271828))
.SetFillUsername(true)
.SetFillOauthScope(true)
.Build();
var response = client.UnaryCall(request);
Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type);
Assert.AreEqual(314159, response.Payload.Body.Length);
Assert.AreEqual(ServiceAccountUser, response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running oauth2_auth_token");
ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { AuthScope });
string oauth2Token = await credential.GetAccessTokenForRequestAsync();
client.HeaderInterceptor = OAuth2Interceptors.FromAccessToken(oauth2Token);
var request = SimpleRequest.CreateBuilder()
.SetFillUsername(true)
.SetFillOauthScope(true)
.Build();
var response = client.UnaryCall(request);
Assert.AreEqual(AuthScopeResponse, response.OauthScope);
Assert.AreEqual(ServiceAccountUser, response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client)
{
Console.WriteLine("running per_rpc_creds");
ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { AuthScope });
string oauth2Token = await credential.GetAccessTokenForRequestAsync();
var headerInterceptor = OAuth2Interceptors.FromAccessToken(oauth2Token);
var request = SimpleRequest.CreateBuilder()
.SetFillUsername(true)
.SetFillOauthScope(true)
.Build();
var headers = new Metadata();
headerInterceptor("", headers);
var response = client.UnaryCall(request, headers: headers);
Assert.AreEqual(AuthScopeResponse, response.OauthScope);
Assert.AreEqual(ServiceAccountUser, response.Username);
Console.WriteLine("Passed!");
}
public static async Task RunCancelAfterBeginAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running cancel_after_begin");
var cts = new CancellationTokenSource();
using (var call = client.StreamingInputCall(cancellationToken: cts.Token))
{
// TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it.
await Task.Delay(1000);
cts.Cancel();
var ex = Assert.Throws<RpcException>(async () => await call.ResponseAsync);
Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode);
}
Console.WriteLine("Passed!");
}
public static async Task RunCancelAfterFirstResponseAsync(TestService.ITestServiceClient client)
{
Console.WriteLine("running cancel_after_first_response");
var cts = new CancellationTokenSource();
using (var call = client.FullDuplexCall(cancellationToken: cts.Token))
{
await call.RequestStream.WriteAsync(StreamingOutputCallRequest.CreateBuilder()
.SetResponseType(PayloadType.COMPRESSABLE)
.AddResponseParameters(ResponseParameters.CreateBuilder().SetSize(31415))
.SetPayload(CreateZerosPayload(27182)).Build());
Assert.IsTrue(await call.ResponseStream.MoveNext());
Assert.AreEqual(PayloadType.COMPRESSABLE, call.ResponseStream.Current.Payload.Type);
Assert.AreEqual(31415, call.ResponseStream.Current.Payload.Body.Length);
cts.Cancel();
var ex = Assert.Throws<RpcException>(async () => await call.ResponseStream.MoveNext());
Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode);
}
Console.WriteLine("Passed!");
}
// This is not an official interop test, but it's useful.
public static void RunBenchmarkEmptyUnary(TestService.ITestServiceClient client)
{
BenchmarkUtil.RunBenchmark(10000, 10000,
() => { client.EmptyCall(Empty.DefaultInstance); });
}
private static Payload CreateZerosPayload(int size)
{
return Payload.CreateBuilder().SetBody(ByteString.CopyFrom(new byte[size])).Build();
}
private static ClientOptions ParseArguments(string[] args)
{
var options = new ClientOptions();
foreach (string arg in args)
{
ParseArgument(arg, options);
if (options.help)
{
break;
}
}
return options;
}
private static void ParseArgument(string arg, ClientOptions options)
{
Match match;
match = Regex.Match(arg, "--server_host=(.*)");
if (match.Success)
{
options.serverHost = match.Groups[1].Value.Trim();
return;
}
match = Regex.Match(arg, "--server_host_override=(.*)");
if (match.Success)
{
options.serverHostOverride = match.Groups[1].Value.Trim();
return;
}
match = Regex.Match(arg, "--server_port=(.*)");
if (match.Success)
{
options.serverPort = int.Parse(match.Groups[1].Value.Trim());
return;
}
match = Regex.Match(arg, "--test_case=(.*)");
if (match.Success)
{
options.testCase = match.Groups[1].Value.Trim();
return;
}
match = Regex.Match(arg, "--use_tls=(.*)");
if (match.Success)
{
options.useTls = bool.Parse(match.Groups[1].Value.Trim());
return;
}
match = Regex.Match(arg, "--use_test_ca=(.*)");
if (match.Success)
{
options.useTestCa = bool.Parse(match.Groups[1].Value.Trim());
return;
}
Console.WriteLine(string.Format("Unrecognized argument \"{0}\"", arg));
options.help = true;
}
}
}
| |
// This file is part of SNMP#NET.
//
// SNMP#NET is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SNMP#NET is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SNMP#NET. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SnmpSharpNet
{
/// <summary>
/// Async delegate called on completion of Async SNMP request
/// </summary>
/// <param name="status">SNMP request status. If status is NoError then pdu will contain valid information</param>
/// <param name="peer">Peer IP and port number. This value is only valid if status is NoError</param>
/// <param name="buffer">Returned data. This value is only valid if status is NoError</param>
/// <param name="length">Length of the returned data. This value is only valid if status is NoError.</param>
internal delegate void SnmpAsyncCallback(AsyncRequestResult status, IPEndPoint peer, byte[] buffer, int length);
/// <summary>
/// IP/UDP transport class.
/// </summary>
public class UdpTransport: IDisposable
{
/// <summary>
/// Socket
/// </summary>
protected Socket _socket;
/// <summary>
/// Flag showing if class is using IPv6 or IPv4
/// </summary>
protected bool _isIPv6;
/// <summary>
/// Internal variable used to disable host IP address/port number check on received SNMP reply packets. If this option is disabled (default)
/// only replies from the IP address/port number combination to which the request was sent will be accepted as valid packets.
///
/// This value is set in the AgentParameters class and is only valid for SNMP v1 and v2c requests.
/// </summary>
protected bool _noSourceCheck;
/// <summary>
/// Constructor. Initializes and binds the Socket class
/// </summary>
/// <param name="useV6">Set to true if you wish to initialize the transport for IPv6</param>
public UdpTransport(bool useV6)
{
_isIPv6 = useV6;
_socket = null;
initSocket(_isIPv6);
}
/// <summary>
/// Destructor
/// </summary>
~UdpTransport()
{
if (_socket != null)
{
_socket.Close();
_socket = null;
}
}
/// <summary>
/// Flag used to determine if class is using IP version 6 (true) or IP version 4 (false)
/// </summary>
public bool IsIPv6
{
get { return _isIPv6; }
}
/// <summary>
/// Initialize class socket
/// </summary>
/// <param name="useV6">Should socket be initialized for IPv6 (true) of IPv4 (false)</param>
protected void initSocket(bool useV6)
{
if (_socket != null)
{
Close();
}
if (useV6)
{
_socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
}
else
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
IPEndPoint ipEndPoint = new IPEndPoint(_socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
EndPoint ep = (EndPoint)ipEndPoint;
_socket.Bind(ep);
}
/// <summary>
/// Make sync request using IP/UDP with request timeouts and retries.
/// </summary>
/// <param name="peer">SNMP agent IP address</param>
/// <param name="port">SNMP agent port number</param>
/// <param name="buffer">Data to send to the agent</param>
/// <param name="bufferLength">Data length in the buffer</param>
/// <param name="timeout">Timeout in milliseconds</param>
/// <param name="retries">Maximum number of retries. 0 = make a single request with no retry attempts</param>
/// <returns>Byte array returned by the agent. Null on error</returns>
/// <exception cref="SnmpException">Thrown on request timed out. SnmpException.ErrorCode is set to
/// SnmpException.RequestTimedOut constant.</exception>
/// <exception cref="SnmpException">Thrown when IPv4 address is passed to the v6 socket or vice versa</exception>
public byte[] Request(IPAddress peer, int port, byte[] buffer, int bufferLength, int timeout, int retries)
{
if (_socket == null)
{
return null; // socket has been closed. no new operations are possible.
}
if (_socket.AddressFamily != peer.AddressFamily)
throw new SnmpException("Invalid address protocol version.");
IPEndPoint netPeer = new IPEndPoint(peer, port);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout);
int recv = 0;
int retry = 0;
byte[] inbuffer = new byte[64 * 1024];
EndPoint remote = (EndPoint)new IPEndPoint(peer.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any,0);
while (true)
{
try
{
_socket.SendTo(buffer, bufferLength, SocketFlags.None, (EndPoint)netPeer);
recv = _socket.ReceiveFrom(inbuffer, ref remote);
}
catch (SocketException ex)
{
if (ex.ErrorCode == 10040)
{
recv = 0; // Packet too large
}
else if (ex.ErrorCode == 10050)
{
throw new SnmpNetworkException(ex, "Network error: Destination network is down.");
}
else if (ex.ErrorCode == 10051)
{
throw new SnmpNetworkException(ex, "Network error: destination network is unreachable.");
}
else if( ex.ErrorCode == 10054)
{
throw new SnmpNetworkException(ex, "Network error: connection reset by peer.");
}
else if (ex.ErrorCode == 10064)
{
throw new SnmpNetworkException(ex, "Network error: remote host is down.");
}
else if (ex.ErrorCode == 10065)
{
throw new SnmpNetworkException(ex, "Network error: remote host is unreachable.");
}
else if (ex.ErrorCode == 10061)
{
throw new SnmpNetworkException(ex, "Network error: connection refused.");
}
else if (ex.ErrorCode == 10060)
{
recv = 0; // Connection attempt timed out. Fall through to retry
}
else
{
// Assume it is a timeout
}
}
if (recv > 0)
{
IPEndPoint remEP = remote as IPEndPoint;
if ( ! _noSourceCheck && ! remEP.Equals(netPeer))
{
if (remEP.Address != netPeer.Address)
{
Console.WriteLine("Address miss-match {0} != {1}", remEP.Address, netPeer.Address);
}
if (remEP.Port != netPeer.Port)
{
Console.WriteLine("Port # miss-match {0} != {1}", remEP.Port, netPeer.Port);
}
/* Not good, we got a response from somebody other then who we requested a response from */
retry++;
if (retry > retries)
{
throw new SnmpException(SnmpException.RequestTimedOut, "Request has reached maximum retries.");
// return null;
}
}
else
{
MutableByte buf = new MutableByte(inbuffer, recv);
return buf;
}
}
else
{
retry++;
if (retry > retries)
{
throw new SnmpException(SnmpException.RequestTimedOut, "Request has reached maximum retries.");
}
}
}
}
/// <summary>
/// SNMP request internal callback
/// </summary>
internal event SnmpAsyncCallback _asyncCallback;
/// <summary>
/// Internal flag used to mark the class busy or available. Any request made when this
/// flag is set to true will fail with OperationInProgress error.
/// </summary>
internal bool _busy;
/// <summary>
/// Is class busy. This property is true when class is servicing another request, false if
/// ready to process a new request.
/// </summary>
public bool IsBusy
{
get { return _busy; }
}
/// <summary>
/// Async request state information.
/// </summary>
internal AsyncRequestState _requestState;
/// <summary>
/// Incoming data buffer
/// </summary>
internal byte[] _inBuffer;
/// <summary>
/// Receiver IP end point
/// </summary>
internal IPEndPoint _receivePeer;
/// <summary>
/// Begin an async SNMP request
/// </summary>
/// <param name="peer">Pdu to send to the agent</param>
/// <param name="port">Callback to receive response from the agent</param>
/// <param name="buffer">Buffer containing data to send to the peer</param>
/// <param name="bufferLength">Length of data in the buffer</param>
/// <param name="timeout">Request timeout in milliseconds</param>
/// <param name="retries">Maximum retry count. 0 = single request no further retries.</param>
/// <param name="asyncCallback">Callback that will receive the status and result of the operation</param>
/// <returns>Returns false if another request is already in progress or if socket used by the class
/// has been closed using Dispose() member, otherwise true</returns>
/// <exception cref="SnmpException">Thrown when IPv4 address is passed to the v6 socket or vice versa</exception>
internal bool RequestAsync(IPAddress peer, int port, byte[] buffer, int bufferLength, int timeout, int retries, SnmpAsyncCallback asyncCallback)
{
if (_busy == true)
{
return false;
}
if (_socket == null)
{
return false; // socket has been closed. no new operations are possible.
}
if (_socket.AddressFamily != peer.AddressFamily)
throw new SnmpException("Invalid address protocol version.");
_busy = true;
_asyncCallback = null;
_asyncCallback += asyncCallback;
_requestState = new AsyncRequestState(peer, port, retries, timeout);
_requestState.Packet = buffer;
_requestState.PacketLength = bufferLength;
// _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _requestState.Timeout);
_inBuffer = new byte[64 * 1024]; // create incoming data buffer
SendToBegin(); // Send the request
return true;
}
/// <summary>
/// Calls async version of the SendTo socket function.
/// </summary>
internal void SendToBegin()
{
if (_requestState == null)
{
_busy = false;
return;
}
// kill the timeout timer - there shouldn't be one active when we are sending a new request
if (_requestState.Timer != null)
{
_requestState.Timer.Dispose();
_requestState.Timer = null;
}
if (_socket == null)
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.Terminated, new IPEndPoint(IPAddress.Any, 0), null, 0);
return; // socket has been closed. no new operations are possible.
}
try
{
_socket.BeginSendTo(_requestState.Packet, 0, _requestState.PacketLength, SocketFlags.None, _requestState.EndPoint, new AsyncCallback(SendToCallback), null);
}
catch
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.SocketSendError, new IPEndPoint(_socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0), null, 0);
}
}
/// <summary>
/// Callback member called on completion of BeginSendTo send data operation.
/// </summary>
/// <param name="ar">Async result</param>
internal void SendToCallback(IAsyncResult ar)
{
if (_socket == null || ! _busy || _requestState == null)
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.Terminated, new IPEndPoint(IPAddress.Any, 0), null, 0);
return; // socket has been closed. no new operations are possible.
}
int sentLength = 0;
try
{
sentLength = _socket.EndSendTo(ar);
}
catch (NullReferenceException ex)
{
ex.GetType();
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.Terminated, new IPEndPoint(_socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0), null, 0);
return;
}
catch
{
sentLength = 0;
}
if (sentLength != _requestState.PacketLength)
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.SocketSendError, new IPEndPoint(_socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0), null, 0);
return;
}
// Start receive timer
ReceiveBegin(); // Initialize a receive call
}
/// <summary>
/// Begin async version of ReceiveFrom member of the socket class.
/// </summary>
internal void ReceiveBegin()
{
// kill the timeout timer
if(_requestState.Timer != null)
{
_requestState.Timer.Dispose();
_requestState.Timer = null;
}
if (_socket == null || !_busy || _requestState == null)
{
_busy = false;
_requestState = null;
if( _socket != null )
_asyncCallback(AsyncRequestResult.Terminated, new IPEndPoint(_socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0), null, 0);
else
_asyncCallback(AsyncRequestResult.Terminated, new IPEndPoint(IPAddress.Any, 0), null, 0);
return;
// socket has been closed. no new operations are possible.
}
_receivePeer = new IPEndPoint(_socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
EndPoint ep = (EndPoint)_receivePeer;
try
{
_socket.BeginReceiveFrom(_inBuffer, 0, _inBuffer.Length, SocketFlags.None, ref ep, new AsyncCallback(ReceiveFromCallback), null);
}
catch
{
// retry on every error. this can be done better by evaluating the returned
// error value but it's a lot of work and for a non-acked protocol, just send it again
// until you reach max retries.
RetryAsyncRequest();
return;
}
_requestState.Timer = new Timer(new TimerCallback(AsyncRequestTimerCallback), null, _requestState.Timeout, System.Threading.Timeout.Infinite);
}
/// <summary>
/// Internal retry function. Checks if request has reached maximum number of retries and either resends the request if not reached,
/// or sends request timed-out notification to the caller if maximum retry count has been reached and request has failed.
/// </summary>
internal void RetryAsyncRequest()
{
// kill the timer if one is active
if (_requestState.Timer != null)
{
_requestState.Timer.Dispose();
_requestState.Timer = null;
}
if (_socket == null || !_busy || _requestState == null)
{
_busy = false;
_requestState = null;
if( _socket != null )
_asyncCallback(AsyncRequestResult.Terminated, new IPEndPoint(_socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0), null, 0);
else
_asyncCallback(AsyncRequestResult.Terminated, new IPEndPoint(IPAddress.Any, 0), null, 0);
return; // socket has been closed. no new operations are possible.
}
// We increment the retry counter before retry count. Initial CurrentRetry value is set to -1 so that
// MaxRetries value can be 0 (first request is not counted as a retry).
_requestState.CurrentRetry += 1;
if (_requestState.CurrentRetry >= _requestState.MaxRetries)
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.Timeout, new IPEndPoint(_socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0), null, 0);
return;
}
else
{
SendToBegin();
}
}
/// <summary>
/// Internal callback called as part of Socket.BeginReceiveFrom. Process incoming packets and notify caller
/// of results.
/// </summary>
/// <param name="ar">Async call result used by <seealso cref="Socket.EndReceiveFrom"/></param>
internal void ReceiveFromCallback(IAsyncResult ar)
{
// kill the timer if one is active
if (_requestState.Timer != null)
{
_requestState.Timer.Dispose();
_requestState.Timer = null;
}
if (_socket == null || !_busy || _requestState == null)
{
_busy = false;
_requestState = null;
if( _socket == null )
_asyncCallback(AsyncRequestResult.Terminated, new IPEndPoint(_socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0), null, 0);
else
_asyncCallback(AsyncRequestResult.Terminated, new IPEndPoint(IPAddress.Any, 0), null, 0);
return; // socket has been closed. no new operations are possible.
}
int inlen = 0;
EndPoint ep = (EndPoint)_receivePeer;
try
{
inlen = _socket.EndReceiveFrom(ar, ref ep);
}
catch (SocketException ex)
{
if (ex.ErrorCode == 10040)
{
inlen = 0; // Packet too large
}
else if (ex.ErrorCode == 10050)
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.SocketReceiveError, null, null, -1);
return;
}
else if (ex.ErrorCode == 10051)
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.SocketReceiveError, null, null, -1);
return;
}
else if (ex.ErrorCode == 10054)
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.SocketReceiveError, null, null, -1);
return;
}
else if (ex.ErrorCode == 10064)
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.SocketReceiveError, null, null, -1);
return;
}
else if (ex.ErrorCode == 10065)
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.SocketReceiveError, null, null, -1);
return;
}
else if (ex.ErrorCode == 10061)
{
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.SocketReceiveError, null, null, -1);
return;
}
else if (ex.ErrorCode == 10060)
{
inlen = 0; // Connection attempt timed out. Fall through to retry
}
else
{
// Assume it is a timeout
}
}
catch (ObjectDisposedException ex)
{
ex.GetType(); // this is to avoid the compilation warning
_asyncCallback(AsyncRequestResult.Terminated, null, null, -1);
return;
}
catch (NullReferenceException ex)
{
ex.GetType(); // this is to avoid the compilation warning
_asyncCallback(AsyncRequestResult.Terminated, null, null, -1);
return;
}
catch (Exception ex)
{
ex.GetType();
// we don't care what exception happened. We only want to know if we should retry the request
inlen = 0;
}
if (inlen == 0 )
{
RetryAsyncRequest();
}
else
{
// make a copy of the data from the internal buffer
byte[] buf = new byte[inlen];
Buffer.BlockCopy(_inBuffer, 0, buf, 0, inlen);
_busy = false;
_requestState = null;
_asyncCallback(AsyncRequestResult.NoError, _receivePeer, buf, buf.Length);
}
}
/// <summary>
/// Internal timer callback. Called by _asyncTimer when SNMP request timeout has expired
/// </summary>
/// <param name="stateInfo">State info. Always null</param>
internal void AsyncRequestTimerCallback(object stateInfo)
{
if (_socket != null || _requestState != null && _busy)
{
// Call retry function
RetryAsyncRequest();
}
}
/// <summary>
/// Dispose of the class.
/// </summary>
public void Dispose()
{
Close();
}
/// <summary>
/// Close network socket
/// </summary>
public void Close()
{
if( _socket != null )
{
try
{
_socket.Close();
}
catch
{
}
_socket = null;
}
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Digests
{
/**
* Base class for SHA-384 and SHA-512.
*/
public abstract class LongDigest
: IDigest, IMemoable
{
private int MyByteLength = 128;
private byte[] xBuf;
private int xBufOff;
private long byteCount1;
private long byteCount2;
internal ulong H1, H2, H3, H4, H5, H6, H7, H8;
private ulong[] W = new ulong[80];
private int wOff;
/**
* Constructor for variable length word
*/
internal LongDigest()
{
xBuf = new byte[8];
Reset();
}
/**
* Copy constructor. We are using copy constructors in place
* of the object.Clone() interface as this interface is not
* supported by J2ME.
*/
internal LongDigest(
LongDigest t)
{
xBuf = new byte[t.xBuf.Length];
CopyIn(t);
}
protected void CopyIn(LongDigest t)
{
Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length);
xBufOff = t.xBufOff;
byteCount1 = t.byteCount1;
byteCount2 = t.byteCount2;
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
H6 = t.H6;
H7 = t.H7;
H8 = t.H8;
Array.Copy(t.W, 0, W, 0, t.W.Length);
wOff = t.wOff;
}
public void Update(
byte input)
{
xBuf[xBufOff++] = input;
if (xBufOff == xBuf.Length)
{
ProcessWord(xBuf, 0);
xBufOff = 0;
}
byteCount1++;
}
public void BlockUpdate(
byte[] input,
int inOff,
int length)
{
//
// fill the current word
//
while ((xBufOff != 0) && (length > 0))
{
Update(input[inOff]);
inOff++;
length--;
}
//
// process whole words.
//
while (length > xBuf.Length)
{
ProcessWord(input, inOff);
inOff += xBuf.Length;
length -= xBuf.Length;
byteCount1 += xBuf.Length;
}
//
// load in the remainder.
//
while (length > 0)
{
Update(input[inOff]);
inOff++;
length--;
}
}
public void Finish()
{
AdjustByteCounts();
long lowBitLength = byteCount1 << 3;
long hiBitLength = byteCount2;
//
// add the pad bytes.
//
Update((byte)128);
while (xBufOff != 0)
{
Update((byte)0);
}
ProcessLength(lowBitLength, hiBitLength);
ProcessBlock();
}
public virtual void Reset()
{
byteCount1 = 0;
byteCount2 = 0;
xBufOff = 0;
for ( int i = 0; i < xBuf.Length; i++ )
{
xBuf[i] = 0;
}
wOff = 0;
Array.Clear(W, 0, W.Length);
}
internal void ProcessWord(
byte[] input,
int inOff)
{
W[wOff] = Pack.BE_To_UInt64(input, inOff);
if (++wOff == 16)
{
ProcessBlock();
}
}
/**
* adjust the byte counts so that byteCount2 represents the
* upper long (less 3 bits) word of the byte count.
*/
private void AdjustByteCounts()
{
if (byteCount1 > 0x1fffffffffffffffL)
{
byteCount2 += (long) ((ulong) byteCount1 >> 61);
byteCount1 &= 0x1fffffffffffffffL;
}
}
internal void ProcessLength(
long lowW,
long hiW)
{
if (wOff > 14)
{
ProcessBlock();
}
W[14] = (ulong)hiW;
W[15] = (ulong)lowW;
}
internal void ProcessBlock()
{
AdjustByteCounts();
//
// expand 16 word block into 80 word blocks.
//
for (int ti = 16; ti <= 79; ++ti)
{
W[ti] = Sigma1(W[ti - 2]) + W[ti - 7] + Sigma0(W[ti - 15]) + W[ti - 16];
}
//
// set up working variables.
//
ulong a = H1;
ulong b = H2;
ulong c = H3;
ulong d = H4;
ulong e = H5;
ulong f = H6;
ulong g = H7;
ulong h = H8;
int t = 0;
for(int i = 0; i < 10; i ++)
{
// t = 8 * i
h += Sum1(e) + Ch(e, f, g) + K[t] + W[t++];
d += h;
h += Sum0(a) + Maj(a, b, c);
// t = 8 * i + 1
g += Sum1(d) + Ch(d, e, f) + K[t] + W[t++];
c += g;
g += Sum0(h) + Maj(h, a, b);
// t = 8 * i + 2
f += Sum1(c) + Ch(c, d, e) + K[t] + W[t++];
b += f;
f += Sum0(g) + Maj(g, h, a);
// t = 8 * i + 3
e += Sum1(b) + Ch(b, c, d) + K[t] + W[t++];
a += e;
e += Sum0(f) + Maj(f, g, h);
// t = 8 * i + 4
d += Sum1(a) + Ch(a, b, c) + K[t] + W[t++];
h += d;
d += Sum0(e) + Maj(e, f, g);
// t = 8 * i + 5
c += Sum1(h) + Ch(h, a, b) + K[t] + W[t++];
g += c;
c += Sum0(d) + Maj(d, e, f);
// t = 8 * i + 6
b += Sum1(g) + Ch(g, h, a) + K[t] + W[t++];
f += b;
b += Sum0(c) + Maj(c, d, e);
// t = 8 * i + 7
a += Sum1(f) + Ch(f, g, h) + K[t] + W[t++];
e += a;
a += Sum0(b) + Maj(b, c, d);
}
H1 += a;
H2 += b;
H3 += c;
H4 += d;
H5 += e;
H6 += f;
H7 += g;
H8 += h;
//
// reset the offset and clean out the word buffer.
//
wOff = 0;
Array.Clear(W, 0, 16);
}
/* SHA-384 and SHA-512 functions (as for SHA-256 but for longs) */
private static ulong Ch(ulong x, ulong y, ulong z)
{
return (x & y) ^ (~x & z);
}
private static ulong Maj(ulong x, ulong y, ulong z)
{
return (x & y) ^ (x & z) ^ (y & z);
}
private static ulong Sum0(ulong x)
{
return ((x << 36) | (x >> 28)) ^ ((x << 30) | (x >> 34)) ^ ((x << 25) | (x >> 39));
}
private static ulong Sum1(ulong x)
{
return ((x << 50) | (x >> 14)) ^ ((x << 46) | (x >> 18)) ^ ((x << 23) | (x >> 41));
}
private static ulong Sigma0(ulong x)
{
return ((x << 63) | (x >> 1)) ^ ((x << 56) | (x >> 8)) ^ (x >> 7);
}
private static ulong Sigma1(ulong x)
{
return ((x << 45) | (x >> 19)) ^ ((x << 3) | (x >> 61)) ^ (x >> 6);
}
/* SHA-384 and SHA-512 Constants
* (represent the first 64 bits of the fractional parts of the
* cube roots of the first sixty-four prime numbers)
*/
internal static readonly ulong[] K =
{
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817
};
public int GetByteLength()
{
return MyByteLength;
}
public abstract string AlgorithmName { get; }
public abstract int GetDigestSize();
public abstract int DoFinal(byte[] output, int outOff);
public abstract IMemoable Copy();
public abstract void Reset(IMemoable t);
}
}
#endif
| |
/**
* _____ _____ _____ _____ __ _____ _____ _____ _____
* | __| | | | | | | | | __| | |
* |__ | | | | | | | | | |__| | | | |- -| --|
* |_____|_____|_|_|_|_____| |_____|_____|_____|_____|_____|
*
* UNICORNS AT WARP SPEED SINCE 2010
*
* 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 SumoLogic.Logging.Serilog.Extensions
{
using System;
using System.Globalization;
using System.Net.Http;
using global::Serilog;
using global::Serilog.Configuration;
using global::Serilog.Core;
using global::Serilog.Events;
using global::Serilog.Formatting;
using global::Serilog.Formatting.Display;
using SumoLogic.Logging.Serilog.Config;
/// <summary>
/// Extension methods of <see cref="LoggerConfiguration"/>.
/// </summary>
public static class LoggerSinkConfigurationExtensions
{
/// <summary>
/// The default output template.
/// </summary>
private const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message} {Exception}";
/// <summary>
/// Adds the <c>WriteTo.BufferedSumoLogic()</c> extension method to <see cref="LoggerConfiguration"/>.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="endpointUrl">SumoLogic endpoint URL.</param>
/// <param name="outputTemplate">
/// A message template describing the format used to write to the sink.
/// Default output template is <see cref="DefaultOutputTemplate"/>, set only if <paramref name="formatter"/> is kept <c>null</c>.
/// </param>
/// <param name="sourceName">The name used for messages sent to SumoLogic server.</param>
/// <param name="sourceCategory">The source category for messages sent to SumoLogic server.</param>
/// <param name="sourceHost">The source host for messages sent to SumoLogic Server.</param>
/// <param name="clientName">The client name value that is included in each request (used for telemetry).</param>
/// <param name="connectionTimeout">The connection timeout, in milliseconds.</param>
/// <param name="retryInterval">The send message retry interval, in milliseconds.</param>
/// <param name="maxFlushInterval">The maximum interval between flushes, in milliseconds.</param>
/// <param name="flushingAccuracy">How often the messages queue is checked for messages to send, in milliseconds.</param>
/// <param name="messagesPerRequest">How many messages need to be in the queue before flushing.</param>
/// <param name="maxQueueSizeBytes">
/// The messages queue capacity, in bytes. Messages are dropped When the queue capacity is exceeded.
/// </param>
/// <param name="httpMessageHandler">Override HTTP message handler which manages requests to SumoLogic.</param>
/// <param name="formatter">
/// Controls the rendering of log events into text, for example to log JSON.
/// To control plain text formatting supply method with <paramref name="outputTemplate"/> and keep this <c>null</c>.
/// </param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level to be changed at runtime.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <returns>
/// Configuration object allowing method chaining.
/// </returns>
public static LoggerConfiguration BufferedSumoLogic(
this LoggerSinkConfiguration sinkConfiguration,
Uri endpointUrl,
string outputTemplate = null,
string sourceName = "Serilog-SumoObject",
string sourceCategory = null,
string sourceHost = null,
string clientName = null,
long? connectionTimeout = null,
long? retryInterval = null,
long? maxFlushInterval = null,
long? flushingAccuracy = null,
long messagesPerRequest = 100,
long maxQueueSizeBytes = 1_000_000,
HttpMessageHandler httpMessageHandler = null,
ITextFormatter formatter = null,
LoggingLevelSwitch levelSwitch = null,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
{
if (endpointUrl is null)
{
throw new ArgumentNullException(nameof(endpointUrl));
}
var sink = new BufferedSumoLogicSink(
null,
httpMessageHandler,
CreateConnection(
endpointUrl,
clientName,
connectionTimeout,
retryInterval,
maxFlushInterval,
flushingAccuracy,
messagesPerRequest,
maxQueueSizeBytes),
CreateSource(sourceName, sourceCategory, sourceHost),
formatter ?? CreateTextFormatter(outputTemplate));
return sinkConfiguration.Sink(sink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>
/// Adds the <c>WriteTo.SumoLogic()</c> extension method to <see cref="LoggerConfiguration"/>.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="endpointUrl">SumoLogic endpoint URL.</param>
/// <param name="outputTemplate">
/// A message template describing the format used to write to the sink.
/// Default output template is <see cref="DefaultOutputTemplate"/>, set only if <paramref name="formatter"/> is kept <c>null</c>.
/// </param>
/// <param name="sourceName">The name used for messages sent to SumoLogic server.</param>
/// <param name="sourceCategory">The source category for messages sent to SumoLogic server.</param>
/// <param name="sourceHost">The source host for messages sent to SumoLogic Server.</param>
/// <param name="clientName">The client name value that is included in each request (used for telemetry).</param>
/// <param name="connectionTimeout">The connection timeout, in milliseconds.</param>
/// <param name="httpMessageHandler">Override HTTP message handler which manages requests to SumoLogic.</param>
/// <param name="formatter">
/// Controls the rendering of log events into text, for example to log JSON.
/// To control plain text formatting supply method with <paramref name="outputTemplate"/> and keep this <c>null</c>.
/// </param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level to be changed at runtime.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <returns>
/// Configuration object allowing method chaining.
/// </returns>
public static LoggerConfiguration SumoLogic(
this LoggerSinkConfiguration sinkConfiguration,
Uri endpointUrl,
string outputTemplate = null,
string sourceName = "Serilog-SumoObject",
string sourceCategory = null,
string sourceHost = null,
string clientName = null,
long? connectionTimeout = null,
HttpMessageHandler httpMessageHandler = null,
ITextFormatter formatter = null,
LoggingLevelSwitch levelSwitch = null,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
{
if (endpointUrl is null)
{
throw new ArgumentNullException(nameof(endpointUrl));
}
var sink = new SumoLogicSink(
null,
httpMessageHandler,
CreateConnection(
endpointUrl,
clientName,
connectionTimeout),
CreateSource(sourceName, sourceCategory, sourceHost),
formatter ?? CreateTextFormatter(outputTemplate));
return sinkConfiguration.Sink(sink, restrictedToMinimumLevel, levelSwitch);
}
/// <summary>
/// Creates SumoLogic connection describer.
/// </summary>
/// <returns>
/// SumoLogic connection describer.
/// </returns>
private static SumoLogicConnection CreateConnection(
Uri endpointUrl,
string clientName = null,
long? connectionTimeout = null,
long? retryInterval = null,
long? maxFlushInterval = null,
long? flushAccuracy = null,
long messagesPerRequest = 100,
long maxQueueSizeBytes = 1_000_000)
{
var connection = new SumoLogicConnection
{
Uri = endpointUrl,
ClientName = clientName,
MessagesPerRequest = messagesPerRequest,
MaxQueueSizeBytes = maxQueueSizeBytes,
};
connection = connection.SetTimeSpanIfNotEmpty(c => c.ConnectionTimeout, connectionTimeout)
.SetTimeSpanIfNotEmpty(c => c.RetryInterval, retryInterval)
.SetTimeSpanIfNotEmpty(c => c.MaxFlushInterval, maxFlushInterval)
.SetTimeSpanIfNotEmpty(c => c.FlushingAccuracy, flushAccuracy);
return connection;
}
/// <summary>
/// Creates SumoLogic source describer.
/// </summary>
/// <returns>
/// SumoLogic source describer.
/// </returns>
private static SumoLogicSource CreateSource(
string sourceName = null,
string sourceCategory = null,
string sourceHost = null) =>
new SumoLogicSource
{
SourceName = sourceName,
SourceCategory = sourceCategory,
SourceHost = sourceHost,
};
/// <summary>
/// Creates text formatter for supplied output template.
/// </summary>
/// <param name="outputTemplate">Event log output template.</param>
/// <returns>
/// Text formatter for provided output template.
/// </returns>
private static ITextFormatter CreateTextFormatter(string outputTemplate)
{
outputTemplate = string.IsNullOrWhiteSpace(outputTemplate)
? DefaultOutputTemplate
: outputTemplate;
return new MessageTemplateTextFormatter(outputTemplate, CultureInfo.InvariantCulture);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.