context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Security.Principal;
using Xunit;
namespace System.Security.AccessControl.Tests
{
public partial class SystemAcl_SetAudit
{
public static IEnumerable<object[]> SystemAcl_SetAudit_TestData()
{
yield return new object[] { true, false, 2, "BA", 2, 3, 3, "64:2:1:BA:false:0", "143:2:2:BA:false:0" };
yield return new object[] { true, false, 2, "BO", 2, 3, 3, "64:2:1:BA:false:0#64:2:1:BG:false:0#64:2:1:BO:false:0", "64:2:1:BA:false:0#64:2:1:BG:false:0#143:2:2:BO:false:0" };
yield return new object[] { true, false, 2, "BG", 2, 3, 3, "64:2:1:BA:false:0#64:2:1:BG:false:0#64:2:1:BO:false:0", "64:2:1:BA:false:0#143:2:2:BG:false:0#64:2:1:BO:false:0 " };
yield return new object[] { true, false, 2, "BA", 2, 3, 3, "64:2:1:BA:false:0#128:2:2:BA:false:0#64:2:1:BA:false:0", "143:2:2:BA:false:0" };
yield return new object[] { true, false, 2, "BO", 2, 3, 3, "64:2:1:BA:false:0", "64:2:1:BA:false:0#143:2:2:BO:false:0 " };
yield return new object[] { true, false, 1, "BA", 1, 0, 0, "80:2:1:BA:false:0", "64:2:1:BA:false:0#80:2:1:BA:false:0 " };
yield return new object[] { true, false, 2, "BA", 2, 3, 3, "143:2:2:BA:false:0", "143:2:2:BA:false:0" };
}
[Theory]
[MemberData(nameof(SystemAcl_SetAudit_TestData))]
public static void BasicValidationTestCases(bool isContainer, bool isDS, int auditFlags, string sid, int accessMask, int inheritanceFlags, int propagationFlags, string initialRawAclStr, string verifierRawAclStr)
{
RawAcl rawAcl = null;
SystemAcl systemAcl = null;
//create a systemAcl
rawAcl = Utils.CreateRawAclFromString(initialRawAclStr);
systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
rawAcl = Utils.CreateRawAclFromString(verifierRawAclStr);
Assert.True(TestSetAudit(systemAcl, rawAcl, (AuditFlags)auditFlags,
new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags));
}
private static bool TestSetAudit(SystemAcl systemAcl, RawAcl rawAcl, AuditFlags auditFlag, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
{
bool result = true;
byte[] sAclBinaryForm = null;
byte[] rAclBinaryForm = null;
systemAcl.SetAudit(auditFlag, sid, accessMask, inheritanceFlags, propagationFlags);
if (systemAcl.Count == rawAcl.Count &&
systemAcl.BinaryLength == rawAcl.BinaryLength)
{
sAclBinaryForm = new byte[systemAcl.BinaryLength];
rAclBinaryForm = new byte[rawAcl.BinaryLength];
systemAcl.GetBinaryForm(sAclBinaryForm, 0);
rawAcl.GetBinaryForm(rAclBinaryForm, 0);
if (!Utils.IsBinaryFormEqual(sAclBinaryForm, rAclBinaryForm))
result = false;
//redundant index check
for (int i = 0; i < systemAcl.Count; i++)
{
if (!Utils.IsAceEqual(systemAcl[i], rawAcl[i]))
{
result = false;
break;
}
}
}
else
result = false;
return result;
}
[Fact]
public static void AdditionalTestCases()
{
RawAcl rawAcl = null;
SystemAcl systemAcl = null;
bool isContainer = false;
bool isDS = false;
int auditFlags = 0;
string sid = null;
int accessMask = 1;
int inheritanceFlags = 0;
int propagationFlags = 0;
GenericAce gAce = null;
byte[] opaque = null;
//Case 1, null sid
Assert.Throws<ArgumentNullException>(() =>
{
isContainer = false;
isDS = false;
rawAcl = new RawAcl(0, 1);
systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
systemAcl.SetAudit(AuditFlags.Success, null, 1, InheritanceFlags.None, PropagationFlags.None);
});
//Case 2, SystemAudit Ace but non AuditFlags
AssertExtensions.Throws<ArgumentException>("auditFlags", () =>
{
isContainer = false;
isDS = false;
rawAcl = new RawAcl(0, 1);
systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
systemAcl.SetAudit(AuditFlags.None,
new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BA")), 1, InheritanceFlags.None, PropagationFlags.None);
});
//Case 3, 0 accessMask
AssertExtensions.Throws<ArgumentException>("accessMask", () =>
{
isContainer = false;
isDS = false;
rawAcl = new RawAcl(0, 1);
systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
systemAcl.SetAudit(AuditFlags.Success,
new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BA")), 0, InheritanceFlags.None, PropagationFlags.None);
});
//Case 4, non-Container, but InheritanceFlags is not None
AssertExtensions.Throws<ArgumentException>("inheritanceFlags", () =>
{
isContainer = false;
isDS = false;
rawAcl = new RawAcl(0, 1);
systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
systemAcl.SetAudit(AuditFlags.Success,
new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BA")), 1, InheritanceFlags.ContainerInherit, PropagationFlags.None);
});
//Case 5, non-Container, but PropagationFlags is not None
AssertExtensions.Throws<ArgumentException>("propagationFlags", () =>
{
isContainer = false;
isDS = false;
rawAcl = new RawAcl(0, 1);
systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
systemAcl.SetAudit(AuditFlags.Success,
new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BA")), 1, InheritanceFlags.None, PropagationFlags.InheritOnly);
});
//Case 6, set one audit ACE to the SystemAcl with no ACE
isContainer = true;
isDS = false;
auditFlags = 1;
sid = "BA";
accessMask = 1;
inheritanceFlags = 3;
propagationFlags = 3;
rawAcl = new RawAcl(0, 1);
systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
//79 = AceFlags.SuccessfulAccess | AceFlags.ObjectInherit |AceFlags.ContainerInherit | AceFlags.NoPropagateInherit | AceFlags.InheritOnly
gAce = new CommonAce((AceFlags)79, AceQualifier.SystemAudit, accessMask,
new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null);
rawAcl.InsertAce(rawAcl.Count, gAce);
Assert.True(TestSetAudit(systemAcl, rawAcl, (AuditFlags)auditFlags,
new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags));
//Case 7, all the ACEs in the Sacl are non-qualified ACE, no merge
Assert.Throws<InvalidOperationException>(() =>
{
isContainer = true;
isDS = false;
inheritanceFlags = 1;//InheritanceFlags.ContainerInherit
propagationFlags = 2; //PropagationFlags.InheritOnly
auditFlags = 3;
sid = "BA";
accessMask = 1;
rawAcl = new RawAcl(0, 1);
opaque = new byte[4];
gAce = new CustomAce(AceType.MaxDefinedAceType + 1, AceFlags.InheritanceFlags | AceFlags.AuditFlags, opaque); ;
rawAcl.InsertAce(0, gAce);
systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
gAce = new CommonAce(AceFlags.ContainerInherit | AceFlags.InheritOnly | AceFlags.AuditFlags,
AceQualifier.SystemAudit,
accessMask,
new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)),
false,
null);
rawAcl.InsertAce(0, gAce);
//After Mark changes design to make ACL with any CustomAce, CompoundAce uncanonical and
//forbid the modification on uncanonical ACL, this case will throw InvalidOperationException
TestSetAudit(systemAcl, rawAcl, (AuditFlags)auditFlags,
new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags);
});
//Case 8, Set Ace to exceed binary length boundary, throw exception
Assert.Throws<InvalidOperationException>(() =>
{
isContainer = true;
isDS = false;
inheritanceFlags = 1;//InheritanceFlags.ContainerInherit
propagationFlags = 2; //PropagationFlags.InheritOnly
auditFlags = 3;
sid = "BA";
accessMask = 1;
rawAcl = new RawAcl(0, 1);
opaque = new byte[GenericAcl.MaxBinaryLength + 1 - 8 - 4 - 16];
gAce = new CustomAce(AceType.MaxDefinedAceType + 1,
AceFlags.InheritanceFlags | AceFlags.AuditFlags, opaque); ;
rawAcl.InsertAce(0, gAce);
systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
//After Mark changes design to make ACL with any CustomAce, CompoundAce uncanonical and
//forbid the modification on uncanonical ACL, this case will throw InvalidOperationException
systemAcl.SetAudit((AuditFlags)auditFlags,
new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags);
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Specialized.Tests
{
public static class BitVector32Tests
{
/// <summary>
/// Data used for testing setting/unsetting multiple bits at a time.
/// </summary>
/// Format is:
/// 1. Set data
/// 2. Unset data
/// 3. Bits to flip for transformation.
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Mask_SetUnset_Multiple_Data()
{
yield return new object[] { 0, 0, new int[] { } };
yield return new object[] { 1, 0, new int[] { 1 } };
yield return new object[] { 2, 0, new int[] { 2 } };
yield return new object[] { int.MinValue, 0, new int[] { 32 } };
yield return new object[] { 6, 0, new int[] { 2, 3 } };
yield return new object[] { 6, 6, new int[] { 2, 3 } };
yield return new object[] { 31, 15, new int[] { 4 } };
yield return new object[] { 22, 16, new int[] { 2, 3 } };
yield return new object[] { -1, 0, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 } };
}
/// <summary>
/// Data used for testing creating sections.
/// </summary>
/// Format is:
/// 1. maximum value allowed
/// 2. resulting mask
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Section_Create_Data()
{
yield return new object[] { 1, 1 };
yield return new object[] { 2, 3 };
yield return new object[] { 3, 3 };
yield return new object[] { 16, 31 };
yield return new object[] { byte.MaxValue, byte.MaxValue };
yield return new object[] { short.MaxValue, short.MaxValue };
yield return new object[] { short.MaxValue - 1, short.MaxValue };
}
/// <summary>
/// Data used for testing setting/unsetting via sections.
/// </summary>
/// Format is:
/// 1. value
/// 2. section
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Section_Set_Data()
{
yield return new object[] { 0, BitVector32.CreateSection(1) };
yield return new object[] { 1, BitVector32.CreateSection(1) };
yield return new object[] { 0, BitVector32.CreateSection(short.MaxValue) };
yield return new object[] { short.MaxValue, BitVector32.CreateSection(short.MaxValue) };
yield return new object[] { 0, BitVector32.CreateSection(1, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { 1, BitVector32.CreateSection(1, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { 0, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { short.MaxValue, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { 16, BitVector32.CreateSection(short.MaxValue) };
yield return new object[] { 16, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { 31, BitVector32.CreateSection(short.MaxValue) };
yield return new object[] { 31, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { 16, BitVector32.CreateSection(byte.MaxValue) };
yield return new object[] { 16, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(short.MaxValue))) };
yield return new object[] { 31, BitVector32.CreateSection(byte.MaxValue) };
yield return new object[] { 31, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(short.MaxValue))) };
}
/// <summary>
/// Data used for testing equal sections.
/// </summary>
/// Format is:
/// 1. Section left
/// 2. Section right
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Section_Equal_Data()
{
BitVector32.Section original = BitVector32.CreateSection(16);
BitVector32.Section nested = BitVector32.CreateSection(16, original);
yield return new object[] { original, original };
yield return new object[] { original, BitVector32.CreateSection(16) };
yield return new object[] { BitVector32.CreateSection(16), original };
// Since the max value is changed to an inclusive mask, equal to mask max value
yield return new object[] { original, BitVector32.CreateSection(31) };
yield return new object[] { nested, nested };
yield return new object[] { nested, BitVector32.CreateSection(16, original) };
yield return new object[] { BitVector32.CreateSection(16, original), nested };
yield return new object[] { nested, BitVector32.CreateSection(31, original) };
yield return new object[] { nested, BitVector32.CreateSection(16, BitVector32.CreateSection(16)) };
yield return new object[] { BitVector32.CreateSection(16, BitVector32.CreateSection(16)), nested };
yield return new object[] { nested, BitVector32.CreateSection(31, BitVector32.CreateSection(16)) };
// Because it only stores the offset, and not the previous section, later sections may be equal
yield return new object[] { nested, BitVector32.CreateSection(16, BitVector32.CreateSection(8, BitVector32.CreateSection(1))) };
yield return new object[] { BitVector32.CreateSection(16, BitVector32.CreateSection(8, BitVector32.CreateSection(1))), nested };
}
/// <summary>
/// Data used for testing unequal sections.
/// </summary>
/// Format is:
/// 1. Section left
/// 2. Section right
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Section_Unequal_Data()
{
BitVector32.Section original = BitVector32.CreateSection(16);
BitVector32.Section nested = BitVector32.CreateSection(16, original);
yield return new object[] { original, BitVector32.CreateSection(1) };
yield return new object[] { BitVector32.CreateSection(1), original };
yield return new object[] { original, nested };
yield return new object[] { nested, original };
yield return new object[] { nested, BitVector32.CreateSection(1, BitVector32.CreateSection(short.MaxValue)) };
yield return new object[] { BitVector32.CreateSection(1, BitVector32.CreateSection(short.MaxValue)), nested };
yield return new object[] { nested, BitVector32.CreateSection(16, BitVector32.CreateSection(short.MaxValue)) };
yield return new object[] { BitVector32.CreateSection(16, BitVector32.CreateSection(short.MaxValue)), nested };
yield return new object[] { nested, BitVector32.CreateSection(1, original) };
yield return new object[] { BitVector32.CreateSection(1, original), nested };
}
[Fact]
public static void Constructor_DefaultTest()
{
BitVector32 bv = new BitVector32();
Assert.NotNull(bv);
Assert.Equal(0, bv.Data);
// Copy constructor results in item with same data.
BitVector32 copied = new BitVector32(bv);
Assert.NotNull(bv);
Assert.Equal(0, copied.Data);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(7)]
[InlineData(99)]
[InlineData(byte.MaxValue)]
[InlineData(int.MaxValue / 2)]
[InlineData(int.MaxValue - 1)]
[InlineData(int.MaxValue)]
[InlineData(-1)]
[InlineData(-2)]
[InlineData(-7)]
[InlineData(-99)]
[InlineData(byte.MinValue)]
[InlineData(int.MinValue / 2)]
[InlineData(int.MinValue + 1)]
[InlineData(int.MinValue)]
public static void Constructor_DataTest(int data)
{
BitVector32 bv = new BitVector32(data);
Assert.NotNull(bv);
Assert.Equal(data, bv.Data);
// Copy constructor results in item with same data.
BitVector32 copied = new BitVector32(bv);
Assert.NotNull(bv);
Assert.Equal(data, copied.Data);
}
[Fact]
public static void Mask_DefaultTest()
{
Assert.Equal(1, BitVector32.CreateMask());
Assert.Equal(1, BitVector32.CreateMask(0));
}
[Theory]
[InlineData(2, 1)]
[InlineData(6, 3)]
[InlineData(short.MaxValue + 1, 1 << 14)]
[InlineData(-2, int.MaxValue)]
[InlineData(-2, -1)]
// Works even if the mask has multiple bits set, which probably wasn't the intended use.
public static void Mask_SeriesTest(int expected, int actual)
{
while (actual != int.MinValue)
{
actual = BitVector32.CreateMask(actual);
Assert.Equal(expected, actual);
expected <<= 1;
}
Assert.Equal(int.MinValue, actual);
}
[Fact]
public static void Mask_LastTest()
{
Assert.Throws<InvalidOperationException>(() => BitVector32.CreateMask(int.MinValue));
}
[Fact]
public static void Get_Mask_AllSetTest()
{
BitVector32 all = new BitVector32(-1);
int mask = 0;
for (int count = 0; count < 32; count++)
{
mask = BitVector32.CreateMask(mask);
Assert.True(all[mask]);
}
Assert.Equal(int.MinValue, mask);
}
[Fact]
public static void Get_Mask_NoneSetTest()
{
BitVector32 none = new BitVector32();
int mask = 0;
for (int count = 0; count < 32; count++)
{
mask = BitVector32.CreateMask(mask);
Assert.False(none[mask]);
}
Assert.Equal(int.MinValue, mask);
}
[Fact]
public static void Get_Mask_SomeSetTest()
{
// Constructs data with every even bit set.
int data = Enumerable.Range(0, 16).Sum(x => 1 << (x * 2));
BitVector32 some = new BitVector32(data);
int mask = 0;
for (int index = 0; index < 32; index++)
{
mask = BitVector32.CreateMask(mask);
Assert.Equal(index % 2 == 0, some[mask]);
}
Assert.Equal(int.MinValue, mask);
}
[Fact]
public static void Set_Mask_EmptyTest()
{
BitVector32 nothing = new BitVector32();
nothing[0] = true;
Assert.Equal(0, nothing.Data);
BitVector32 all = new BitVector32(-1);
all[0] = false;
Assert.Equal(-1, all.Data);
}
[Fact]
public static void Set_Mask_AllTest()
{
BitVector32 flip = new BitVector32();
int mask = 0;
for (int bit = 1; bit < 32 + 1; bit++)
{
mask = BitVector32.CreateMask(mask);
BitVector32 single = new BitVector32();
Assert.False(single[mask]);
single[mask] = true;
Assert.True(single[mask]);
Assert.Equal(1 << (bit - 1), single.Data);
flip[mask] = true;
}
Assert.Equal(-1, flip.Data);
Assert.Equal(int.MinValue, mask);
}
[Fact]
public static void Set_Mask_UnsetAllTest()
{
BitVector32 flip = new BitVector32(-1);
int mask = 0;
for (int bit = 1; bit < 32 + 1; bit++)
{
mask = BitVector32.CreateMask(mask);
BitVector32 single = new BitVector32(1 << (bit - 1));
Assert.True(single[mask]);
single[mask] = false;
Assert.False(single[mask]);
Assert.Equal(0, single.Data);
flip[mask] = false;
}
Assert.Equal(0, flip.Data);
Assert.Equal(int.MinValue, mask);
}
[Theory]
[MemberData(nameof(Mask_SetUnset_Multiple_Data))]
public static void Set_Mask_MultipleTest(int expected, int start, int[] maskPositions)
{
int mask = maskPositions.Sum(x => 1 << (x - 1));
BitVector32 blank = new BitVector32();
BitVector32 set = new BitVector32();
set[mask] = true;
for (int bit = 0; bit < 32; bit++)
{
Assert.False(blank[1 << bit]);
bool willSet = maskPositions.Contains(bit + 1);
blank[1 << bit] = willSet;
Assert.Equal(willSet, blank[1 << bit]);
Assert.Equal(willSet, set[1 << bit]);
}
Assert.Equal(set, blank);
}
[Theory]
[MemberData(nameof(Mask_SetUnset_Multiple_Data))]
public static void Set_Mask_Multiple_UnsetTest(int start, int expected, int[] maskPositions)
{
int mask = maskPositions.Sum(x => 1 << (x - 1));
BitVector32 set = new BitVector32();
set[mask] = true;
for (int bit = 0; bit < 32; bit++)
{
bool willUnset = maskPositions.Contains(bit + 1);
Assert.Equal(willUnset, set[1 << bit]);
set[1 << bit] = false;
Assert.False(set[1 << bit]);
}
Assert.Equal(set, new BitVector32());
}
[Theory]
[MemberData(nameof(Section_Set_Data))]
public static void Set_SectionTest(int value, BitVector32.Section section)
{
BitVector32 empty = new BitVector32();
empty[section] = value;
Assert.Equal(value, empty[section]);
Assert.Equal(value << section.Offset, empty.Data);
BitVector32 full = new BitVector32(-1);
full[section] = value;
Assert.Equal(value, full[section]);
int offsetMask = section.Mask << section.Offset;
Assert.Equal((-1 & ~offsetMask) | (value << section.Offset), full.Data);
}
[Theory]
[InlineData(short.MaxValue, int.MaxValue)]
[InlineData(1, 2)]
[InlineData(1, short.MaxValue)]
[InlineData(1, -1)]
[InlineData(short.MaxValue, short.MinValue)]
public static void Set_Section_OutOfRangeTest(short maximum, int value)
{
{
BitVector32 data = new BitVector32();
BitVector32.Section section = BitVector32.CreateSection(maximum);
data[section] = value;
Assert.Equal(maximum & value, data.Data);
Assert.NotEqual(value, data.Data);
Assert.Equal(maximum & value, data[section]);
Assert.NotEqual(value, data[section]);
}
{
BitVector32 data = new BitVector32();
BitVector32.Section nested = BitVector32.CreateSection(maximum, BitVector32.CreateSection(short.MaxValue));
data[nested] = value;
Assert.Equal((maximum & value) << 15, data.Data);
Assert.NotEqual(value << 15, data.Data);
Assert.Equal(maximum & value, data[nested]);
Assert.NotEqual(value, data[nested]);
}
}
[Theory]
[InlineData(4)]
[InlineData(5)]
[InlineData(short.MaxValue)]
[InlineData(byte.MaxValue)]
// Regardless of mask size, values will be truncated if they hang off the end
public static void Set_Section_OverflowTest(int value)
{
BitVector32 data = new BitVector32();
BitVector32.Section offset = BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(short.MaxValue));
BitVector32.Section final = BitVector32.CreateSection(short.MaxValue, offset);
data[final] = value;
Assert.Equal((3 & value) << 30, data.Data);
Assert.NotEqual(value, data.Data);
Assert.Equal(3 & value, data[final]);
Assert.NotEqual(value, data[final]);
}
[Theory]
[MemberData(nameof(Section_Create_Data))]
public static void CreateSectionTest(short maximum, short mask)
{
BitVector32.Section section = BitVector32.CreateSection(maximum);
Assert.Equal(0, section.Offset);
Assert.Equal(mask, section.Mask);
}
[Theory]
[MemberData(nameof(Section_Create_Data))]
public static void CreateSection_NextTest(short maximum, short mask)
{
BitVector32.Section initial = BitVector32.CreateSection(short.MaxValue);
BitVector32.Section section = BitVector32.CreateSection(maximum, initial);
Assert.Equal(15, section.Offset);
Assert.Equal(mask, section.Mask);
}
[Theory]
[InlineData(short.MinValue)]
[InlineData(-1)]
[InlineData(0)]
public static void CreateSection_InvalidMaximumTest(short maxvalue)
{
AssertExtensions.Throws<ArgumentException>("maxValue", () => BitVector32.CreateSection(maxvalue));
BitVector32.Section valid = BitVector32.CreateSection(1);
AssertExtensions.Throws<ArgumentException>("maxValue", () => BitVector32.CreateSection(maxvalue, valid));
}
[Theory]
[InlineData(7, short.MaxValue)]
[InlineData(short.MaxValue, 7)]
[InlineData(short.MaxValue, short.MaxValue)]
[InlineData(byte.MaxValue, byte.MaxValue)]
public static void CreateSection_FullTest(short prior, short invalid)
{
// BV32 can hold just over 2 shorts, so fill most of the way first....
BitVector32.Section initial = BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(short.MaxValue));
BitVector32.Section overflow = BitVector32.CreateSection(prior, initial);
// Final masked value can hang off the end
Assert.Equal(prior, overflow.Mask);
Assert.Equal(30, overflow.Offset);
// The next section would be created "off the end"
// - the current offset is 30, and the current mask requires more than the remaining 1 bit.
Assert.InRange(CountBitsRequired(overflow.Mask), 2, 15);
Assert.Throws<InvalidOperationException>(() => BitVector32.CreateSection(invalid, overflow));
}
[Theory]
[MemberData(nameof(Section_Equal_Data))]
public static void Section_EqualsTest(BitVector32.Section left, BitVector32.Section right)
{
Assert.True(left.Equals(left));
Assert.True(left.Equals(right));
Assert.True(right.Equals(left));
Assert.True(left.Equals((object)left));
Assert.True(left.Equals((object)right));
Assert.True(right.Equals((object)left));
Assert.True(left == right);
Assert.True(right == left);
Assert.False(left != right);
Assert.False(right != left);
}
[Theory]
[MemberData(nameof(Section_Unequal_Data))]
public static void Section_Unequal_EqualsTest(BitVector32.Section left, BitVector32.Section right)
{
Assert.False(left.Equals(right));
Assert.False(right.Equals(left));
Assert.False(left.Equals((object)right));
Assert.False(right.Equals((object)left));
Assert.False(left.Equals(new object()));
Assert.False(left == right);
Assert.False(right == left);
Assert.True(left != right);
Assert.True(right != left);
}
[Theory]
[MemberData(nameof(Section_Equal_Data))]
public static void Section_GetHashCodeTest(BitVector32.Section left, BitVector32.Section right)
{
Assert.Equal(left.GetHashCode(), left.GetHashCode());
Assert.Equal(left.GetHashCode(), right.GetHashCode());
}
[Fact]
public static void Section_ToStringTest()
{
Random random = new Random(-55);
short maxValue = (short)random.Next(1, short.MaxValue);
BitVector32.Section section1 = BitVector32.CreateSection(maxValue);
BitVector32.Section section2 = BitVector32.CreateSection(maxValue);
Assert.Equal(section1.ToString(), section2.ToString());
Assert.Equal(section1.ToString(), BitVector32.Section.ToString(section2));
}
[Fact]
public static void EqualsTest()
{
BitVector32 original = new BitVector32();
Assert.True(original.Equals(original));
Assert.True(new BitVector32().Equals(original));
Assert.True(original.Equals(new BitVector32()));
Assert.True(new BitVector32(0).Equals(original));
Assert.True(original.Equals(new BitVector32(0)));
BitVector32 other = new BitVector32(int.MaxValue / 2 - 1);
Assert.True(other.Equals(other));
Assert.True(new BitVector32(int.MaxValue / 2 - 1).Equals(other));
Assert.True(other.Equals(new BitVector32(int.MaxValue / 2 - 1)));
Assert.False(other.Equals(original));
Assert.False(original.Equals(other));
Assert.False(other.Equals(null));
Assert.False(original.Equals(null));
Assert.False(other.Equals(int.MaxValue / 2 - 1));
Assert.False(original.Equals(0));
}
[Fact]
public static void GetHashCodeTest()
{
BitVector32 original = new BitVector32();
Assert.Equal(original.GetHashCode(), original.GetHashCode());
Assert.Equal(new BitVector32().GetHashCode(), original.GetHashCode());
Assert.Equal(new BitVector32(0).GetHashCode(), original.GetHashCode());
BitVector32 other = new BitVector32(int.MaxValue / 2 - 1);
Assert.Equal(other.GetHashCode(), other.GetHashCode());
Assert.Equal(new BitVector32(int.MaxValue / 2 - 1).GetHashCode(), other.GetHashCode());
}
[Theory]
[InlineData(0, "BitVector32{00000000000000000000000000000000}")]
[InlineData(1, "BitVector32{00000000000000000000000000000001}")]
[InlineData(-1, "BitVector32{11111111111111111111111111111111}")]
[InlineData(16 - 2, "BitVector32{00000000000000000000000000001110}")]
[InlineData(-(16 - 2), "BitVector32{11111111111111111111111111110010}")]
[InlineData(int.MaxValue, "BitVector32{01111111111111111111111111111111}")]
[InlineData(int.MinValue, "BitVector32{10000000000000000000000000000000}")]
[InlineData(short.MaxValue, "BitVector32{00000000000000000111111111111111}")]
[InlineData(short.MinValue, "BitVector32{11111111111111111000000000000000}")]
public static void ToStringTest(int data, string expected)
{
Assert.Equal(expected, new BitVector32(data).ToString());
Assert.Equal(expected, BitVector32.ToString(new BitVector32(data)));
}
private static short CountBitsRequired(short value)
{
short required = 16;
while ((value & 0x8000) == 0)
{
required--;
value <<= 1;
}
return required;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
/// <summary>
/// Base class for all Roslyn light bulb menu items.
/// </summary>
internal partial class SuggestedAction : ForegroundThreadAffinitizedObject, ISuggestedAction, IEquatable<ISuggestedAction>
{
protected readonly Workspace Workspace;
protected readonly ITextBuffer SubjectBuffer;
protected readonly ICodeActionEditHandlerService EditHandler;
protected readonly object Provider;
internal readonly CodeAction CodeAction;
private readonly ImmutableArray<SuggestedActionSet> _actionSets;
protected readonly IWaitIndicator WaitIndicator;
internal SuggestedAction(
Workspace workspace,
ITextBuffer subjectBuffer,
ICodeActionEditHandlerService editHandler,
IWaitIndicator waitIndicator,
CodeAction codeAction,
object provider,
IEnumerable<SuggestedActionSet> actionSets = null)
{
Contract.ThrowIfTrue(provider == null);
this.Workspace = workspace;
this.SubjectBuffer = subjectBuffer;
this.CodeAction = codeAction;
this.EditHandler = editHandler;
this.WaitIndicator = waitIndicator;
this.Provider = provider;
_actionSets = actionSets.AsImmutableOrEmpty();
}
public bool TryGetTelemetryId(out Guid telemetryId)
{
// TODO: this is temporary. Diagnostic team needs to figure out how to provide unique id per a fix.
// for now, we will use type of CodeAction, but there are some predefined code actions that are used by multiple fixes
// and this will not distinguish those
// AssemblyQualifiedName will change across version numbers, FullName won't
var type = CodeAction.GetType();
type = type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : type;
telemetryId = new Guid(type.FullName.GetHashCode(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
return true;
}
// NOTE: We want to avoid computing the operations on the UI thread. So we use Task.Run() to do this work on the background thread.
protected Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync(CancellationToken cancellationToken)
{
return Task.Run(
async () => await CodeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false), cancellationToken);
}
protected Task<IEnumerable<CodeActionOperation>> GetOperationsAsync(CodeActionWithOptions actionWithOptions, object options, CancellationToken cancellationToken)
{
return Task.Run(
async () => await actionWithOptions.GetOperationsAsync(options, cancellationToken).ConfigureAwait(false), cancellationToken);
}
protected Task<ImmutableArray<CodeActionOperation>> GetPreviewOperationsAsync(CancellationToken cancellationToken)
{
return Task.Run(
async () => await CodeAction.GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(false), cancellationToken);
}
public virtual void Invoke(CancellationToken cancellationToken)
{
this.AssertIsForeground();
var snapshot = this.SubjectBuffer.CurrentSnapshot;
using (new CaretPositionRestorer(this.SubjectBuffer, this.EditHandler.AssociatedViewService))
{
Func<Document> getFromDocument = () => this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
InvokeCore(getFromDocument, cancellationToken);
}
}
public void InvokeCore(Func<Document> getFromDocument, CancellationToken cancellationToken)
{
this.AssertIsForeground();
var extensionManager = this.Workspace.Services.GetService<IExtensionManager>();
extensionManager.PerformAction(Provider, () =>
{
this.WaitIndicator.Wait(CodeAction.Title, CodeAction.Message, allowCancel: true, action: context =>
{
using (var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, context.CancellationToken))
{
InvokeWorker(getFromDocument, linkedSource.Token);
}
});
});
}
private void InvokeWorker(Func<Document> getFromDocument, CancellationToken cancellationToken)
{
IEnumerable<CodeActionOperation> operations = null;
// NOTE: As mentioned above, we want to avoid computing the operations on the UI thread.
// However, for CodeActionWithOptions, GetOptions() might involve spinning up a dialog
// to compute the options and must be done on the UI thread.
var actionWithOptions = this.CodeAction as CodeActionWithOptions;
if (actionWithOptions != null)
{
var options = actionWithOptions.GetOptions(cancellationToken);
if (options != null)
{
operations = GetOperationsAsync(actionWithOptions, options, cancellationToken).WaitAndGetResult(cancellationToken);
}
}
else
{
operations = GetOperationsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
}
if (operations != null)
{
EditHandler.Apply(Workspace, getFromDocument(), operations, CodeAction.Title, cancellationToken);
}
}
public string DisplayText
{
get
{
// Underscores will become an accelerator in the VS smart tag. So we double all
// underscores so they actually get represented as an underscore in the UI.
var extensionManager = this.Workspace.Services.GetService<IExtensionManager>();
var text = extensionManager.PerformFunction(Provider, () => CodeAction.Title, defaultValue: string.Empty);
return text.Replace("_", "__");
}
}
protected async Task<SolutionPreviewResult> GetPreviewResultAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// We will always invoke this from the UI thread.
AssertIsForeground();
// We use ConfigureAwait(true) to stay on the UI thread.
var operations = await GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(true);
return EditHandler.GetPreviews(Workspace, operations, cancellationToken);
}
public virtual bool HasPreview
{
get
{
// HasPreview is called synchronously on the UI thread. In order to avoid blocking the UI thread,
// we need to provide a 'quick' answer here as opposed to the 'right' answer. Providing the 'right'
// answer is expensive (because we will need to call CodeAction.GetPreviewOperationsAsync() for this
// and this will involve computing the changed solution for the ApplyChangesOperation for the fix /
// refactoring). So we always return 'true' here (so that platform will call GetActionSetsAsync()
// below). Platform guarantees that nothing bad will happen if we return 'true' here and later return
// 'null' / empty collection from within GetPreviewAsync().
return true;
}
}
public virtual async Task<object> GetPreviewAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Light bulb will always invoke this function on the UI thread.
AssertIsForeground();
var preferredDocumentId = Workspace.GetDocumentIdInCurrentContext(SubjectBuffer.AsTextContainer());
var preferredProjectId = preferredDocumentId?.ProjectId;
var extensionManager = this.Workspace.Services.GetService<IExtensionManager>();
var previewContent = await extensionManager.PerformFunctionAsync(Provider, async () =>
{
// We need to stay on UI thread after GetPreviewResultAsync() so that TakeNextPreviewAsync()
// below can execute on UI thread. We use ConfigureAwait(true) to stay on the UI thread.
var previewResult = await GetPreviewResultAsync(cancellationToken).ConfigureAwait(true);
if (previewResult == null)
{
return null;
}
else
{
// TakeNextPreviewAsync() needs to run on UI thread.
AssertIsForeground();
return await previewResult.TakeNextPreviewAsync(preferredDocumentId, preferredProjectId, cancellationToken).ConfigureAwait(true);
}
// GetPreviewPane() below needs to run on UI thread. We use ConfigureAwait(true) to stay on the UI thread.
}, defaultValue: null).ConfigureAwait(true);
var previewPaneService = Workspace.Services.GetService<IPreviewPaneService>();
if (previewPaneService == null)
{
return null;
}
cancellationToken.ThrowIfCancellationRequested();
// GetPreviewPane() needs to run on the UI thread.
AssertIsForeground();
string language;
string projectType;
Workspace.GetLanguageAndProjectType(preferredProjectId, out language, out projectType);
return previewPaneService.GetPreviewPane(GetDiagnostic(), language, projectType, previewContent);
}
protected virtual DiagnosticData GetDiagnostic()
{
return null;
}
public virtual bool HasActionSets => _actionSets.Length > 0;
public virtual Task<IEnumerable<SuggestedActionSet>> GetActionSetsAsync(CancellationToken cancellationToken)
{
return Task.FromResult<IEnumerable<SuggestedActionSet>>(GetActionSets());
}
internal ImmutableArray<SuggestedActionSet> GetActionSets()
{
return _actionSets;
}
#region not supported
void IDisposable.Dispose()
{
// do nothing
}
// same as display text
string ISuggestedAction.IconAutomationText => DisplayText;
ImageMoniker ISuggestedAction.IconMoniker
{
get
{
// no icon support
return default(ImageMoniker);
}
}
string ISuggestedAction.InputGestureText
{
get
{
// no shortcut support
return null;
}
}
#endregion
#region IEquatable<ISuggestedAction>
public bool Equals(ISuggestedAction other)
{
return Equals(other as SuggestedAction);
}
public override bool Equals(object obj)
{
return Equals(obj as SuggestedAction);
}
internal bool Equals(SuggestedAction otherSuggestedAction)
{
if (otherSuggestedAction == null)
{
return false;
}
if (ReferenceEquals(this, otherSuggestedAction))
{
return true;
}
if (!ReferenceEquals(Provider, otherSuggestedAction.Provider))
{
return false;
}
var otherCodeAction = otherSuggestedAction.CodeAction;
if (CodeAction.EquivalenceKey == null || otherCodeAction.EquivalenceKey == null)
{
return false;
}
return CodeAction.EquivalenceKey == otherCodeAction.EquivalenceKey;
}
public override int GetHashCode()
{
if (CodeAction.EquivalenceKey == null)
{
return base.GetHashCode();
}
return Hash.Combine(Provider.GetHashCode(), CodeAction.EquivalenceKey.GetHashCode());
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="CustomActionProxy.cs" company="Microsoft Corporation">
// Copyright (c) 1999, Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Part of the Deployment Tools Foundation project.
// </summary>
//---------------------------------------------------------------------
namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller
{
using System;
using System.Collections;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
/// <summary>
/// Managed-code portion of the custom action proxy.
/// </summary>
internal static class CustomActionProxy
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static int InvokeCustomAction32(int sessionHandle, string entryPoint,
int remotingDelegatePtr)
{
return CustomActionProxy.InvokeCustomAction(sessionHandle, entryPoint, new IntPtr(remotingDelegatePtr));
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static int InvokeCustomAction64(int sessionHandle, string entryPoint,
long remotingDelegatePtr)
{
return CustomActionProxy.InvokeCustomAction(sessionHandle, entryPoint, new IntPtr(remotingDelegatePtr));
}
/// <summary>
/// Invokes a managed custom action method.
/// </summary>
/// <param name="sessionHandle">Integer handle to the installer session.</param>
/// <param name="entryPoint">Name of the custom action entrypoint. This must
/// either map to an entrypoint definition in the <c>customActions</c>
/// config section, or be an explicit entrypoint of the form:
/// "AssemblyName!Namespace.Class.Method"</param>
/// <param name="remotingDelegatePtr">Pointer to a delegate used to
/// make remote API calls, if this custom action is running out-of-proc.</param>
/// <returns>The value returned by the custom action method,
/// or ERROR_INSTALL_FAILURE if the custom action could not be invoked.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static int InvokeCustomAction(int sessionHandle, string entryPoint,
IntPtr remotingDelegatePtr)
{
Session session = null;
string assemblyName, className, methodName;
MethodInfo method;
try
{
MsiRemoteInvoke remotingDelegate = (MsiRemoteInvoke)
Marshal.GetDelegateForFunctionPointer(
remotingDelegatePtr, typeof(MsiRemoteInvoke));
RemotableNativeMethods.RemotingDelegate = remotingDelegate;
sessionHandle = RemotableNativeMethods.MakeRemoteHandle(sessionHandle);
session = new Session((IntPtr) sessionHandle, false);
if (string.IsNullOrWhiteSpace(entryPoint))
{
throw new ArgumentNullException("entryPoint");
}
if (!CustomActionProxy.FindEntryPoint(
session,
entryPoint,
out assemblyName,
out className,
out methodName))
{
return (int) ActionResult.Failure;
}
session.Log("Calling custom action {0}!{1}.{2}", assemblyName, className, methodName);
method = CustomActionProxy.GetCustomActionMethod(
session,
assemblyName,
className,
methodName);
if (method == null)
{
return (int) ActionResult.Failure;
}
}
catch (Exception ex)
{
if (session != null)
{
try
{
session.Log("Exception while loading custom action:");
session.Log(ex.ToString());
}
catch (Exception) { }
}
return (int) ActionResult.Failure;
}
try
{
// Set the current directory to the location of the extracted files.
Environment.CurrentDirectory =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
object[] args = new object[] { session };
if (DebugBreakEnabled(new string[] { entryPoint, methodName }))
{
string message = String.Format(CultureInfo.InvariantCulture,
"To debug your custom action, attach to process ID {0} (0x{0:x}) and click OK; otherwise, click Cancel to fail the custom action.",
System.Diagnostics.Process.GetCurrentProcess().Id
);
MessageResult button = NativeMethods.MessageBox(
IntPtr.Zero,
message,
"Custom Action Breakpoint",
(int)MessageButtons.OKCancel | (int)MessageIcon.Asterisk | (int)(MessageBoxStyles.TopMost | MessageBoxStyles.ServiceNotification)
);
if (MessageResult.Cancel == button)
{
return (int)ActionResult.UserExit;
}
}
ActionResult result = (ActionResult) method.Invoke(null, args);
session.Close();
return (int) result;
}
catch (InstallCanceledException)
{
return (int) ActionResult.UserExit;
}
catch (Exception ex)
{
session.Log("Exception thrown by custom action:");
session.Log(ex.ToString());
return (int) ActionResult.Failure;
}
}
/// <summary>
/// Checks the "MMsiBreak" environment variable for any matching custom action names.
/// </summary>
/// <param name="names">List of names to search for in the environment
/// variable string.</param>
/// <returns>True if a match was found, else false.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static bool DebugBreakEnabled(string[] names)
{
string mmsibreak = Environment.GetEnvironmentVariable("MMsiBreak");
if (mmsibreak != null)
{
foreach (string breakName in mmsibreak.Split(',', ';'))
{
foreach (string name in names)
{
if (breakName == name)
{
return true;
}
}
}
}
return false;
}
/// <summary>
/// Locates and parses an entrypoint mapping in CustomAction.config.
/// </summary>
/// <param name="session">Installer session handle, just used for logging.</param>
/// <param name="entryPoint">Custom action entrypoint name: the key value
/// in an item in the <c>customActions</c> section of the config file.</param>
/// <param name="assemblyName">Returned display name of the assembly from
/// the entrypoint mapping.</param>
/// <param name="className">Returned class name of the entrypoint mapping.</param>
/// <param name="methodName">Returned method name of the entrypoint mapping.</param>
/// <returns>True if the entrypoint was found, false if not or if some error
/// occurred.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private static bool FindEntryPoint(
Session session,
string entryPoint,
out string assemblyName,
out string className,
out string methodName)
{
assemblyName = null;
className = null;
methodName = null;
string fullEntryPoint;
if (entryPoint.IndexOf('!') > 0)
{
fullEntryPoint = entryPoint;
}
else
{
IDictionary config;
try
{
config = (IDictionary) ConfigurationManager.GetSection("customActions");
}
catch (ConfigurationException cex)
{
session.Log("Error: missing or invalid customActions config section.");
session.Log(cex.ToString());
return false;
}
fullEntryPoint = (string) config[entryPoint];
if (fullEntryPoint == null)
{
session.Log(
"Error: custom action entry point '{0}' not found " +
"in customActions config section.",
entryPoint);
return false;
}
}
int assemblySplit = fullEntryPoint.IndexOf('!');
int methodSplit = fullEntryPoint.LastIndexOf('.');
if (assemblySplit < 0 || methodSplit < 0 || methodSplit < assemblySplit)
{
session.Log("Error: invalid custom action entry point:" + entryPoint);
return false;
}
assemblyName = fullEntryPoint.Substring(0, assemblySplit);
className = fullEntryPoint.Substring(assemblySplit + 1, methodSplit - assemblySplit - 1);
methodName = fullEntryPoint.Substring(methodSplit + 1);
return true;
}
/// <summary>
/// Uses reflection to load the assembly and class and find the method.
/// </summary>
/// <param name="session">Installer session handle, just used for logging.</param>
/// <param name="assemblyName">Display name of the assembly containing the
/// custom action method.</param>
/// <param name="className">Fully-qualified name of the class containing the
/// custom action method.</param>
/// <param name="methodName">Name of the custom action method.</param>
/// <returns>The method, or null if not found.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private static MethodInfo GetCustomActionMethod(
Session session,
string assemblyName,
string className,
string methodName)
{
Assembly customActionAssembly;
Type customActionClass = null;
Exception caughtEx = null;
try
{
customActionAssembly = AppDomain.CurrentDomain.Load(assemblyName);
customActionClass = customActionAssembly.GetType(className, true, true);
}
catch (IOException ex) { caughtEx = ex; }
catch (BadImageFormatException ex) { caughtEx = ex; }
catch (TypeLoadException ex) { caughtEx = ex; }
catch (ReflectionTypeLoadException ex) { caughtEx = ex; }
catch (SecurityException ex) { caughtEx = ex; }
if (caughtEx != null)
{
session.Log("Error: could not load custom action class " + className + " from assembly: " + assemblyName);
session.Log(caughtEx.ToString());
return null;
}
MethodInfo[] methods = customActionClass.GetMethods(
BindingFlags.Public | BindingFlags.Static);
foreach (MethodInfo method in methods)
{
if (method.Name == methodName &&
CustomActionProxy.MethodHasCustomActionSignature(method))
{
return method;
}
}
session.Log("Error: custom action method \"" + methodName +
"\" is missing or has the wrong signature.");
return null;
}
/// <summary>
/// Checks if a method has the right return and parameter types
/// for a custom action, and that it is marked by a CustomActionAttribute.
/// </summary>
/// <param name="method">Method to be checked.</param>
/// <returns>True if the method is a valid custom action, else false.</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private static bool MethodHasCustomActionSignature(MethodInfo method)
{
if (method.ReturnType == typeof(ActionResult) &&
method.GetParameters().Length == 1 &&
method.GetParameters()[0].ParameterType == typeof(Session))
{
object[] methodAttribs = method.GetCustomAttributes(false);
foreach (object attrib in methodAttribs)
{
if (attrib is CustomActionAttribute)
{
return true;
}
}
}
return false;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace resume.interface.rest.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Omnius.Base;
using Omnius.Correction;
using Omnius.Utils;
using Xunit;
using Xunit.Abstractions;
namespace Omnius.Tests
{
[Trait("Category", "Omnius.Correction")]
public class Omnius_Correction_Tests : TestsBase
{
private BufferManager _bufferManager = BufferManager.Instance;
private Random _random = new Random();
public Omnius_Correction_Tests(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void ReedSolomon8Test()
{
for (int type = 0; type < 2; type++)
{
for (int count = 128 - 1; count >= 0; count--)
{
int blockLength = _random.Next(32, 1024);
var reedSolomon8 = new ReedSolomon8(128, 256, 2, _bufferManager);
if (type == 0) reedSolomon8.LoadNativeMethods();
else if (type == 1) reedSolomon8.LoadPureUnsafeMethods();
var tokenSource = new CancellationTokenSource();
var buffList = new ArraySegment<byte>[128];
for (int i = 0; i < 128; i++)
{
var buffer = new byte[blockLength];
_random.NextBytes(buffer);
buffList[i] = new ArraySegment<byte>(buffer, 0, buffer.Length);
}
var buffList2 = new ArraySegment<byte>[256];
for (int i = 0; i < 256; i++)
{
var buffer = new byte[blockLength];
buffList2[i] = new ArraySegment<byte>(buffer, 0, buffer.Length);
}
var intList = new int[256];
for (int i = 0; i < 256; i++)
{
intList[i] = i;
}
reedSolomon8.Encode(buffList, buffList2, intList, blockLength, tokenSource.Token).Wait();
var buffList3 = new ArraySegment<byte>[128];
{
int i = 0;
for (int j = 0; i < 64; i++, j++)
{
buffList3[i] = buffList2[i];
}
for (int j = 0; i < 128; i++, j++)
{
buffList3[i] = buffList2[128 + j];
}
}
var intList2 = new int[128];
{
int i = 0;
for (int j = 0; i < 64; i++, j++)
{
intList2[i] = i;
}
for (int j = 0; i < 128; i++, j++)
{
intList2[i] = 128 + j;
}
}
{
int n = buffList3.Length;
while (n > 1)
{
int k = _random.Next(n--);
var temp = buffList3[n];
buffList3[n] = buffList3[k];
buffList3[k] = temp;
int temp2 = intList2[n];
intList2[n] = intList2[k];
intList2[k] = temp2;
}
}
reedSolomon8.Decode(buffList3, intList2, blockLength, tokenSource.Token).Wait();
for (int i = 0; i < buffList.Length; i++)
{
Assert.True(CollectionUtils.Equals(buffList[i].Array, buffList[i].Offset, buffList3[i].Array, buffList3[i].Offset, blockLength));
}
}
{
var reedSolomon8 = new ReedSolomon8(128, 256, 4, _bufferManager);
if (type == 0) reedSolomon8.LoadNativeMethods();
else if (type == 1) reedSolomon8.LoadPureUnsafeMethods();
var tokenSource = new CancellationTokenSource();
var buffList = new ArraySegment<byte>[128];
for (int i = 0; i < 128; i++)
{
var buffer = new byte[1024 * 32];
_random.NextBytes(buffer);
buffList[i] = new ArraySegment<byte>(buffer, 0, buffer.Length);
}
var buffList2 = new ArraySegment<byte>[128];
for (int i = 0; i < 128; i++)
{
var buffer = new byte[1024 * 32];
buffList2[i] = new ArraySegment<byte>(buffer, 0, buffer.Length);
}
var intList = new int[128];
for (int i = 0; i < 128; i++)
{
intList[i] = i + 128;
}
{
var sw = new Stopwatch();
sw.Start();
var task1 = reedSolomon8.Encode(buffList, buffList2, intList, 1024 * 32, tokenSource.Token);
Thread.Sleep(1000 * 1);
tokenSource.Cancel();
task1.Wait();
sw.Stop();
Assert.True(sw.Elapsed.TotalSeconds < 3);
}
}
{
var reedSolomon8 = new ReedSolomon8(128, 256, 4, _bufferManager);
if (type == 0) reedSolomon8.LoadNativeMethods();
else if (type == 1) reedSolomon8.LoadPureUnsafeMethods();
var tokenSource = new CancellationTokenSource();
var buffList = new ArraySegment<byte>[128];
for (int i = 0; i < 128; i++)
{
var buffer = new byte[1024 * 32];
_random.NextBytes(buffer);
buffList[i] = new ArraySegment<byte>(buffer, 0, buffer.Length);
}
var buffList2 = new ArraySegment<byte>[128];
for (int i = 0; i < 128; i++)
{
var buffer = new byte[1024 * 32];
buffList2[i] = new ArraySegment<byte>(buffer, 0, buffer.Length);
}
var intList = new int[128];
for (int i = 0; i < 128; i++)
{
intList[i] = i + 128;
}
reedSolomon8.Encode(buffList, buffList2, intList, 1024 * 32, tokenSource.Token).Wait();
{
var sw = new Stopwatch();
sw.Start();
var task1 = reedSolomon8.Decode(buffList2.ToArray(), intList, 1024 * 32, tokenSource.Token);
Thread.Sleep(1000 * 1);
tokenSource.Cancel();
task1.Wait();
sw.Stop();
Assert.True(sw.Elapsed.TotalSeconds < 3);
}
}
}
}
}
}
| |
//**************************************************************************
//
//
// National Institute Of Standards and Technology
// DTS Version 1.0
//
// Attr Interface
//
// Written by: Carmelo Montanez
//
// Ported to System.Xml by: Mizrahi Rafael rafim@mainsoft.com
// Mainsoft Corporation (c) 2003-2004
//
//**************************************************************************
using System;
using System.Xml;
using nist_dom;
using NUnit.Framework;
namespace nist_dom.fundamental
{
[TestFixture]
public class AttrTest : Assertion//, ITest
{
public static int i = 1;
/*
public testResults[] RunTests()
{
testResults[] tests = new testResults[] {core0001A(), core0002A(), core0003A(),core0004A(),
core0005A(), core0006A(), core0007A(), core0008A(),
core0009A(), core0010A(), core0011A(), core0012A(),
core0013A(), core0014A()};
return tests;
}
*/
//------------------------ test case core-0001A ------------------------
//
// Testing feature - The parentNode attribute for an Attr object should
// be null.
//
// Testing approach - Retrieve the attribute named "domestic" from the last
// child of of the first employee and examine its
// parentNode attribute. This test uses the
// "GetNamedItem(name)" method from the NamedNodeMap
// interface.
//
// Semantic Requirements: 1
//
//----------------------------------------------------------------------------
[Test]
public void core0001A()
{
object computedValue = null;
object expectedValue = null;
System.Xml.XmlNode testNode = null;
System.Xml.XmlAttribute domesticAttr = null;
testResults results = new testResults("Core0001A");
try
{
results.description = "The ParentNode attribute should be null for" +
" an Attr object.";
//
// Retrieve targeted data and examine parentNode attribute.
//
testNode = util.nodeObject(util.FIRST, util.SIXTH);
domesticAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("domestic");
computedValue = domesticAttr.ParentNode;
//
// Write out results
//
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
results.expected = (expectedValue == null).ToString();
results.actual = (computedValue == null).ToString();
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0001A --------------------------
//
//------------------------- test case core-0002A ----------------------------
//
//
// Written By: Carmelo Montanez
//
// Testing feature - The previousSibling attribute for an Attr object
// should be null.
//
// Testing approach - Retrieve the attribute named "domestic" from the last
// child of of the first employee and examine its
// previousSibling attribute. This test uses the
// "GetNamedItem(name)" method from the NamedNodeMap
// interface.
//
// Semantic Requirements: 1
//
//----------------------------------------------------------------------------
[Test]
public void core0002A()
{
object computedValue = null;
object expectedValue = null;
System.Xml.XmlAttribute domesticAttr = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0002A");
try
{
results.description = "The previousSibling attribute should be " +
"null for an Attr object.";
//
// Retrieve the targeted data and examine its previousSibling attribute.
//
testNode = util.nodeObject(util.FIRST,util.SIXTH);
domesticAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("domestic");
computedValue = domesticAttr.PreviousSibling;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = (expectedValue == null).ToString();
results.actual = (computedValue == null).ToString();
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0002A --------------------------
//
//------------------------- test case core-0003A ----------------------------
// Written By: Carmelo Montanez
//
// Testing feature - The nextSibling attribute for an Attr object should
// be null.
//
// Testing approach - Retrieve the attribute named "domestic" from the
// last child of of the first employee and examine
// its nextSibling attribute. This test uses the
// "GetNamedItem(name)" method from the NamedNodeMap
// interface.
//
// Semantic Requirements: 1
//
//----------------------------------------------------------------------------
[Test]
public void core0003A()
{
object computedValue = null;
object expectedValue = null;
System.Xml.XmlAttribute domesticAttr = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0003A");
try
{
results.description = "The nextSibling attribute should be null " +
"for an Attr object.";
//
// Retrieve the targeted data and examine its nextSibling attribute.
//
testNode = util.nodeObject(util.FIRST,util.SIXTH);
domesticAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("domestic");
computedValue = domesticAttr.NextSibling;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = (expectedValue == null).ToString();
results.actual = (computedValue == null).ToString();
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0003A --------------------------
//
//------------------------- test case core-0004A ----------------------------
//
// Written By: Carmelo Montanez
//
// Testing feature - Attr objects may be associated with Element nodes
// contained within a DocumentFragment.
//
// Testing approach - Create a new DocumentFragment object and add a newly
// created Element node to it (with one attribute). Once
// the element is added, its attribute should be available
// as an attribute associated with an Element within a
// DocumentFragment.
//
// Semantic Requirements: 2
//
//----------------------------------------------------------------------------
[Test]
public void core0004A()
{
string computedValue = "";
string expectedValue = "domestic";
System.Xml.XmlAttribute domesticAttr = null;
testResults results = new testResults("Core0004A");
try
{
results.description = "Attr objects may be associated with Element " +
"nodes contained within a DocumentFragment.";
System.Xml.XmlDocumentFragment docFragment = util.getDOMDocument().CreateDocumentFragment();
System.Xml.XmlElement newElement = (System.Xml.XmlElement)util.createNode(util.ELEMENT_NODE,"element1");
//
// The new DocumentFragment is empty upon creation. Set an attribute for
// a newly created element and add the element to the documentFragment.
//
newElement.SetAttribute("domestic","Yes");
docFragment.AppendChild(newElement);
//
// Access the attributes of the only child of the documentFragment
//
domesticAttr = (System.Xml.XmlAttribute)docFragment.FirstChild.Attributes.Item(0) ;
computedValue = domesticAttr.Name;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0004A --------------------------
//
//-------------------------- test case core-0005A ----------------------------
//
// Testing feature - If an Attr is explicitly assigned any value, then that
// value is the attribute's effective value.
//
// Testing approach - Retrieve the attribute name "domestic" from the last
// child of of the first employee element and examine its
// assigned value. This test uses the
// "GetNamedItem(name)" method from the NamedNodeMap
// interface.
//
// Semantic Requirements: 3
//
//----------------------------------------------------------------------------
[Test]
public void core0005A()
{
string computedValue = "";
string expectedValue = "Yes";
System.Xml.XmlAttribute domesticAttr = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0005A");
try
{
results.description = "If an attribute is explicitly assigned any value, " +
"then that value is the attribute's effective value.";
//
// Retrieve the targeted data and examine its assigned value.
//
testNode = util.nodeObject(util.FIRST,util.SIXTH);
domesticAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("domestic");
computedValue = domesticAttr.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0005A --------------------------
//
//-------------------------- test case core-0006A ----------------------------
//
// Testing feature - If there is no explicit value assigned to an attribute
// and there is a declaration for this attribute and that
// declaration includes a default value, then that default
// value is the Attribute's default value.
//
// Testing approach - Retrieve the attribute named "street" from the
// last child of of the first employee and examine its
// value. That value should be the value given during
// the declaration of the attribute in the DTD file.
// This test uses the "GetNamedItem(name)" method from
// the NamedNodeMap interface.
//
// Semantic Requirements: 4
//
//----------------------------------------------------------------------------
[Test]
public void core0006A()
{
string computedValue = "";
string expectedValue = "Yes";
System.Xml.XmlAttribute streetAttr = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0006A");
try
{
results.description = "If there is no explicit value assigned to an " +
"attribute and there is a declaration for this " +
"attribute and that declaration includes a default " +
"value, then that default value is the Attribute's " +
"default value.";
//
// Retrieve the targeted data and examine its default value.
//
testNode = util.nodeObject(util.FIRST,util.SIXTH);
streetAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("street");
computedValue = streetAttr.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0006A --------------------------
//
//-------------------------- test case core-0007A ---------------------------
//
// Testing feature - The "name" Attribute of an Attribute node.
//
// Testing approach - Retrieve the attribute named "street" from the
// last child of the second employee and examine its "name"
// attribute. This test uses the "GetNamedItem(name)"
// method from the NamedNodeMap interface.
//
// Semantic Requirements: 5
//
//----------------------------------------------------------------------------
[Test]
public void core0007A()
{
string computedValue = "";
string expectedValue = "street";
System.Xml.XmlAttribute streetAttr = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0007A");
try
{
results.description = "The \"name\" attribute of an Attr object contains " +
"the name of that attribute.";
//
// Retrieve the targeted data and capture its assigned name.
//
testNode = util.nodeObject(util.SECOND,util.SIXTH);
streetAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("street");
computedValue = streetAttr.Name;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0007A --------------------------
//
//-------------------------- test case core-0008A ---------------------------
//
// Testing feature - The "specified" attribute of an Attr node should be set
// to true if the attribute was explicitly given a value.
//
// Testing approach - Retrieve the attribute named "doestic" from the last
// child of the first employee and examine its "specified"
// attribute. It should be set to true. This test
// uses the "GetNamedItem(name)" method from the
// NamedNodeMap interface.
//
// Semantic Requirements: 6
//
//----------------------------------------------------------------------------
[Test]
public void core0008A()
{
string computedValue = "";//0;
string expectedValue = "True";
System.Xml.XmlNode testNode = null;
System.Xml.XmlAttribute domesticAttr = null;
testResults results = new testResults("Core0008A");
try
{
results.description = "The \"specified\" attribute for an Attr object " +
"should be set to true if the attribute was " +
"explictly given a value.";
//
// Retrieve the targeted data and capture its "specified" value.
//
testNode = util.nodeObject(util.FIRST,util.SIXTH);
domesticAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("domestic");;
computedValue = domesticAttr.Specified.ToString();
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0008A --------------------------
//
//-------------------------- test case core-0009A ---------------------------
//
// Testing feature - The "specified" attribute for an Attr node should be
// set to false if the attribute was not explicitly given
// a value.
//
// Testing approach - Retrieve the attribute named "street"(not explicity
// given a value) from the last child of the first employee
// and examine its "specified" attribute. It should be
// set to false. This test uses the
// "GetNamedItem(name)" method from the NamedNodeMap
// interface.
//
// Semantic Requirements: 6
//
//----------------------------------------------------------------------------
[Test]
public void core0009A()
{
string computedValue = "";//0;
string expectedValue = "False";
System.Xml.XmlAttribute streetAttr = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0009A");
try
{
results.description = "The \"specified\" attribute for an Attr node " +
"should be set to false if the attribute was " +
"not explictly given a value.";
//
// Retrieve the targeted data and capture its "specified" attribute.
//
testNode = util.nodeObject(util.FIRST,util.SIXTH);
streetAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("street");
computedValue = streetAttr.Specified.ToString();
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0009A --------------------------
//
//-------------------------- test case core-0010A ---------------------------
//
// Testing feature - The "specified" attribute for an Attr node should be
// automatically flipped to true if value of the attribute
// is changed (even its ends up having a default DTD value)
//
// Testing approach - Retrieve the attribute named "street" from the last
// child of the third employee and change its value to "Yes"
// (which is its default DTD value). This should cause the
// "specified" attribute to be flipped to true. This test
// makes use of the "setAttribute(name,value )" method from
// the Element interface and the "GetNamedItem(name)"
// method from the NamedNodeMap interface.
//
// Semantic Requirements: 7
//
//----------------------------------------------------------------------------
[Test]
public void core0010A()
{
string computedValue = "";//"";
string expectedValue = "True";
System.Xml.XmlAttribute streetAttr = null;
System.Xml.XmlElement testNode = null;
testResults results = new testResults("Core0010A");
try
{
results.description = "The \"specified\" attribute for an Attr node " +
"should be flipped to true if the attribute value " +
"is changed (even it changed to its default value).";
//
// Retrieve the targeted data and set a new attribute for it, then
// capture its "specified" attribute.
//
testNode = (System.Xml.XmlElement)util.nodeObject(util.THIRD,util.FIFTH);
testNode.SetAttribute("street","Yes");//testNode.node.setAttribute("street","Yes");
streetAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("street");
computedValue = streetAttr.Specified.ToString();
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0010A --------------------------
//
//-------------------------- test case core-0011A ---------------------------
//
// Testing feature - To respecify the attribute to its default value from the
// DTD, the attribute must be deleted. The implementation
// will then make a new attribute available with the
// "specified" attribute set to false.
// Testing approach - Retrieve the attribute named "street" from the last
// child of the third employee and delete it. The
// implementation should then create a new attribute with
// its default value and "specified" set to false. This
// test uses the "removeAttribute(name)" from the Element
// interface and the "GetNamedItem(name)" method from the
// NamedNodeMap interface.
//
// Semantic Requirements: 8
//
//----------------------------------------------------------------------------
[Test]
public void core0011A()
{
string computedValue = "";//"";
string expectedValue = "False";
System.Xml.XmlAttribute streetAttr = null;
System.Xml.XmlElement testNode = null;
testResults results = new testResults("Core0011A");
try
{
results.description = "Re-setting an attribute to its default value " +
"requires that the attribute be deleted. The " +
"implementation should create a new attribute " +
"with its \"specified\" attribute set to false.";
//
// Retrieve the targeted data, remove the "street" attribute and capture
// its specified attribute.
//
testNode = (System.Xml.XmlElement)util.nodeObject(util.THIRD,util.SIXTH);
testNode.RemoveAttribute("street");//testNode.node.removeAttribute("street");
streetAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("street");
computedValue = streetAttr.Specified.ToString();
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0011A --------------------------
//
//-------------------------- test case core-0012A ---------------------------
//
// Testing feature - Upon retrieval, the "value" of an attribute is returned
// as a string with characters and general entity references
// replaced with their values.
// Testing approach - Retrieve the attribute named "street" from the last
// child of the fourth employee and examine its value
// attribute. This value should be "Yes" after the
// EntityReference is replaced with its value. This
// test uses the "GetNamedItem(name)" method from
// the NamedNodeMap interface.
//
// Semantic Requirements: 9
//
//----------------------------------------------------------------------------
[Test]
public void core0012A()
{
string computedValue = "";
string expectedValue = "Yes";
System.Xml.XmlAttribute streetAttr = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0012A");
try
{
results.description = "Upon retrieval the \"value\" attribute of an Attr" +
"object is returned as a string with any Entity " +
"References replaced with their values.";
//
// Retrieve the targeted data.
//
testNode = util.nodeObject(util.FOURTH,util.SIXTH);
streetAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("street");
computedValue = streetAttr.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0012A --------------------------
//
//-------------------------- test case core-0013A ---------------------------
//
// Testing feature - On setting, the "value" attribute of an Attr node
// creates a Text node with the unparsed content of
// the string.
// Testing approach - Retrieve the attribute named "street" from the last
// child of the fourth employee and assign the "Y%ent1;"
// string to its value attribute. This value is not yet
// parsed and therefore should still be the same upon
// retrieval. This test uses the "GetNamedItem(name)"
// method from the NamedNodeMap interface.
//
// Semantic Requirements: 10
//
//----------------------------------------------------------------------------
[Test]
public void core0013A()
{
string computedValue = "";
string expectedValue = "Y%ent1;";
System.Xml.XmlAttribute streetAttr = null;
System.Xml.XmlNode testNode = null;
testResults results = new testResults("Core0013A");
try
{
results.description = "On setting, the \"value\" attribute of an Attr " +
"object creates a Text node with the unparsed " +
"content of the string.";
//
// Retrieve the targeted data, assign a value to it and capture its
// "value" attribute.
//
testNode = util.nodeObject(util.FOURTH,util.SIXTH);
streetAttr = (System.Xml.XmlAttribute)testNode.Attributes.GetNamedItem("street");
streetAttr.Value = "Y%ent1;";
computedValue = streetAttr.Value;
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
//
// Write out results
//
results.expected = expectedValue;
results.actual = computedValue;
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0013A --------------------------
//
//-------------------------- test case core-0014A ---------------------------
//
// Testing feature - Setting the "value" attribute raises a
// NO_MODIFICATION_ALLOWED_ERR Exception if the
// node is readonly.
//
// Testing approach - Retrieve the first attribute of the Entity node named
// "ent4" and attempt to change its value attribute.
// Since the descendants of Entity nodes are readonly, the
// desired exception should be raised.
//
// Semantic Requirements: 11
//
//----------------------------------------------------------------------------
[Test]
[Category ("NotDotNet")] // MS DOM is buggy
public void core0014A()
{
string computedValue = "";
System.Xml.XmlNode testNode = null;
System.Xml.XmlAttribute readOnlyAttribute = null;
string expectedValue = "System.ArgumentException";//util.NO_MODIFICATION_ALLOWED_ERR;
testResults results = new testResults("Core0014A");
try
{
results.description = "Setting the \"value\" attribute raises a " +
"NO_MODIFICATION_ALLOWED_ERR Exception if " +
"the node is readonly.";
//
// Retrieve the targeted data.
//
testNode = util.getEntity("ent4");
readOnlyAttribute = (System.Xml.XmlAttribute)testNode.FirstChild.Attributes.Item(0);
//
// attempt to set a value on a readonly node should raise an exception.
//
try
{
readOnlyAttribute.Value = "ABCD";
}
catch (ArgumentException ex)
{
computedValue = ex.GetType ().FullName;
}
}
catch(System.Exception ex)
{
computedValue = "Exception " + ex.Message;
}
results.expected = expectedValue;
results.actual = computedValue;
util.resetData();
AssertEquals (results.expected, results.actual);
// return results;
}
//------------------------ End test case core-0014A --------------------------
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Glimpse.Agent.Messages;
using Microsoft.AspNet.FileProviders;
using Microsoft.Extensions.PlatformAbstractions;
namespace Glimpse.Agent.Internal.Inspectors
{
public class ExceptionProcessor : IExceptionProcessor
{
private static readonly int SourceCodeLineCount = 6; // TODO: Make as an option?
private static readonly bool IsMono = Type.GetType("Mono.Runtime") != null;
private readonly IFileProvider _fileProvider;
public ExceptionProcessor(IApplicationEnvironment appEnvironment)
{
// TODO: Allow the user to configure which provider should be used
_fileProvider = new PhysicalFileProvider(appEnvironment.ApplicationBasePath);
}
public IEnumerable<ExceptionDetails> GetErrorDetails(Exception ex)
{
var result = new List<ExceptionDetails>();
for (var scan = ex; scan != null; scan = scan.InnerException)
{
result.Add(new ExceptionDetails
{
Type = scan.GetType(),
TypeName = scan.GetType().Name,
Message = scan.Message,
RawException = scan.ToString(),
StackFrames = StackFrames(scan)
});
}
return result;
}
private IEnumerable<StackFrame> StackFrames(Exception ex)
{
var result = new List<StackFrame>();
var stackTrace = ex.StackTrace;
if (!string.IsNullOrEmpty(stackTrace))
{
var heap = new Chunk { Text = stackTrace + Environment.NewLine, End = stackTrace.Length + Environment.NewLine.Length };
for (var line = heap.Advance(Environment.NewLine); line.HasValue; line = heap.Advance(Environment.NewLine))
{
result.Add(StackFrame(line));
}
}
return result;
}
private StackFrame StackFrame(Chunk line)
{
line.Advance(" at ");
var function = line.Advance(" in ").ToString();
//exception message line format differences in .net and mono
//On .net : at ConsoleApplication.Program.Main(String[] args) in D:\Program.cs:line 16
//On Mono : at ConsoleApplication.Program.Main(String[] args) in d:\Program.cs:16
var file = !IsMono ?
line.Advance(":line ").ToString() :
line.Advance(":").ToString();
var lineNumber = line.ToInt32();
if (string.IsNullOrEmpty(file))
{
return GetStackFrame(
// Handle stack trace lines like
// "--- End of stack trace from previous location where exception from thrown ---"
string.IsNullOrEmpty(function) ? line.ToString() : function,
file: string.Empty,
lineNumber: 0);
}
else
{
return GetStackFrame(function, file, lineNumber);
}
}
// make it internal to enable unit testing
internal StackFrame GetStackFrame(string function, string file, int lineNumber)
{
var frame = new StackFrame { Function = function, File = file, Line = lineNumber };
if (string.IsNullOrEmpty(file))
{
return frame;
}
IEnumerable<string> lines = null;
if (File.Exists(file))
{
lines = File.ReadLines(file);
}
else
{
// Handle relative paths and embedded files
var fileInfo = _fileProvider.GetFileInfo(file);
if (fileInfo.Exists)
{
// ReadLines doesn't accept a stream. Use ReadLines as its more efficient
// relative to reading lines via stream reader
if (!string.IsNullOrEmpty(fileInfo.PhysicalPath))
{
lines = File.ReadLines(fileInfo.PhysicalPath);
}
else
{
lines = ReadLines(fileInfo);
}
}
}
if (lines != null)
{
ReadFrameContent(frame, lines, lineNumber, lineNumber);
}
return frame;
}
// make it internal to enable unit testing
internal void ReadFrameContent(
StackFrame frame,
IEnumerable<string> allLines,
int errorStartLineNumberInFile,
int errorEndLineNumberInFile)
{
// Get the line boundaries in the file to be read and read all these lines at once into an array.
var preErrorLineNumberInFile = Math.Max(errorStartLineNumberInFile - SourceCodeLineCount, 1);
var postErrorLineNumberInFile = errorEndLineNumberInFile + SourceCodeLineCount;
var codeBlock = allLines
.Skip(preErrorLineNumberInFile - 1)
.Take(postErrorLineNumberInFile - preErrorLineNumberInFile + 1)
.ToArray();
var numOfErrorLines = (errorEndLineNumberInFile - errorStartLineNumberInFile) + 1;
var errorStartLineNumberInArray = errorStartLineNumberInFile - preErrorLineNumberInFile;
frame.PreContextLine = preErrorLineNumberInFile;
frame.PreContextCode = codeBlock.Take(errorStartLineNumberInArray).ToArray();
frame.ContextCode = codeBlock
.Skip(errorStartLineNumberInArray)
.Take(numOfErrorLines)
.ToArray();
frame.PostContextCode = codeBlock
.Skip(errorStartLineNumberInArray + numOfErrorLines)
.ToArray();
}
private static IEnumerable<string> ReadLines(IFileInfo fileInfo)
{
var result = new List<string>();
using (var reader = new StreamReader(fileInfo.CreateReadStream()))
{
string line;
while ((line = reader.ReadLine()) != null)
{
result.Add(line);
}
}
return result;
}
internal class Chunk
{
public string Text { get; set; }
public int Start { get; set; }
public int End { get; set; }
public bool HasValue => Text != null;
public Chunk Advance(string delimiter)
{
var indexOf = HasValue ? Text.IndexOf(delimiter, Start, End - Start, StringComparison.Ordinal) : -1;
if (indexOf < 0)
{
return new Chunk();
}
var chunk = new Chunk { Text = Text, Start = Start, End = indexOf };
Start = indexOf + delimiter.Length;
return chunk;
}
public override string ToString()
{
return HasValue ? Text.Substring(Start, End - Start) : string.Empty;
}
public int ToInt32()
{
int value;
return HasValue && int.TryParse(
Text.Substring(Start, End - Start),
NumberStyles.Integer,
CultureInfo.InvariantCulture,
out value) ? value : 0;
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="PrimitiveType.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Common.Utils;
using System.Data.Spatial;
using System.Diagnostics;
using System.Linq;
namespace System.Data.Metadata.Edm
{
/// <summary>
/// Class representing a primitive type
/// </summary>
public sealed class PrimitiveType : SimpleType
{
#region constructors
/// <summary>
/// Initializes a new instance of PrimitiveType
/// </summary>
internal PrimitiveType()
{
// No initialization of item attributes in here, it's used as a pass thru in the case for delay population
// of item attributes
}
/// <summary>
/// The constructor for PrimitiveType. It takes the required information to identify this type.
/// </summary>
/// <param name="name">The name of this type</param>
/// <param name="namespaceName">The namespace name of this type</param>
/// <param name="version">The version of this type</param>
/// <param name="dataSpace">dataSpace in which this primitive type belongs to</param>
/// <param name="baseType">The primitive type that this type is derived from</param>
/// <param name="providerManifest">The ProviderManifest of the provider of this type</param>
/// <exception cref="System.ArgumentNullException">Thrown if name, namespaceName, version, baseType or providerManifest arguments are null</exception>
internal PrimitiveType(string name,
string namespaceName,
DataSpace dataSpace,
PrimitiveType baseType,
DbProviderManifest providerManifest)
: base(name, namespaceName, dataSpace)
{
EntityUtil.GenericCheckArgumentNull(baseType, "baseType");
EntityUtil.GenericCheckArgumentNull(providerManifest, "providerManifest");
this.BaseType = baseType;
Initialize(this, baseType.PrimitiveTypeKind,
false, // isDefault
providerManifest);
}
/// <summary>
/// The constructor for PrimitiveType, it takes in a CLR type containing the identity information
/// </summary>
/// <param name="clrType">The CLR type object for this primitive type</param>
/// <param name="baseType">The base type for this primitive type</param>
/// <param name="providerManifest">The ProviderManifest of the provider of this type</param>
internal PrimitiveType(Type clrType,
PrimitiveType baseType,
DbProviderManifest providerManifest)
: this(EntityUtil.GenericCheckArgumentNull(clrType, "clrType").Name, clrType.Namespace,
DataSpace.OSpace, baseType, providerManifest)
{
Debug.Assert(clrType == ClrEquivalentType, "not equivalent to ClrEquivalentType");
}
#endregion
#region Fields
private PrimitiveTypeKind _primitiveTypeKind;
private DbProviderManifest _providerManifest;
#endregion
#region Properties
/// <summary>
/// Returns the kind of the type
/// </summary>
public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.PrimitiveType; } }
/// <summary>
/// </summary>
internal override System.Type ClrType
{
get { return ClrEquivalentType; }
}
/// <summary>
/// Returns the PrimitiveTypeKind enumeration value indicating what kind of primitive type this is
/// </summary>
/// <returns>A PrimitiveTypeKind value</returns>
[MetadataProperty(BuiltInTypeKind.PrimitiveTypeKind, false)]
public PrimitiveTypeKind PrimitiveTypeKind
{
get
{
return _primitiveTypeKind;
}
internal set
{
_primitiveTypeKind = value;
}
}
/// <summary>
/// Returns the ProviderManifest giving access to the Manifest that this type came from
/// </summary>
/// <returns>The types ProviderManifest value</returns>
internal DbProviderManifest ProviderManifest
{
get
{
Debug.Assert(_providerManifest != null, "This primitive type should have been added to a manifest, which should have set this");
return _providerManifest;
}
set
{
Debug.Assert(value != null, "This primitive type should have been added to a manifest, which should have set this");
_providerManifest = value;
}
}
/// <summary>
/// Gets the FacetDescriptions for this type
/// </summary>
/// <returns>The FacetDescritions for this type.</returns>
public System.Collections.ObjectModel.ReadOnlyCollection<FacetDescription> FacetDescriptions
{
get
{
return ProviderManifest.GetFacetDescriptions(this);
}
}
/// <summary>
/// Returns an equivalent CLR type representing this primitive type
/// </summary>
public Type ClrEquivalentType
{
get
{
switch (PrimitiveTypeKind)
{
case PrimitiveTypeKind.Binary:
return typeof(byte[]);
case PrimitiveTypeKind.Boolean:
return typeof(bool);
case PrimitiveTypeKind.Byte:
return typeof(byte);
case PrimitiveTypeKind.DateTime:
return typeof(DateTime);
case PrimitiveTypeKind.Time:
return typeof(TimeSpan);
case PrimitiveTypeKind.DateTimeOffset:
return typeof(DateTimeOffset);
case PrimitiveTypeKind.Decimal:
return typeof(decimal);
case PrimitiveTypeKind.Double:
return typeof(double);
case PrimitiveTypeKind.Geography:
case PrimitiveTypeKind.GeographyPoint:
case PrimitiveTypeKind.GeographyLineString:
case PrimitiveTypeKind.GeographyPolygon:
case PrimitiveTypeKind.GeographyMultiPoint:
case PrimitiveTypeKind.GeographyMultiLineString:
case PrimitiveTypeKind.GeographyMultiPolygon:
case PrimitiveTypeKind.GeographyCollection:
return typeof(DbGeography);
case PrimitiveTypeKind.Geometry:
case PrimitiveTypeKind.GeometryPoint:
case PrimitiveTypeKind.GeometryLineString:
case PrimitiveTypeKind.GeometryPolygon:
case PrimitiveTypeKind.GeometryMultiPoint:
case PrimitiveTypeKind.GeometryMultiLineString:
case PrimitiveTypeKind.GeometryMultiPolygon:
case PrimitiveTypeKind.GeometryCollection:
return typeof(DbGeometry);
case PrimitiveTypeKind.Guid:
return typeof(Guid);
case PrimitiveTypeKind.Single:
return typeof(Single);
case PrimitiveTypeKind.SByte:
return typeof(sbyte);
case PrimitiveTypeKind.Int16:
return typeof(short);
case PrimitiveTypeKind.Int32:
return typeof(int);
case PrimitiveTypeKind.Int64:
return typeof(long);
case PrimitiveTypeKind.String:
return typeof(string);
}
return null;
}
}
#endregion
#region Methods
internal override IEnumerable<FacetDescription> GetAssociatedFacetDescriptions()
{
// return all general facets and facets associated with this type
return base.GetAssociatedFacetDescriptions().Concat(this.FacetDescriptions);
}
/// <summary>
/// Perform initialization that's common across all constructors
/// </summary>
/// <param name="primitiveType">The primitive type to initialize</param>
/// <param name="primitiveTypeKind">The primitive type kind of this primitive type</param>
/// <param name="isDefaultType">When true this is the default type to return when a type is asked for by PrimitiveTypeKind</param>
/// <param name="providerManifest">The ProviderManifest of the provider of this type</param>
internal static void Initialize(PrimitiveType primitiveType,
PrimitiveTypeKind primitiveTypeKind,
bool isDefaultType,
DbProviderManifest providerManifest)
{
primitiveType._primitiveTypeKind = primitiveTypeKind;
primitiveType._providerManifest = providerManifest;
}
/// <summary>
/// return the model equivalent type for this type,
/// for example if this instance is nvarchar and it's
/// base type is Edm String then the return type is Edm String.
/// If the type is actually already a model type then the
/// return type is "this".
/// </summary>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
public EdmType GetEdmPrimitiveType()
{
return MetadataItem.EdmProviderManifest.GetPrimitiveType(PrimitiveTypeKind);
}
/// <summary>
/// Returns the list of EDM primitive types
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
public static System.Collections.ObjectModel.ReadOnlyCollection<PrimitiveType> GetEdmPrimitiveTypes()
{
return EdmProviderManifest.GetStoreTypes();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")]
public static PrimitiveType GetEdmPrimitiveType(PrimitiveTypeKind primitiveTypeKind)
{
return MetadataItem.EdmProviderManifest.GetPrimitiveType(primitiveTypeKind);
}
#endregion
}
}
| |
using System;
using System.Text;
///<summary>
///System.Test.UnicodeEncoding.GetCharCount(System.Byte[],System.Int32,System.Int32) [v-zuolan]
///</summary>
public class UnicodeEncodingGetCharCount
{
public static int Main()
{
UnicodeEncodingGetCharCount testObj = new UnicodeEncodingGetCharCount();
TestLibrary.TestFramework.BeginTestCase("for field of System.Test.UnicodeEncoding");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("Positive");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("Positive");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
return retVal;
}
#region Helper Method
//Create a None-Surrogate-Char Array.
public Char[] GetCharArray(int length)
{
if (length <= 0) return new Char[] { };
Char[] charArray = new Char[length];
int i = 0;
while (i < length)
{
Char temp = TestLibrary.Generator.GetChar(-55);
if (!Char.IsSurrogate(temp))
{
charArray[i] = temp;
i++;
}
}
return charArray;
}
public String ToString(Char[] chars)
{
String str = "{";
for (int i = 0; i < chars.Length; i++)
{
str = str + @"\u" + String.Format("{0:X04}", (int)chars[i]);
if (i != chars.Length - 1) str = str + ",";
}
str = str + "}";
return str;
}
#endregion
#region Positive Test Logic
public bool PosTest1()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(chars,0,10,bytes,0);
int expectedValue = 10;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method.");
try
{
actualValue = uEncoding.GetCharCount(bytes, 0, 20);
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")" + " when Chars is:" + ToString(chars));
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e + " when Chars is:" + ToString(chars));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
int expectedValue = 0;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method and set byteCount as 0.");
try
{
actualValue = uEncoding.GetCharCount(bytes, 5, 0);
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")" + " when Chars is:" + ToString(chars));
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e + " when Chars is:" + ToString(chars));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
int expectedValue = 1;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the method and set byteCount as 2");
try
{
actualValue = uEncoding.GetCharCount(bytes, 0, 2);
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("005", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")" + " when Chars is:" + ToString(chars));
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception:" + e + " when Chars is:" + ToString(chars));
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
int expectedValue = 0;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest4:Invoke the method and set byteIndex out of right range.");
try
{
actualValue = uEncoding.GetCharCount(bytes, 20, 0);
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("017", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")" + " when Chars is:" + ToString(chars));
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Negative Test Logic
public bool NegTest1()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
int actualValue;
TestLibrary.TestFramework.BeginScenario("NegTest1:Invoke the method and set bytes as null");
try
{
actualValue = uEncoding.GetCharCount(null, 0, 0);
TestLibrary.TestFramework.LogError("007", "No ArgumentNullException throw out expected.");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
int actualValue;
TestLibrary.TestFramework.BeginScenario("NegTest2:Invoke the method and set byteIndex as -1");
try
{
actualValue = uEncoding.GetCharCount(bytes, -1, 2);
TestLibrary.TestFramework.LogError("009", "No ArgumentOutOfRangeException throw out expected.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
int actualValue;
TestLibrary.TestFramework.BeginScenario("NegTest3:Invoke the method and set byteIndex out of right range.");
try
{
actualValue = uEncoding.GetCharCount(bytes, 21, 0);
TestLibrary.TestFramework.LogError("011", "No ArgumentOutOfRangeException throw out expected.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
int actualValue;
TestLibrary.TestFramework.BeginScenario("NegTest4:Invoke the method and set byteCount as -1");
try
{
actualValue = uEncoding.GetCharCount(bytes, 0, -1);
TestLibrary.TestFramework.LogError("013", "No ArgumentOutOfRangeException throw out expected.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
int actualValue;
TestLibrary.TestFramework.BeginScenario("NegTest5:Invoke the method and set byteCount as 21");
try
{
actualValue = uEncoding.GetCharCount(bytes, 0, 21);
TestLibrary.TestFramework.LogError("015", "No ArgumentOutOfRangeException throw out expected.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
namespace AsterNET
{
#if LOGGER
#region class LogFactory
/// <summary>
/// Facade to hide details of the underlying logging system.
/// </summary>
public sealed class Logger
{
public enum MessageLevel
{
Info,
Warning,
Error,
Debug
}
private static Logger logger;
private Hashtable visibleDebug = new Hashtable();
private bool visibleDebugDef = true;
private Hashtable visibleError = new Hashtable();
private bool visibleErrorDef = true;
private Hashtable visibleInfo = new Hashtable();
private bool visibleInfoDef = true;
private Hashtable visibleWarning = new Hashtable();
private bool visibleWarningDef = true;
/// <summary>
/// Creates a new CommonsLoggingLog obtained from commons-logging's LogFactory for the given class.
/// </summary>
public Logger()
{
}
/// <summary>
/// Returns an instance of Log suitable for logging from the given class.
/// </summary>
/// <returns> the created logger.</returns>
public static Logger Instance()
{
if (logger == null)
logger = new Logger();
return logger;
}
private void writeLine(string type, string msg)
{
System.Diagnostics.Debug.Print("{0}[{1}] {2}", type, Thread.CurrentThread.Name, msg);
}
private void writeLine(string msg)
{
System.Diagnostics.Debug.Print(msg);
}
// Max 2 calls from original caller !
private string debugInfo()
{
var sf = new StackFrame(2, true);
MethodBase mb = sf.GetMethod();
return string.Concat(mb.DeclaringType.Name, ":", mb.Name);
}
/// <summary>
/// Get visibility for message level of class:method
/// </summary>
/// <param name="debugClass">messageType:class:method</param>
/// <returns></returns>
public bool IsVisible(MessageLevel messageLevel, string classMethod)
{
return isVisible(messageLevel, classMethod.GetHashCode());
}
private bool isVisible(MessageLevel messageLevel, int hash)
{
switch (messageLevel)
{
case MessageLevel.Debug:
return (visibleDebug.ContainsKey(hash) ? (bool) visibleDebug[hash] : visibleDebugDef);
case MessageLevel.Error:
return (visibleError.ContainsKey(hash) ? (bool) visibleError[hash] : visibleErrorDef);
case MessageLevel.Info:
return (visibleInfo.ContainsKey(hash) ? (bool) visibleInfo[hash] : visibleInfoDef);
case MessageLevel.Warning:
return (visibleWarning.ContainsKey(hash) ? (bool) visibleWarning[hash] : visibleWarningDef);
}
return true;
}
/// <summary>
/// Set visibility for message level of class:method
/// </summary>
/// <param name="visible">visible</param>
/// <param name="messageLevel">message level</param>
/// <param name="classMethod">class:method</param>
public void Visible(bool visible, MessageLevel messageLevel, string classMethod)
{
int hash = classMethod.GetHashCode();
switch (messageLevel)
{
case MessageLevel.Debug:
visibleDebug[hash] = visible;
return;
case MessageLevel.Error:
visibleError[hash] = visible;
return;
case MessageLevel.Info:
visibleInfo[hash] = visible;
return;
case MessageLevel.Warning:
visibleWarning[hash] = visible;
return;
}
}
/// <summary>
/// Set visibility for message level of class:method
/// </summary>
/// <param name="visible">visible</param>
/// <param name="messageLevel">message level</param>
/// <param name="classMethod">class:method</param>
public void Visible(bool visible, MessageLevel messageLevel)
{
switch (messageLevel)
{
case MessageLevel.Debug:
visibleDebugDef = visible;
return;
case MessageLevel.Error:
visibleErrorDef = visible;
return;
case MessageLevel.Info:
visibleInfoDef = visible;
return;
case MessageLevel.Warning:
visibleWarningDef = visible;
return;
}
}
#region Debug
public void Debug(object o)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Debug, caller.GetHashCode()))
writeLine(" Debug:", string.Concat(caller, " - ", o.ToString()));
}
public void Debug(string msg)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Debug, caller.GetHashCode()))
writeLine(" Debug:", string.Concat(caller, " - ", msg));
}
public void Debug(string format, params object[] args)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Debug, caller.GetHashCode()))
writeLine(" Debug:", string.Concat(caller, " - ", string.Format(format, args)));
}
public void Debug(string msg, Exception ex)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Debug, caller.GetHashCode()))
writeLine(" Debug:", string.Concat(caller, " - ", string.Format("{0}\n{1}", msg, ex)));
}
#endregion
#region Info
public void Info(object o)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Info, caller.GetHashCode()))
writeLine(" Info:", string.Concat(caller, " - ", o.ToString()));
}
public void Info(string msg)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Info, caller.GetHashCode()))
writeLine(" Info:", string.Concat(caller, " - ", msg));
}
public void Info(string format, params object[] args)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Info, caller.GetHashCode()))
writeLine(" Info:", string.Concat(caller, " - ", string.Format(format, args)));
}
public void Info(string msg, Exception ex)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Info, caller.GetHashCode()))
writeLine(" Info:", string.Concat(caller, " - ", string.Format("{0}\n{1}", msg, ex)));
}
#endregion
#region Warning
public void Warning(object o)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Warning, caller.GetHashCode()))
writeLine("Warning:", string.Concat(caller, " - ", o.ToString()));
}
public void Warning(string msg)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Warning, caller.GetHashCode()))
writeLine("Warning:", string.Concat(caller, " - ", msg));
}
public void Warning(string format, params object[] args)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Warning, caller.GetHashCode()))
writeLine("Warning:", string.Concat(caller, " - ", string.Format(format, args)));
}
public void Warning(string msg, Exception ex)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Warning, caller.GetHashCode()))
writeLine("Warning:", string.Concat(caller, " - ", string.Format("{0}\n{1}", msg, ex)));
}
#endregion
#region Error
public void Error(object o)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Error, caller.GetHashCode()))
writeLine(" Error:", string.Concat(caller, " - ", o.ToString()));
}
public void Error(string msg)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Error, caller.GetHashCode()))
writeLine(" Error:", string.Concat(caller, " - ", msg));
}
public void Error(string format, params object[] args)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Error, caller.GetHashCode()))
writeLine(" Error:", string.Concat(caller, " - ", string.Format(format, args)));
}
public void Error(string msg, Exception ex)
{
string caller = debugInfo();
if (isVisible(MessageLevel.Error, caller.GetHashCode()))
writeLine(" Error:", string.Concat(caller, " - ", string.Format("{0}\n{1}", msg, ex)));
}
#endregion
}
#endregion
#endif
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
/// <summary>
/// A two-dimensional vector with floating-point values
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector2 : IComparable<Vector2>, IEquatable<Vector2>
{
/// <summary>X value</summary>
public float X;
/// <summary>Y value</summary>
public float Y;
#region Constructors
public Vector2(float x, float y)
{
X = x;
Y = y;
}
public Vector2(float value)
{
X = value;
Y = value;
}
public Vector2(Vector2 vector)
{
X = vector.X;
Y = vector.Y;
}
#endregion Constructors
#region Public Methods
/// <summary>
/// Test if this vector is equal to another vector, within a given
/// tolerance range
/// </summary>
/// <param name="vec">Vector to test against</param>
/// <param name="tolerance">The acceptable magnitude of difference
/// between the two vectors</param>
/// <returns>True if the magnitude of difference between the two vectors
/// is less than the given tolerance, otherwise false</returns>
public bool ApproxEquals(Vector2 vec, float tolerance)
{
Vector2 diff = this - vec;
return (diff.LengthSquared() <= tolerance * tolerance);
}
/// <summary>
/// Test if this vector is composed of all finite numbers
/// </summary>
public bool IsFinite()
{
return Utils.IsFinite(X) && Utils.IsFinite(Y);
}
/// <summary>
/// IComparable.CompareTo implementation
/// </summary>
public int CompareTo(Vector2 vector)
{
return Length().CompareTo(vector.Length());
}
/// <summary>
/// Builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing two four-byte floats</param>
/// <param name="pos">Beginning position in the byte array</param>
public void FromBytes(byte[] byteArray, int pos)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[8];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 8);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
}
}
/// <summary>
/// Returns the raw bytes for this vector
/// </summary>
/// <returns>An eight-byte array containing X and Y</returns>
public byte[] GetBytes()
{
byte[] byteArray = new byte[8];
ToBytes(byteArray, 0);
return byteArray;
}
/// <summary>
/// Writes the raw bytes for this vector to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 8 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 4, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(dest, pos + 0, 4);
Array.Reverse(dest, pos + 4, 4);
}
}
public float Length()
{
return (float)Math.Sqrt(DistanceSquared(this, Zero));
}
public float LengthSquared()
{
return DistanceSquared(this, Zero);
}
public void Normalize()
{
this = Normalize(this);
}
#endregion Public Methods
#region Static Methods
public static Vector2 Add(Vector2 value1, Vector2 value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
return value1;
}
public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max)
{
return new Vector2(
Utils.Clamp(value1.X, min.X, max.X),
Utils.Clamp(value1.Y, min.Y, max.Y));
}
public static float Distance(Vector2 value1, Vector2 value2)
{
return (float)Math.Sqrt(DistanceSquared(value1, value2));
}
public static float DistanceSquared(Vector2 value1, Vector2 value2)
{
return
(value1.X - value2.X) * (value1.X - value2.X) +
(value1.Y - value2.Y) * (value1.Y - value2.Y);
}
public static Vector2 Divide(Vector2 value1, Vector2 value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
return value1;
}
public static Vector2 Divide(Vector2 value1, float divider)
{
float factor = 1 / divider;
value1.X *= factor;
value1.Y *= factor;
return value1;
}
public static float Dot(Vector2 value1, Vector2 value2)
{
return value1.X * value2.X + value1.Y * value2.Y;
}
public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount)
{
return new Vector2(
Utils.Lerp(value1.X, value2.X, amount),
Utils.Lerp(value1.Y, value2.Y, amount));
}
public static Vector2 Max(Vector2 value1, Vector2 value2)
{
return new Vector2(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y));
}
public static Vector2 Min(Vector2 value1, Vector2 value2)
{
return new Vector2(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y));
}
public static Vector2 Multiply(Vector2 value1, Vector2 value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
return value1;
}
public static Vector2 Multiply(Vector2 value1, float scaleFactor)
{
value1.X *= scaleFactor;
value1.Y *= scaleFactor;
return value1;
}
public static Vector2 Negate(Vector2 value)
{
value.X = -value.X;
value.Y = -value.Y;
return value;
}
public static Vector2 Normalize(Vector2 value)
{
const float MAG_THRESHOLD = 0.0000001f;
float factor = DistanceSquared(value, Zero);
if (factor > MAG_THRESHOLD)
{
factor = 1f / (float)Math.Sqrt(factor);
value.X *= factor;
value.Y *= factor;
}
else
{
value.X = 0f;
value.Y = 0f;
}
return value;
}
/// <summary>
/// Parse a vector from a string
/// </summary>
/// <param name="val">A string representation of a 2D vector, enclosed
/// in arrow brackets and separated by commas</param>
public static Vector3 Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
return new Vector3(
float.Parse(split[0].Trim(), Utils.EnUsCulture),
float.Parse(split[1].Trim(), Utils.EnUsCulture),
float.Parse(split[2].Trim(), Utils.EnUsCulture));
}
public static bool TryParse(string val, out Vector3 result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = Vector3.Zero;
return false;
}
}
/// <summary>
/// Interpolates between two vectors using a cubic equation
/// </summary>
public static Vector2 SmoothStep(Vector2 value1, Vector2 value2, float amount)
{
return new Vector2(
Utils.SmoothStep(value1.X, value2.X, amount),
Utils.SmoothStep(value1.Y, value2.Y, amount));
}
public static Vector2 Subtract(Vector2 value1, Vector2 value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
return value1;
}
public static Vector2 Transform(Vector2 position, Matrix4 matrix)
{
position.X = (position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41;
position.Y = (position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42;
return position;
}
public static Vector2 TransformNormal(Vector2 position, Matrix4 matrix)
{
position.X = (position.X * matrix.M11) + (position.Y * matrix.M21);
position.Y = (position.X * matrix.M12) + (position.Y * matrix.M22);
return position;
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Vector2) ? this == ((Vector2)obj) : false;
}
public bool Equals(Vector2 other)
{
return this == other;
}
public override int GetHashCode()
{
int hash = X.GetHashCode();
hash = hash * 31 + Y.GetHashCode();
return hash;
}
/// <summary>
/// Get a formatted string representation of the vector
/// </summary>
/// <returns>A string representation of the vector</returns>
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}>", X, Y);
}
/// <summary>
/// Get a string representation of the vector elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the vector</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1}", X, Y);
}
#endregion Overrides
#region Operators
public static bool operator ==(Vector2 value1, Vector2 value2)
{
return value1.X == value2.X && value1.Y == value2.Y;
}
public static bool operator !=(Vector2 value1, Vector2 value2)
{
return value1.X != value2.X || value1.Y != value2.Y;
}
public static Vector2 operator +(Vector2 value1, Vector2 value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
return value1;
}
public static Vector2 operator -(Vector2 value)
{
value.X = -value.X;
value.Y = -value.Y;
return value;
}
public static Vector2 operator -(Vector2 value1, Vector2 value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
return value1;
}
public static Vector2 operator *(Vector2 value1, Vector2 value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
return value1;
}
public static Vector2 operator *(Vector2 value, float scaleFactor)
{
value.X *= scaleFactor;
value.Y *= scaleFactor;
return value;
}
public static Vector2 operator /(Vector2 value1, Vector2 value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
return value1;
}
public static Vector2 operator /(Vector2 value1, float divider)
{
float factor = 1 / divider;
value1.X *= factor;
value1.Y *= factor;
return value1;
}
#endregion Operators
/// <summary>A vector with a value of 0,0</summary>
public readonly static Vector2 Zero = new Vector2();
/// <summary>A vector with a value of 1,1</summary>
public readonly static Vector2 One = new Vector2(1f, 1f);
/// <summary>A vector with a value of 1,0</summary>
public readonly static Vector2 UnitX = new Vector2(1f, 0f);
/// <summary>A vector with a value of 0,1</summary>
public readonly static Vector2 UnitY = new Vector2(0f, 1f);
}
}
| |
using System;
using System.Text;
using System.IO;
/// <summary>
/// C# implementation of ASCII85 encoding.
/// Based on C code from http://www.stillhq.com/cgi-bin/cvsweb/ascii85/
/// </summary>
/// <remarks>
/// Jeff Atwood
/// http://www.codinghorror.com/blog/archives/000410.html
/// </remarks>
public class Ascii85
{
/// <summary>
/// Prefix mark that identifies an encoded ASCII85 string, traditionally '<~'
/// </summary>
public string PrefixMark = "<~";
/// <summary>
/// Suffix mark that identifies an encoded ASCII85 string, traditionally '~>'
/// </summary>
public string SuffixMark = "~>";
/// <summary>
/// Maximum line length for encoded ASCII85 string;
/// set to zero for one unbroken line.
/// </summary>
public int LineLength = 75;
/// <summary>
/// Add the Prefix and Suffix marks when encoding, and enforce their presence for decoding
/// </summary>
public bool EnforceMarks = true;
private const int _asciiOffset = 33;
private byte[] _encodedBlock = new byte[5];
private byte[] _decodedBlock = new byte[4];
private uint _tuple = 0;
private int _linePos = 0;
private uint[] pow85 = { 85 * 85 * 85 * 85, 85 * 85 * 85, 85 * 85, 85, 1 };
/// <summary>
/// Decodes an ASCII85 encoded string into the original binary data
/// </summary>
/// <param name="s">ASCII85 encoded string</param>
/// <returns>byte array of decoded binary data</returns>
public byte[] Decode(string s)
{
if (EnforceMarks)
{
if (!s.StartsWith(PrefixMark) | !s.EndsWith(SuffixMark))
{
throw new Exception("ASCII85 encoded data should begin with '" + PrefixMark +
"' and end with '" + SuffixMark + "'");
}
}
// strip prefix and suffix if present
if (s.StartsWith(PrefixMark))
{
s = s.Substring(PrefixMark.Length);
}
if (s.EndsWith(SuffixMark))
{
s = s.Substring(0, s.Length - SuffixMark.Length);
}
MemoryStream ms = new MemoryStream();
int count = 0;
bool processChar = false;
foreach (char c in s)
{
switch (c)
{
case 'z':
if (count != 0)
{
throw new Exception("The character 'z' is invalid inside an ASCII85 block.");
}
_decodedBlock[0] = 0;
_decodedBlock[1] = 0;
_decodedBlock[2] = 0;
_decodedBlock[3] = 0;
ms.Write(_decodedBlock, 0, _decodedBlock.Length);
processChar = false;
break;
case '\n': case '\r': case '\t': case '\0': case '\f': case '\b':
processChar = false;
break;
default:
if (c < '!' || c > 'u')
{
throw new Exception("Bad character '" + c + "' found. ASCII85 only allows characters '!' to 'u'.");
}
processChar = true;
break;
}
if (processChar)
{
_tuple += ((uint)(c - _asciiOffset) * pow85[count]);
count++;
if (count == _encodedBlock.Length)
{
DecodeBlock();
ms.Write(_decodedBlock, 0, _decodedBlock.Length);
_tuple = 0;
count = 0;
}
}
}
// if we have some bytes left over at the end..
if (count != 0)
{
if (count == 1)
{
throw new Exception("The last block of ASCII85 data cannot be a single byte.");
}
count--;
_tuple += pow85[count];
DecodeBlock(count);
for (int i = 0; i < count; i++)
{
ms.WriteByte(_decodedBlock[i]);
}
}
return ms.ToArray();
}
/// <summary>
/// Encodes binary data into a plaintext ASCII85 format string
/// </summary>
/// <param name="ba">binary data to encode</param>
/// <returns>ASCII85 encoded string</returns>
public string Encode(byte[] ba)
{
StringBuilder sb = new StringBuilder((int)(ba.Length * (_encodedBlock.Length/_decodedBlock.Length)));
_linePos = 0;
if (EnforceMarks)
{
AppendString(sb, PrefixMark);
}
int count = 0;
_tuple = 0;
foreach (byte b in ba)
{
if (count >= _decodedBlock.Length - 1)
{
_tuple |= b;
if (_tuple == 0)
{
AppendChar(sb, 'z');
}
else
{
EncodeBlock(sb);
}
_tuple = 0;
count = 0;
}
else
{
_tuple |= (uint)(b << (24 - (count * 8)));
count++;
}
}
// if we have some bytes left over at the end..
if (count > 0)
{
EncodeBlock(count + 1, sb);
}
if (EnforceMarks)
{
AppendString(sb, SuffixMark);
}
return sb.ToString();
}
private void EncodeBlock(StringBuilder sb)
{
EncodeBlock(_encodedBlock.Length, sb);
}
private void EncodeBlock(int count, StringBuilder sb)
{
for (int i = _encodedBlock.Length - 1; i >= 0; i--)
{
_encodedBlock[i] = (byte)((_tuple % 85) + _asciiOffset);
_tuple /= 85;
}
for (int i = 0; i < count; i++)
{
char c = (char)_encodedBlock[i];
AppendChar(sb, c);
}
}
private void DecodeBlock()
{
DecodeBlock(_decodedBlock.Length);
}
private void DecodeBlock(int bytes)
{
for (int i = 0; i < bytes; i++)
{
_decodedBlock[i] = (byte)(_tuple >> 24 - (i * 8));
}
}
private void AppendString(StringBuilder sb, string s)
{
if (LineLength > 0 && (_linePos + s.Length > LineLength))
{
_linePos = 0;
sb.Append('\n');
}
else
{
_linePos += s.Length;
}
sb.Append(s);
}
private void AppendChar(StringBuilder sb, char c)
{
sb.Append(c);
_linePos++;
if (LineLength > 0 && (_linePos >= LineLength))
{
_linePos = 0;
sb.Append('\n');
}
}
}
| |
// 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;
using System;
using System.Collections;
using System.Collections.Specialized;
namespace System.Collections.Specialized.Tests
{
public class OrderedDictionaryTests
{
// public OrderedDictionary();
[Fact]
public void DefaultConstructorDoesNotThrow()
{
OrderedDictionary dictionary = new OrderedDictionary();
}
// public OrderedDictionary(int capacity);
[Fact]
public void CreatingWithDifferentCapacityValues()
{
// exceptions are not thrown until you add an element
var d1 = new OrderedDictionary(-1000);
var d2 = new OrderedDictionary(-1);
var d3 = new OrderedDictionary(0);
var d4 = new OrderedDictionary(1);
var d5 = new OrderedDictionary(1000);
Assert.Throws<ArgumentOutOfRangeException>(() => d1.Add("foo", "bar"));
Assert.Throws<ArgumentOutOfRangeException>(() => d2.Add("foo", "bar"));
d3.Add("foo", "bar");
d4.Add("foo", "bar");
d5.Add("foo", "bar");
}
// public OrderedDictionary(IEqualityComparer comparer);
[Fact]
public void PassingEqualityComparers()
{
var eqComp = new CaseInsensitiveEqualityComparer();
var d1 = new OrderedDictionary(eqComp);
d1.Add("foo", "bar");
AssertExtensions.Throws<ArgumentException>(null, () => d1.Add("FOO", "bar"));
// The equality comparer should also test for a non-existent key
d1.Remove("foofoo");
Assert.True(d1.Contains("foo"));
// Make sure we can change an existent key that passes the equality comparer
d1["FOO"] = "barbar";
Assert.Equal("barbar", d1["foo"]);
d1.Remove("FOO");
Assert.False(d1.Contains("foo"));
}
// public OrderedDictionary(int capacity, IEqualityComparer comparer);
[Fact]
public void PassingCapacityAndIEqualityComparer()
{
var eqComp = new CaseInsensitiveEqualityComparer();
var d1 = new OrderedDictionary(-1000, eqComp);
var d2 = new OrderedDictionary(-1, eqComp);
var d3 = new OrderedDictionary(0, eqComp);
var d4 = new OrderedDictionary(1, eqComp);
var d5 = new OrderedDictionary(1000, eqComp);
Assert.Throws<ArgumentOutOfRangeException>(() => d1.Add("foo", "bar"));
Assert.Throws<ArgumentOutOfRangeException>(() => d2.Add("foo", "bar"));
d3.Add("foo", "bar");
d4.Add("foo", "bar");
d5.Add("foo", "bar");
}
// public int Count { get; }
[Fact]
public void CountTests()
{
var d = new OrderedDictionary();
Assert.Equal(0, d.Count);
for (int i = 0; i < 1000; i++)
{
d.Add(i, i);
Assert.Equal(i + 1, d.Count);
}
for (int i = 0; i < 1000; i++)
{
d.Remove(i);
Assert.Equal(1000 - i - 1, d.Count);
}
for (int i = 0; i < 1000; i++)
{
d[(object)i] = i;
Assert.Equal(i + 1, d.Count);
}
for (int i = 0; i < 1000; i++)
{
d.RemoveAt(0);
Assert.Equal(1000 - i - 1, d.Count);
}
}
// public bool IsReadOnly { get; }
[Fact]
public void IsReadOnlyTests()
{
var d = new OrderedDictionary();
Assert.False(d.IsReadOnly);
var d2 = d.AsReadOnly();
Assert.True(d2.IsReadOnly);
}
[Fact]
public void AsReadOnly_AttemptingToModifyDictionary_Throws()
{
OrderedDictionary orderedDictionary = new OrderedDictionary().AsReadOnly();
Assert.Throws<NotSupportedException>(() => orderedDictionary[0] = "value");
Assert.Throws<NotSupportedException>(() => orderedDictionary["key"] = "value");
Assert.Throws<NotSupportedException>(() => orderedDictionary.Add("key", "value"));
Assert.Throws<NotSupportedException>(() => orderedDictionary.Insert(0, "key", "value"));
Assert.Throws<NotSupportedException>(() => orderedDictionary.Remove("key"));
Assert.Throws<NotSupportedException>(() => orderedDictionary.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => orderedDictionary.Clear());
}
// public ICollection Keys { get; }
[Fact]
public void KeysPropertyContainsAllKeys()
{
var d = new OrderedDictionary();
var alreadyChecked = new bool[1000];
for (int i = 0; i < 1000; i++)
{
d["test_" + i] = i;
alreadyChecked[i] = false;
}
ICollection keys = d.Keys;
Assert.False(keys.IsSynchronized);
Assert.NotSame(d, keys.SyncRoot);
Assert.Equal(d.Count, keys.Count);
foreach (var key in d.Keys)
{
string skey = (string)key;
var p = skey.Split(new char[] { '_' });
Assert.Equal(2, p.Length);
int number = int.Parse(p[1]);
Assert.False(alreadyChecked[number]);
Assert.True(number >= 0 && number < 1000);
alreadyChecked[number] = true;
}
object[] array = new object[keys.Count + 50];
keys.CopyTo(array, 50);
for (int i = 50; i < array.Length; i++)
{
Assert.True(d.Contains(array[i]));
}
AssertExtensions.Throws<ArgumentNullException>("array", () => keys.CopyTo(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => keys.CopyTo(new object[keys.Count], -1));
}
// bool System.Collections.ICollection.IsSynchronized { get; }
[Fact]
public void IsSynchronizedTests()
{
ICollection c = new OrderedDictionary();
Assert.False(c.IsSynchronized);
}
[Fact]
public void SyncRootTests()
{
ICollection orderedDictionary1 = new OrderedDictionary();
ICollection orderedDictionary2 = new OrderedDictionary();
object sync1 = orderedDictionary1.SyncRoot;
object sync2 = orderedDictionary2.SyncRoot;
// Sync root objects for the same dictionaries are equivalent
Assert.Same(orderedDictionary1.SyncRoot, orderedDictionary1.SyncRoot);
Assert.Same(orderedDictionary2.SyncRoot, orderedDictionary2.SyncRoot);
// Sync root objects for different dictionaries are not equivalent
Assert.NotSame(sync1, sync2);
}
// bool System.Collections.IDictionary.IsFixedSize { get; }
[Fact]
public void IsFixedSizeTests()
{
var d = new OrderedDictionary();
IDictionary dic = d;
IDictionary rodic = d.AsReadOnly();
Assert.False(dic.IsFixedSize);
Assert.True(rodic.IsFixedSize);
}
// public object this[int index] { get; set; }
[Fact]
public void GettingByIndexTests()
{
var d = new OrderedDictionary();
for (int i = 0; i < 1000; i++)
{
d.Add("test" + i, i);
}
for (int i = 0; i < 1000; i++)
{
Assert.Equal(d[i], i);
d[i] = (int)d[i] + 100;
Assert.Equal(d[i], 100 + i);
}
Assert.Throws<ArgumentOutOfRangeException>(() => { int foo = (int)d[-1]; });
Assert.Throws<ArgumentOutOfRangeException>(() => { d[-1] = 5; });
Assert.Throws<ArgumentOutOfRangeException>(() => { int foo = (int)d[1000]; });
Assert.Throws<ArgumentOutOfRangeException>(() => { d[1000] = 5; });
}
// public object this[object key] { get; set; }
[Fact]
public void GettingByKeyTests()
{
var d = new OrderedDictionary();
for (int i = 0; i < 1000; i++)
{
d.Add("test" + i, i);
}
for (int i = 0; i < 1000; i++)
{
Assert.Equal(d["test" + i], i);
d["test" + i] = (int)d["test" + i] + 100;
Assert.Equal(d["test" + i], 100 + i);
}
for (int i = 1000; i < 2000; i++)
{
d["test" + i] = 1337;
}
Assert.Null(d["asdasd"]);
Assert.Throws<ArgumentNullException>(() => { var a = d[null]; });
Assert.Throws<ArgumentNullException>(() => { d[null] = 1337; });
}
// public ICollection Values { get; }
[Fact]
public void ValuesPropertyContainsAllValues()
{
var d = new OrderedDictionary();
var alreadyChecked = new bool[1000];
for (int i = 0; i < 1000; i++)
{
d["foo" + i] = "bar_" + i;
alreadyChecked[i] = false;
}
ICollection values = d.Values;
Assert.False(values.IsSynchronized);
Assert.NotSame(d, values.SyncRoot);
Assert.Equal(d.Count, values.Count);
foreach (var val in values)
{
string sval = (string)val;
var p = sval.Split(new char[] { '_' });
Assert.Equal(2, p.Length);
int number = int.Parse(p[1]);
Assert.False(alreadyChecked[number]);
Assert.True(number >= 0 && number < 1000);
alreadyChecked[number] = true;
}
object[] array = new object[values.Count + 50];
values.CopyTo(array, 50);
for (int i = 50; i < array.Length; i++)
{
Assert.Equal(array[i], "bar_" + (i - 50));
}
AssertExtensions.Throws<ArgumentNullException>("array", () => values.CopyTo(null, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => values.CopyTo(new object[values.Count], -1));
}
// public void Add(object key, object value);
[Fact]
public void AddTests()
{
var d = new OrderedDictionary();
d.Add((int)5, "foo1");
Assert.Equal("foo1", d[(object)((int)5)]);
d.Add((double)5, "foo2");
Assert.Equal("foo2", d[(object)((double)5)]);
d.Add((long)5, "foo3");
Assert.Equal("foo3", d[(object)((long)5)]);
d.Add((short)5, "foo4");
Assert.Equal("foo4", d[(object)((short)5)]);
d.Add((uint)5, "foo5");
Assert.Equal("foo5", d[(object)((uint)5)]);
d.Add("5", "foo6");
Assert.Equal("foo6", d["5"]);
AssertExtensions.Throws<ArgumentException>(null, () => d.Add((int)5, "foo"));
AssertExtensions.Throws<ArgumentException>(null, () => d.Add((double)5, "foo"));
AssertExtensions.Throws<ArgumentException>(null, () => d.Add((long)5, "foo"));
AssertExtensions.Throws<ArgumentException>(null, () => d.Add((short)5, "foo"));
AssertExtensions.Throws<ArgumentException>(null, () => d.Add((uint)5, "foo"));
AssertExtensions.Throws<ArgumentException>(null, () => d.Add("5", "foo"));
Assert.Throws<ArgumentNullException>(() => d.Add(null, "foobar"));
}
// public OrderedDictionary AsReadOnly();
[Fact]
public void AsReadOnlyTests()
{
var _d = new OrderedDictionary();
_d["foo"] = "bar";
_d[(object)13] = 37;
var d = _d.AsReadOnly();
Assert.True(d.IsReadOnly);
Assert.Equal("bar", d["foo"]);
Assert.Equal(37, d[(object)13]);
Assert.Throws<NotSupportedException>(() => { d["foo"] = "moooooooooaaah"; });
Assert.Throws<NotSupportedException>(() => { d["asdasd"] = "moooooooooaaah"; });
Assert.Null(d["asdasd"]);
Assert.Throws<ArgumentNullException>(() => { var a = d[null]; });
}
// public void Clear();
[Fact]
public void ClearTests()
{
var d = new OrderedDictionary();
d.Clear();
Assert.Equal(0, d.Count);
for (int i = 0; i < 1000; i++)
{
d.Add(i, i);
}
d.Clear();
Assert.Equal(0, d.Count);
d.Clear();
Assert.Equal(0, d.Count);
for (int i = 0; i < 1000; i++)
{
d.Add("foo", "bar");
d.Clear();
Assert.Equal(0, d.Count);
}
}
// public bool Contains(object key);
[Fact]
public void ContainsTests()
{
var d = new OrderedDictionary();
Assert.Throws<ArgumentNullException>(() => d.Contains(null));
Assert.False(d.Contains("foo"));
for (int i = 0; i < 1000; i++)
{
var k = "test_" + i;
d.Add(k, "asd");
Assert.True(d.Contains(k));
// different reference
Assert.True(d.Contains("test_" + i));
}
Assert.False(d.Contains("foo"));
}
// public void CopyTo(Array array, int index);
[Fact]
public void CopyToTests()
{
var d = new OrderedDictionary();
d["foo"] = "bar";
d[" "] = "asd";
DictionaryEntry[] arr = new DictionaryEntry[3];
Assert.Throws<ArgumentNullException>(() => d.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => d.CopyTo(arr, -1));
AssertExtensions.Throws<ArgumentException>(null, () => d.CopyTo(arr, 3));
d.CopyTo(arr, 0);
for (int i = 0; i < 2; i++)
{
Assert.True(d.Contains(arr[i].Key));
Assert.Equal(d[arr[i].Key], arr[i].Value);
}
Assert.NotEqual(arr[0].Key, arr[1].Key);
d.CopyTo(arr, 1);
for (int i = 1; i < 3; i++)
{
Assert.True(d.Contains(arr[i].Key));
Assert.Equal(d[arr[i].Key], arr[i].Value);
}
Assert.NotEqual(arr[1].Key, arr[2].Key);
}
[Fact]
public void GetDictionaryEnumeratorTests()
{
var d = new OrderedDictionary();
for (int i = 0; i < 10; i++)
{
d.Add("Key_" + i, "Value_" + i);
}
IDictionaryEnumerator e = d.GetEnumerator();
for (int i = 0; i < 2; i++)
{
int count = 0;
while (e.MoveNext())
{
DictionaryEntry entry1 = (DictionaryEntry)e.Current;
DictionaryEntry entry2 = e.Entry;
Assert.Equal(entry1.Key, entry2.Key);
Assert.Equal(entry1.Value, entry1.Value);
Assert.Equal(e.Key, entry1.Key);
Assert.Equal(e.Value, entry1.Value);
Assert.Equal(e.Value, d[e.Key]);
count++;
}
Assert.Equal(count, d.Count);
Assert.False(e.MoveNext());
e.Reset();
}
e = d.GetEnumerator();
d["foo"] = "bar";
Assert.Throws<InvalidOperationException>(() => e.MoveNext());
}
[Fact]
public void GetEnumeratorTests()
{
var d = new OrderedDictionary();
for (int i = 0; i < 10; i++)
{
d.Add("Key_" + i, "Value_" + i);
}
IEnumerator e = ((ICollection)d).GetEnumerator();
for (int i = 0; i < 2; i++)
{
int count = 0;
while (e.MoveNext())
{
DictionaryEntry entry = (DictionaryEntry)e.Current;
Assert.Equal(entry.Value, d[entry.Key]);
count++;
}
Assert.Equal(count, d.Count);
Assert.False(e.MoveNext());
e.Reset();
}
}
// public void Insert(int index, object key, object value);
[Fact]
public void InsertTests()
{
var d = new OrderedDictionary();
Assert.Throws<ArgumentOutOfRangeException>(() => d.Insert(-1, "foo", "bar"));
Assert.Throws<ArgumentNullException>(() => d.Insert(0, null, "bar"));
Assert.Throws<ArgumentOutOfRangeException>(() => d.Insert(1, "foo", "bar"));
d.Insert(0, "foo", "bar");
Assert.Equal("bar", d["foo"]);
Assert.Equal("bar", d[0]);
AssertExtensions.Throws<ArgumentException>(null, () => d.Insert(0, "foo", "bar"));
d.Insert(0, "aaa", "bbb");
Assert.Equal("bbb", d["aaa"]);
Assert.Equal("bbb", d[0]);
d.Insert(0, "zzz", "ccc");
Assert.Equal("ccc", d["zzz"]);
Assert.Equal("ccc", d[0]);
d.Insert(3, "13", "37");
Assert.Equal("37", d["13"]);
Assert.Equal("37", d[3]);
}
// public void Remove(object key);
[Fact]
public void RemoveTests()
{
var d = new OrderedDictionary();
// should work
d.Remove("asd");
Assert.Throws<ArgumentNullException>(() => d.Remove(null));
for (var i = 0; i < 1000; i++)
{
d.Add("foo_" + i, "bar_" + i);
}
for (var i = 0; i < 1000; i++)
{
Assert.True(d.Contains("foo_" + i));
d.Remove("foo_" + i);
Assert.False(d.Contains("foo_" + i));
Assert.Equal(1000 - i - 1, d.Count);
}
}
// public void RemoveAt(int index);
[Fact]
public void RemoveAtTests()
{
var d = new OrderedDictionary();
Assert.Throws<ArgumentOutOfRangeException>(() => d.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>(() => d.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => d.RemoveAt(5));
Assert.Throws<ArgumentNullException>(() => d.Remove(null));
for (var i = 0; i < 1000; i++)
{
d.Add("foo_" + i, "bar_" + i);
}
for (var i = 0; i < 1000; i++)
{
d.RemoveAt(1000 - i - 1);
Assert.Equal(1000 - i - 1, d.Count);
}
for (var i = 0; i < 1000; i++)
{
d.Add("foo_" + i, "bar_" + i);
}
for (var i = 0; i < 1000; i++)
{
Assert.Equal("bar_" + i, d[0]);
d.RemoveAt(0);
Assert.Equal(1000 - i - 1, d.Count);
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.SS.Util
{
using System;
using System.Text;
using System.Collections;
public class AreaReference
{
/** The Char (!) that Separates sheet names from cell references */
private const char SHEET_NAME_DELIMITER = '!';
/** The Char (:) that Separates the two cell references in a multi-cell area reference */
private const char CELL_DELIMITER = ':';
/** The Char (') used to quote sheet names when they contain special Chars */
private const char SPECIAL_NAME_DELIMITER = '\'';
private CellReference _firstCell;
private CellReference _lastCell;
private bool _isSingleCell;
/**
* Create an area ref from a string representation. Sheet names containing special Chars should be
* delimited and escaped as per normal syntax rules for formulas.<br/>
* The area reference must be contiguous (i.e. represent a single rectangle, not a Union of rectangles)
*/
public AreaReference(String reference)
{
if (!IsContiguous(reference))
{
throw new ArgumentException(
"References passed to the AreaReference must be contiguous, " +
"use generateContiguous(ref) if you have non-contiguous references");
}
String[] parts = SeparateAreaRefs(reference);
String part0 = parts[0];
if (parts.Length == 1)
{
// TODO - probably shouldn't initialize area ref when text is really a cell ref
// Need to fix some named range stuff to get rid of this
_firstCell = new CellReference(part0);
_lastCell = _firstCell;
_isSingleCell = true;
return;
}
if (parts.Length != 2)
{
throw new ArgumentException("Bad area ref '" + reference + "'");
}
String part1 = parts[1];
if (IsPlainColumn(part0))
{
if (!IsPlainColumn(part1))
{
throw new Exception("Bad area ref '" + reference + "'");
}
// Special handling for whole-column references
// Represented internally as x$1 to x$65536
// which is the maximum range of rows
bool firstIsAbs = CellReference.IsPartAbsolute(part0);
bool lastIsAbs = CellReference.IsPartAbsolute(part1);
int col0 = CellReference.ConvertColStringToIndex(part0);
int col1 = CellReference.ConvertColStringToIndex(part1);
_firstCell = new CellReference(0, col0, true, firstIsAbs);
_lastCell = new CellReference(0xFFFF, col1, true, lastIsAbs);
_isSingleCell = false;
// TODO - whole row refs
}
else
{
_firstCell = new CellReference(part0);
_lastCell = new CellReference(part1);
_isSingleCell = part0.Equals(part1);
}
}
private bool IsPlainColumn(String refPart)
{
for (int i = refPart.Length - 1; i >= 0; i--)
{
int ch = refPart[i];
if (ch == '$' && i == 0)
{
continue;
}
if (ch < 'A' || ch > 'Z')
{
return false;
}
}
return true;
}
public static AreaReference GetWholeRow(String start, String end)
{
return new AreaReference("$A" + start + ":$IV" + end);
}
public static AreaReference GetWholeColumn(String start, String end)
{
return new AreaReference(start + "$1:" + end + "$65536");
}
/**
* Creates an area ref from a pair of Cell References.
*/
public AreaReference(CellReference topLeft, CellReference botRight)
{
//_firstCell = topLeft;
//_lastCell = botRight;
//_isSingleCell = false;
bool swapRows = topLeft.Row > botRight.Row;
bool swapCols = topLeft.Col > botRight.Col;
if (swapRows || swapCols)
{
int firstRow;
int lastRow;
int firstColumn;
int lastColumn;
bool firstRowAbs;
bool lastRowAbs;
bool firstColAbs;
bool lastColAbs;
if (swapRows)
{
firstRow = botRight.Row;
firstRowAbs = botRight.IsRowAbsolute;
lastRow = topLeft.Row;
lastRowAbs = topLeft.IsRowAbsolute;
}
else
{
firstRow = topLeft.Row;
firstRowAbs = topLeft.IsRowAbsolute;
lastRow = botRight.Row;
lastRowAbs = botRight.IsRowAbsolute;
}
if (swapCols)
{
firstColumn = botRight.Col;
firstColAbs = botRight.IsColAbsolute;
lastColumn = topLeft.Col;
lastColAbs = topLeft.IsColAbsolute;
}
else
{
firstColumn = topLeft.Col;
firstColAbs = topLeft.IsColAbsolute;
lastColumn = botRight.Col;
lastColAbs = botRight.IsColAbsolute;
}
_firstCell = new CellReference(firstRow, firstColumn, firstRowAbs, firstColAbs);
_lastCell = new CellReference(lastRow, lastColumn, lastRowAbs, lastColAbs);
}
else
{
_firstCell = topLeft;
_lastCell = botRight;
}
_isSingleCell = false;
}
/**
* is the reference for a contiguous (i.e.
* Unbroken) area, or is it made up of
* several different parts?
* (If it Is, you will need to call
* ....
*/
public static bool IsContiguous(String reference)
{
// If there's a sheet name, strip it off
int sheetRefEnd = reference.IndexOf('!');
if (sheetRefEnd != -1)
{
reference = reference.Substring(sheetRefEnd);
}
// Check for the , as a sign of non-coniguous
if (reference.IndexOf(',') == -1)
{
return true;
}
return false;
}
/**
* is the reference for a whole-column reference,
* such as C:C or D:G ?
*/
public static bool IsWholeColumnReference(CellReference topLeft, CellReference botRight)
{
// These are represented as something like
// C$1:C$65535 or D$1:F$0
// i.e. absolute from 1st row to 0th one
if (topLeft.Row == 0 && topLeft.IsRowAbsolute &&
(botRight.Row == -1 || botRight.Row == 65535) && botRight.IsRowAbsolute)
{
return true;
}
return false;
}
public bool IsWholeColumnReference()
{
return IsWholeColumnReference(_firstCell, _lastCell);
}
/**
* Takes a non-contiguous area reference, and
* returns an array of contiguous area references.
*/
public static AreaReference[] GenerateContiguous(String reference)
{
ArrayList refs = new ArrayList();
String st = reference;
string[] token = st.Split(',');
foreach (string t in token)
{
refs.Add(
new AreaReference(t)
);
}
return (AreaReference[])refs.ToArray(typeof(AreaReference));
}
/**
* @return <c>false</c> if this area reference involves more than one cell
*/
public bool IsSingleCell
{
get { return _isSingleCell; }
}
/**
* @return the first cell reference which defines this area. Usually this cell is in the upper
* left corner of the area (but this is not a requirement).
*/
public CellReference FirstCell
{
get { return _firstCell; }
}
/**
* Note - if this area reference refers to a single cell, the return value of this method will
* be identical to that of <c>GetFirstCell()</c>
* @return the second cell reference which defines this area. For multi-cell areas, this is
* cell diagonally opposite the 'first cell'. Usually this cell is in the lower right corner
* of the area (but this is not a requirement).
*/
public CellReference LastCell
{
get{return _lastCell;}
}
/**
* Returns a reference to every cell covered by this area
*/
public CellReference[] GetAllReferencedCells()
{
// Special case for single cell reference
if (_isSingleCell)
{
return new CellReference[] { _firstCell, };
}
// Interpolate between the two
int minRow = Math.Min(_firstCell.Row, _lastCell.Row);
int maxRow = Math.Max(_firstCell.Row, _lastCell.Row);
int minCol = Math.Min(_firstCell.Col, _lastCell.Col);
int maxCol = Math.Max(_firstCell.Col, _lastCell.Col);
String sheetName = _firstCell.SheetName;
ArrayList refs = new ArrayList();
for (int row = minRow; row <= maxRow; row++)
{
for (int col = minCol; col <= maxCol; col++)
{
CellReference ref1 = new CellReference(sheetName, row, col, _firstCell.IsRowAbsolute, _firstCell.IsColAbsolute);
refs.Add(ref1);
}
}
return (CellReference[])refs.ToArray(typeof(CellReference));
}
/**
* Example return values:
* <table border="0" cellpAdding="1" cellspacing="0" summary="Example return values">
* <tr><th align='left'>Result</th><th align='left'>Comment</th></tr>
* <tr><td>A1:A1</td><td>Single cell area reference without sheet</td></tr>
* <tr><td>A1:$C$1</td><td>Multi-cell area reference without sheet</td></tr>
* <tr><td>Sheet1!A$1:B4</td><td>Standard sheet name</td></tr>
* <tr><td>'O''Brien''s Sales'!B5:C6' </td><td>Sheet name with special Chars</td></tr>
* </table>
* @return the text representation of this area reference as it would appear in a formula.
*/
public String FormatAsString()
{
// Special handling for whole-column references
if (IsWholeColumnReference())
{
return
CellReference.ConvertNumToColString(_firstCell.Col)
+ ":" +
CellReference.ConvertNumToColString(_lastCell.Col);
}
StringBuilder sb = new StringBuilder(32);
sb.Append(_firstCell.FormatAsString());
if (!_isSingleCell)
{
sb.Append(CELL_DELIMITER);
if (_lastCell.SheetName == null)
{
sb.Append(_lastCell.FormatAsString());
}
else
{
// don't want to include the sheet name twice
_lastCell.AppendCellReference(sb);
}
}
return sb.ToString();
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(this.GetType().Name).Append(" [");
sb.Append(FormatAsString());
sb.Append("]");
return sb.ToString();
}
/**
* Separates Area refs in two parts and returns them as Separate elements in a String array,
* each qualified with the sheet name (if present)
*
* @return array with one or two elements. never <c>null</c>
*/
private static String[] SeparateAreaRefs(String reference)
{
// TODO - refactor cell reference parsing logic to one place.
// Current known incarnations:
// FormulaParser.Name
// CellReference.SeparateRefParts()
// AreaReference.SeparateAreaRefs() (here)
// SheetNameFormatter.format() (inverse)
int len = reference.Length;
int delimiterPos = -1;
bool insideDelimitedName = false;
for (int i = 0; i < len; i++)
{
switch (reference[i])
{
case CELL_DELIMITER:
if (!insideDelimitedName)
{
if (delimiterPos >= 0)
{
throw new ArgumentException("More than one cell delimiter '"
+ CELL_DELIMITER + "' appears in area reference '" + reference + "'");
}
delimiterPos = i;
}
continue;
case SPECIAL_NAME_DELIMITER:
// fall through
break;
default:
continue;
}
if (!insideDelimitedName)
{
insideDelimitedName = true;
continue;
}
if (i >= len - 1)
{
// reference ends with the delimited name.
// Assume names like: "Sheet1!'A1'" are never legal.
throw new ArgumentException("Area reference '" + reference
+ "' ends with special name delimiter '" + SPECIAL_NAME_DELIMITER + "'");
}
if (reference[i + 1] == SPECIAL_NAME_DELIMITER)
{
// two consecutive quotes is the escape sequence for a single one
i++; // skip this and keep parsing the special name
}
else
{
// this is the end of the delimited name
insideDelimitedName = false;
}
}
if (delimiterPos < 0)
{
return new String[] { reference, };
}
String partA = reference.Substring(0, delimiterPos);
String partB = reference.Substring(delimiterPos + 1);
if (partB.IndexOf(SHEET_NAME_DELIMITER) >= 0)
{
// TODO - are references like "Sheet1!A1:Sheet1:B2" ever valid?
// FormulaParser has code to handle that.
throw new Exception("Unexpected " + SHEET_NAME_DELIMITER
+ " in second cell reference of '" + reference + "'");
}
int plingPos = partA.LastIndexOf(SHEET_NAME_DELIMITER);
if (plingPos < 0)
{
return new String[] { partA, partB, };
}
String sheetName = partA.Substring(0, plingPos + 1); // +1 to include delimiter
return new String[] { partA, sheetName + partB, };
}
}
}
| |
// JsonString.cs
//
// Copyright (C) 2006 Andy Kernahan
//
// 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
using System;
using System.Text;
using System.Diagnostics;
using System.Globalization;
namespace NetServ.Net.Json
{
/// <summary>
/// Represents a JavaScript Object Notation String data type. This class cannot
/// be inherited.
/// </summary>
[Serializable()]
[DebuggerDisplay("{_value}")]
public sealed class JsonString : JsonTypeSkeleton, IJsonString
{
#region Private Fields.
private string _encodedValue;
private readonly string _value;
private static readonly char[] QUOTE_CHARS = { '"', '/', '\\', '\b', '\f', '\n', '\r', '\t' };
#endregion
#region Public Interface.
/// <summary>
/// Defines an empty JsonString. This field is readonly.
/// </summary>
public static readonly JsonString Empty = new JsonString(string.Empty);
/// <summary>
/// Initialises a new instance of the JsonString class and specifies the
/// value.
/// </summary>
/// <param name="value">The value of the instance.</param>
public JsonString(string value)
: base(JsonTypeCode.String) {
if(value == null)
throw new ArgumentNullException("value");
_value = value;
}
/// <summary>
/// Writes the contents of this Json type using the specified
/// <see cref="NetServ.Net.Json.IJsonWriter"/>.
/// </summary>
/// <param name="writer">The Json writer.</param>
public override void Write(IJsonWriter writer) {
if(writer == null)
throw new ArgumentNullException("writer");
writer.WriteValue(this.EncodedValue);
}
/// <summary>
/// Returns a <see cref="System.String"/> representation of this JsonString
/// instance.
/// </summary>
/// <returns> <see cref="System.String"/> representation of this JsonString
/// instance.</returns>
public override string ToString() {
return this.Value;
}
/// <summary>
/// Returns a indicating whether this instance is equal to the specified
/// <see cref="System.Object"/>.
/// </summary>
/// <param name="obj">The object to compare.</param>
/// <returns>True if the specified object is equal to this instance, otherwise;
/// false.</returns>
public override bool Equals(object obj) {
if(obj == null)
return false;
if(obj.GetType() != GetType())
return false;
return Equals((JsonString)obj);
}
/// <summary>
/// Returns a indicating whether this instance is equal to the specified
/// JsonString.
/// </summary>
/// <param name="other">The value to compare.</param>
/// <returns>True if the specified instance is equal to this instance, otherwise;
/// false.</returns>
public bool Equals(JsonString other) {
return other != null && Equals(other.Value);
}
/// <summary>
/// Returns a indicating whether this instance is equal to the specified
/// <see cref="NetServ.Net.Json.IJsonString"/>.
/// </summary>
/// <param name="other">The value to compare.</param>
/// <returns>True if the specified instance is equal to this instance, otherwise;
/// false.</returns>
public bool Equals(IJsonString other) {
return other != null && Equals(other.Value);
}
/// <summary>
/// Returns a indicating whether this instance is equal to the specified
/// <see cref="System.String"/>.
/// </summary>
/// <param name="other">The value to compare.</param>
/// <returns>True if the specified instance is equal to this instance, otherwise;
/// false.</returns>
public bool Equals(string other) {
return this.Value.Equals(other);
}
/// <summary>
/// Returns a value indicating equality with the specified instance.
/// </summary>
/// <param name="other">The JsonNumber to compare.</param>
/// <returns></returns>
public int CompareTo(JsonString other) {
return other != null ? this.Value.CompareTo(other.Value) : -1;
}
/// <summary>
/// Returns a value indicating equality with the specified
/// <see cref="NetServ.Net.Json.IJsonString"/>.
/// </summary>
/// <param name="other">The <see cref="NetServ.Net.Json.IJsonString"/> to
/// compare.</param>
/// <returns></returns>
public int CompareTo(IJsonString other) {
return other != null ? this.Value.CompareTo(other.Value) : -1;
}
/// <summary>
/// Returns a value indicating equality with the specified <see cref="System.String"/>.
/// </summary>
/// <param name="other">The String to compare.</param>
/// <returns></returns>
public int CompareTo(string other) {
return this.Value.CompareTo(other);
}
/// <summary>
/// Returns a hash code for this JsonString.
/// </summary>
/// <returns>A hash code for this JsonString.</returns>
public override int GetHashCode() {
return this.Value.GetHashCode();
}
/// <summary>
/// Gets the un-encoded value of the this JsonString.
/// </summary>
public string Value {
get { return _value; }
}
/// <summary>
/// Gets the encoded value of this JsonString.
/// </summary>
public string EncodedValue {
get {
if(_encodedValue == null)
_encodedValue = JsonString.Encode(this.Value);
return _encodedValue;
}
}
/// <summary>
/// Determines if the two <see cref="NetServ.Net.Json.JsonString"/>s are
/// equal.
/// </summary>
/// <param name="a">The first JsonString.</param>
/// <param name="b">The second JsonString.</param>
/// <returns>True if the JsonStrings are equal, otherwise; false.</returns>
public static bool Equals(JsonString a, JsonString b) {
object ao = a;
object bo = b;
if(ao == bo)
return true;
if(ao == null || bo == null)
return false;
return a.Equals(b.Value);
}
/// <summary>
/// Equality operator.
/// </summary>
/// <param name="a">The first JsonString.</param>
/// <param name="b">The second JsonString.</param>
/// <returns>True if the JsonStrings are equal, otherwise; false.</returns>
public static bool operator ==(JsonString a, JsonString b) {
return JsonString.Equals(a, b);
}
/// <summary>
/// Inequality operator.
/// </summary>
/// <param name="a">The first JsonString.</param>
/// <param name="b">The second JsonString.</param>
/// <returns>True if the JsonStrings are not equal, otherwise; false.</returns>
public static bool operator !=(JsonString a, JsonString b) {
return !JsonString.Equals(a, b);
}
/// <summary>
/// Implicit conversion operator.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>The converted value.</returns>
public static implicit operator JsonString(string value) {
if(value == null)
return null;
if(value.Equals(string.Empty))
return JsonString.Empty;
return new JsonString(value);
}
/// <summary>
/// Implicit conversion operator.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>This method always returns null.</returns>
public static implicit operator JsonString(JsonNull value) {
return null;
}
/// <summary>
/// Explicit conversion operator.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator string(JsonString value) {
return value != null ? value.Value : null;
}
/// <summary>
/// Encodes the specified <see cref="System.String"/>.
/// </summary>
/// <param name="s">The string to encode.</param>
/// <returns>The encoded string.</returns>
public static string Encode(string s) {
if(s == null)
throw new ArgumentNullException("s");
if(s.Equals(string.Empty) || !JsonString.ShouldEncode(s))
return string.Concat("\"", s, "\"");
char ch;
StringBuilder sb = new StringBuilder(s.Length);
sb.Append('"');
for(int i = 0; i < s.Length; ++i) {
ch = s[i];
switch(ch) {
case '"':
sb.Append(@"\""");
break;
case '/':
sb.Append(@"\/");
break;
case '\\':
sb.Append(@"\\");
break;
case '\b':
sb.Append(@"\b");
break;
case '\f':
sb.Append(@"\f");
break;
case '\n':
sb.Append(@"\n");
break;
case '\r':
sb.Append(@"\r");
break;
case '\t':
sb.Append(@"\t");
break;
default:
if(ch > 0x7F)
// TODO: MUST add support for UTF-16.
sb.AppendFormat(@"\u{0}", ((int)ch).ToString("X4"));
else
sb.Append(ch);
break;
}
}
sb.Append('"');
return sb.ToString();
}
#endregion
#region Private Impl.
private static bool ShouldEncode(string s) {
for(int i = 0; i < s.Length; ++i) {
if(s[i] > 0x7F || Array.IndexOf(JsonString.QUOTE_CHARS, s[i]) > -1)
return true;
}
return false;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
public class FlurryAgent : IDisposable
{
private static FlurryAgent _instance;
public static FlurryAgent Instance
{
get
{
if(_instance == null) _instance = new FlurryAgent();
return _instance;
}
}
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport("__Internal")]
private static extern void mStartSession(string apiKey);
[DllImport("__Internal")]
private static extern void mLogEvent(string eventId, bool timed);
[DllImport("__Internal")]
private static extern void mLogEventWithParams(string eventId, string keyList, string valueList, bool timed);
[DllImport("__Internal")]
private static extern void mEndTimedEvent(string eventId);
[DllImport("__Internal")]
private static extern void mStopSession();
public void onStartSession(string apiKey){
mStartSession(apiKey);
}
public void onEndSession(){
mStopSession();
}
public void logEvent(string eventId, bool timed=false){
mLogEvent(eventId, timed);
}
public void setContinueSessionMillis(long milliseconds){}
public void onError(string errorId, string message, string errorClass){}
public void onPageView(){}
public void setLogEnabled(bool enabled){}
public void setUserID(string userId){}
public void setAge(int age){}
public void setReportLocation(bool reportLocation){}
public void logEvent(string eventId, Dictionary<string, string> parameters, bool timed=false)
{
if(parameters.Count == 0)
{
return;
}
mLogEventWithParams(eventId,
string.Join("|||", new List<string>(parameters.Keys).ToArray()),
string.Join("|||", new List<string>(parameters.Values).ToArray()), timed);
}
public void endTimedEvent(string eventId)
{
mEndTimedEvent(eventId);
}
public void Dispose(){}
#elif UNITY_ANDROID && !UNITY_EDITOR
private AndroidJavaClass cls_FlurryAgent = new AndroidJavaClass("com.flurry.android.FlurryAgent");
public void onStartSession(string apiKey)
{
using(AndroidJavaClass cls_UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
using(AndroidJavaObject obj_Activity = cls_UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
{
cls_FlurryAgent.CallStatic("onStartSession", obj_Activity, apiKey);
}
}
}
public void onEndSession()
{
using(AndroidJavaClass cls_UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
using(AndroidJavaObject obj_Activity = cls_UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
{
cls_FlurryAgent.CallStatic("onEndSession", obj_Activity);
}
}
}
public void logEvent(string eventId, bool timed = false)
{
if(timed)
{
cls_FlurryAgent.CallStatic("logEvent", eventId, timed);
}
else
{
cls_FlurryAgent.CallStatic("logEvent", eventId);
}
}
public void setContinueSessionMillis(long milliseconds)
{
cls_FlurryAgent.CallStatic("setContinueSessionMillis", milliseconds);
}
public void onError(string errorId, string message, string errorClass)
{
cls_FlurryAgent.CallStatic("onError", errorId, message, errorClass);
}
public void onPageView()
{
cls_FlurryAgent.CallStatic("onPageView");
}
public void setLogEnabled(bool enabled)
{
cls_FlurryAgent.CallStatic("setLogEnabled", enabled);
}
public void setUserID(string userId)
{
cls_FlurryAgent.CallStatic("setUserID", userId);
}
public void setAge(int age)
{
cls_FlurryAgent.CallStatic("setAge", age);
}
/*
// Not working, and I don't need it, so I'm not going to worry about it
private static AndroidJavaClass cls_FlurryAgentConstants = new AndroidJavaClass("com.flurry.android.FlurryAgent.Constants");
public enum Gender
{
Male,
Female
}
public void setGender(Gender gender)
{
byte javaGender = (gender == Gender.Male ? cls_FlurryAgentConstants.Get<byte>("MALE") : cls_FlurryAgentConstants.Get<byte>("FEMALE"));
cls_FlurryAgent.CallStatic("setGender", javaGender);
}
*/
public void setReportLocation(bool reportLocation)
{
cls_FlurryAgent.CallStatic("setReportLocation", reportLocation);
}
public void logEvent(string eventId, Dictionary<string, string> parameters, bool timed = false)
{
using(AndroidJavaObject obj_HashMap = new AndroidJavaObject("java.util.HashMap"))
{
// Call 'put' via the JNI instead of using helper classes to avoid:
// "JNI: Init'd AndroidJavaObject with null ptr!"
IntPtr method_Put = AndroidJNIHelper.GetMethodID(obj_HashMap.GetRawClass(), "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
object[] args = new object[2];
foreach(KeyValuePair<string, string> kvp in parameters)
{
using(AndroidJavaObject k = new AndroidJavaObject("java.lang.String", kvp.Key))
{
using(AndroidJavaObject v = new AndroidJavaObject("java.lang.String", kvp.Value))
{
args[0] = k;
args[1] = v;
AndroidJNI.CallObjectMethod(obj_HashMap.GetRawObject(),
method_Put, AndroidJNIHelper.CreateJNIArgArray(args));
}
}
}
if(timed)
{
cls_FlurryAgent.CallStatic("logEvent", eventId, obj_HashMap, timed);
}
else
{
cls_FlurryAgent.CallStatic("logEvent", eventId, obj_HashMap);
}
}
}
public void endTimedEvent(string eventId)
{
cls_FlurryAgent.CallStatic("endTimedEvent", eventId);
}
public void Dispose()
{
cls_FlurryAgent.Dispose();
}
#else
public void onStartSession(string apiKey){}
public void onEndSession(){}
public void logEvent(string eventId, bool timed=false){}
public void setContinueSessionMillis(long milliseconds){}
public void onError(string errorId, string message, string errorClass){}
public void onPageView(){}
public void setLogEnabled(bool enabled){}
public void setUserID(string userId){}
public void setAge(int age){}
public void setReportLocation(bool reportLocation){}
public void logEvent(string eventId, Dictionary<string, string> parameters, bool timed=false){}
public void endTimedEvent(string eventId) {}
public void Dispose(){}
#endif
};
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// Section 5.2.5.4. Cancel of resupply by either the receiving or supplying entity
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
public partial class ResupplyCancelPdu : LogisticsPdu, IEquatable<ResupplyCancelPdu>
{
/// <summary>
/// Entity that is receiving service
/// </summary>
private EntityID _receivingEntityID = new EntityID();
/// <summary>
/// Entity that is supplying
/// </summary>
private EntityID _supplyingEntityID = new EntityID();
/// <summary>
/// Initializes a new instance of the <see cref="ResupplyCancelPdu"/> class.
/// </summary>
public ResupplyCancelPdu()
{
PduType = (byte)8;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(ResupplyCancelPdu left, ResupplyCancelPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(ResupplyCancelPdu left, ResupplyCancelPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._receivingEntityID.GetMarshalledSize(); // this._receivingEntityID
marshalSize += this._supplyingEntityID.GetMarshalledSize(); // this._supplyingEntityID
return marshalSize;
}
/// <summary>
/// Gets or sets the Entity that is receiving service
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "receivingEntityID")]
public EntityID ReceivingEntityID
{
get
{
return this._receivingEntityID;
}
set
{
this._receivingEntityID = value;
}
}
/// <summary>
/// Gets or sets the Entity that is supplying
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "supplyingEntityID")]
public EntityID SupplyingEntityID
{
get
{
return this._supplyingEntityID;
}
set
{
this._supplyingEntityID = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._receivingEntityID.Marshal(dos);
this._supplyingEntityID.Marshal(dos);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._receivingEntityID.Unmarshal(dis);
this._supplyingEntityID.Unmarshal(dis);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<ResupplyCancelPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<receivingEntityID>");
this._receivingEntityID.Reflection(sb);
sb.AppendLine("</receivingEntityID>");
sb.AppendLine("<supplyingEntityID>");
this._supplyingEntityID.Reflection(sb);
sb.AppendLine("</supplyingEntityID>");
sb.AppendLine("</ResupplyCancelPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as ResupplyCancelPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(ResupplyCancelPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._receivingEntityID.Equals(obj._receivingEntityID))
{
ivarsEqual = false;
}
if (!this._supplyingEntityID.Equals(obj._supplyingEntityID))
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._receivingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._supplyingEntityID.GetHashCode();
return result;
}
}
}
| |
using J2N.Runtime.CompilerServices;
using YAF.Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace YAF.Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IBits = YAF.Lucene.Net.Util.IBits;
/// <summary>
/// An <see cref="AtomicReader"/> which reads multiple, parallel indexes. Each index
/// added must have the same number of documents, but typically each contains
/// different fields. Deletions are taken from the first reader.
/// Each document contains the union of the fields of all documents
/// with the same document number. When searching, matches for a
/// query term are from the first index added that has the field.
///
/// <para/>This is useful, e.g., with collections that have large fields which
/// change rarely and small fields that change more frequently. The smaller
/// fields may be re-indexed in a new index and both indexes may be searched
/// together.
///
/// <para/><strong>Warning:</strong> It is up to you to make sure all indexes
/// are created and modified the same way. For example, if you add
/// documents to one index, you need to add the same documents in the
/// same order to the other indexes. <em>Failure to do so will result in
/// undefined behavior</em>.
/// </summary>
public class ParallelAtomicReader : AtomicReader
{
private void InitializeInstanceFields()
{
fields = new ParallelFields(this);
}
private readonly FieldInfos fieldInfos;
private ParallelFields fields;
private readonly AtomicReader[] parallelReaders, storedFieldsReaders;
private readonly ISet<AtomicReader> completeReaderSet = new JCG.HashSet<AtomicReader>(IdentityEqualityComparer<AtomicReader>.Default);
private readonly bool closeSubReaders;
private readonly int maxDoc, numDocs;
private readonly bool hasDeletions;
// LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java
private readonly IDictionary<string, AtomicReader> fieldToReader = new JCG.SortedDictionary<string, AtomicReader>(StringComparer.Ordinal);
private readonly IDictionary<string, AtomicReader> tvFieldToReader = new JCG.SortedDictionary<string, AtomicReader>(StringComparer.Ordinal);
/// <summary>
/// Create a <see cref="ParallelAtomicReader"/> based on the provided
/// readers; auto-disposes the given <paramref name="readers"/> on <see cref="IndexReader.Dispose()"/>.
/// </summary>
public ParallelAtomicReader(params AtomicReader[] readers)
: this(true, readers)
{
}
/// <summary>
/// Create a <see cref="ParallelAtomicReader"/> based on the provided
/// <paramref name="readers"/>.
/// </summary>
public ParallelAtomicReader(bool closeSubReaders, params AtomicReader[] readers)
: this(closeSubReaders, readers, readers)
{
}
/// <summary>
/// Expert: create a <see cref="ParallelAtomicReader"/> based on the provided
/// <paramref name="readers"/> and <paramref name="storedFieldsReaders"/>; when a document is
/// loaded, only <paramref name="storedFieldsReaders"/> will be used.
/// </summary>
public ParallelAtomicReader(bool closeSubReaders, AtomicReader[] readers, AtomicReader[] storedFieldsReaders)
{
InitializeInstanceFields();
this.closeSubReaders = closeSubReaders;
if (readers.Length == 0 && storedFieldsReaders.Length > 0)
{
throw new System.ArgumentException("There must be at least one main reader if storedFieldsReaders are used.");
}
this.parallelReaders = (AtomicReader[])readers.Clone();
this.storedFieldsReaders = (AtomicReader[])storedFieldsReaders.Clone();
if (parallelReaders.Length > 0)
{
AtomicReader first = parallelReaders[0];
this.maxDoc = first.MaxDoc;
this.numDocs = first.NumDocs;
this.hasDeletions = first.HasDeletions;
}
else
{
this.maxDoc = this.numDocs = 0;
this.hasDeletions = false;
}
completeReaderSet.UnionWith(this.parallelReaders);
completeReaderSet.UnionWith(this.storedFieldsReaders);
// check compatibility:
foreach (AtomicReader reader in completeReaderSet)
{
if (reader.MaxDoc != maxDoc)
{
throw new System.ArgumentException("All readers must have same MaxDoc: " + maxDoc + "!=" + reader.MaxDoc);
}
}
// TODO: make this read-only in a cleaner way?
FieldInfos.Builder builder = new FieldInfos.Builder();
// build FieldInfos and fieldToReader map:
foreach (AtomicReader reader in this.parallelReaders)
{
FieldInfos readerFieldInfos = reader.FieldInfos;
foreach (FieldInfo fieldInfo in readerFieldInfos)
{
// NOTE: first reader having a given field "wins":
if (!fieldToReader.ContainsKey(fieldInfo.Name))
{
builder.Add(fieldInfo);
fieldToReader[fieldInfo.Name] = reader;
if (fieldInfo.HasVectors)
{
tvFieldToReader[fieldInfo.Name] = reader;
}
}
}
}
fieldInfos = builder.Finish();
// build Fields instance
foreach (AtomicReader reader in this.parallelReaders)
{
Fields readerFields = reader.Fields;
if (readerFields != null)
{
foreach (string field in readerFields)
{
// only add if the reader responsible for that field name is the current:
if (fieldToReader[field].Equals(reader))
{
this.fields.AddField(field, readerFields.GetTerms(field));
}
}
}
}
// do this finally so any Exceptions occurred before don't affect refcounts:
foreach (AtomicReader reader in completeReaderSet)
{
if (!closeSubReaders)
{
reader.IncRef();
}
reader.RegisterParentReader(this);
}
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder("ParallelAtomicReader(");
bool removeLastCommaSpace = false;
foreach (AtomicReader reader in completeReaderSet)
{
buffer.Append(reader);
buffer.Append(", ");
removeLastCommaSpace = true;
}
if (removeLastCommaSpace)
{
buffer.Remove(buffer.Length - 2, 2);
}
return buffer.Append(')').ToString();
}
// Single instance of this, per ParallelReader instance
private sealed class ParallelFields : Fields
{
private readonly ParallelAtomicReader outerInstance;
// LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java
internal readonly IDictionary<string, Terms> fields = new JCG.SortedDictionary<string, Terms>(StringComparer.Ordinal);
internal ParallelFields(ParallelAtomicReader outerInstance)
{
this.outerInstance = outerInstance;
}
internal void AddField(string fieldName, Terms terms)
{
fields[fieldName] = terms;
}
public override IEnumerator<string> GetEnumerator()
{
return fields.Keys.GetEnumerator();
}
public override Terms GetTerms(string field)
{
Terms result;
fields.TryGetValue(field, out result);
return result;
}
public override int Count
{
get { return fields.Count; }
}
}
/// <summary>
/// Get the <see cref="Index.FieldInfos"/> describing all fields in
/// this reader.
/// <para/>
/// NOTE: the returned field numbers will likely not
/// correspond to the actual field numbers in the underlying
/// readers, and codec metadata (<see cref="FieldInfo.GetAttribute(string)"/>
/// will be unavailable.
/// </summary>
public override FieldInfos FieldInfos
{
get
{
return fieldInfos;
}
}
public override IBits LiveDocs
{
get
{
EnsureOpen();
return hasDeletions ? parallelReaders[0].LiveDocs : null;
}
}
public override Fields Fields
{
get
{
EnsureOpen();
return fields;
}
}
public override int NumDocs
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return numDocs;
}
}
public override int MaxDoc
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return maxDoc;
}
}
public override void Document(int docID, StoredFieldVisitor visitor)
{
EnsureOpen();
foreach (AtomicReader reader in storedFieldsReaders)
{
reader.Document(docID, visitor);
}
}
public override Fields GetTermVectors(int docID)
{
EnsureOpen();
ParallelFields fields = null;
foreach (KeyValuePair<string, AtomicReader> ent in tvFieldToReader/*.EntrySet()*/)
{
string fieldName = ent.Key;
Terms vector = ent.Value.GetTermVector(docID, fieldName);
if (vector != null)
{
if (fields == null)
{
fields = new ParallelFields(this);
}
fields.AddField(fieldName, vector);
}
}
return fields;
}
protected internal override void DoClose()
{
lock (this)
{
IOException ioe = null;
foreach (AtomicReader reader in completeReaderSet)
{
try
{
if (closeSubReaders)
{
reader.Dispose();
}
else
{
reader.DecRef();
}
}
catch (IOException e)
{
if (ioe == null)
{
ioe = e;
}
}
}
// throw the first exception
if (ioe != null)
{
throw ioe;
}
}
}
public override NumericDocValues GetNumericDocValues(string field)
{
EnsureOpen();
AtomicReader reader;
return fieldToReader.TryGetValue(field, out reader) ? reader.GetNumericDocValues(field) : null;
}
public override BinaryDocValues GetBinaryDocValues(string field)
{
EnsureOpen();
AtomicReader reader;
return fieldToReader.TryGetValue(field, out reader) ? reader.GetBinaryDocValues(field) : null;
}
public override SortedDocValues GetSortedDocValues(string field)
{
EnsureOpen();
AtomicReader reader;
return fieldToReader.TryGetValue(field, out reader) ? reader.GetSortedDocValues(field) : null;
}
public override SortedSetDocValues GetSortedSetDocValues(string field)
{
EnsureOpen();
AtomicReader reader;
return fieldToReader.TryGetValue(field, out reader) ? reader.GetSortedSetDocValues(field) : null;
}
public override IBits GetDocsWithField(string field)
{
EnsureOpen();
AtomicReader reader;
return fieldToReader.TryGetValue(field, out reader) ? reader.GetDocsWithField(field) : null;
}
public override NumericDocValues GetNormValues(string field)
{
EnsureOpen();
AtomicReader reader;
NumericDocValues values = null;
if (fieldToReader.TryGetValue(field, out reader))
{
values = reader.GetNormValues(field);
}
return values;
}
public override void CheckIntegrity()
{
EnsureOpen();
foreach (AtomicReader reader in completeReaderSet)
{
reader.CheckIntegrity();
}
}
}
}
| |
// QuickGraph Library
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// QuickGraph Library HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
using System;
namespace QuickGraph.Algorithms
{
using System.Collections;
using QuickGraph.Concepts;
using QuickGraph.Concepts.Traversals;
using QuickGraph.Collections;
using QuickGraph.Algorithms.Search;
/// <summary>
/// Computes the graph strong components.
/// </summary>
/// <remarks>
/// This class compute the strongly connected
/// components of a directed graph using Tarjan's algorithm based on DFS.
/// </remarks>
public class StrongComponentsAlgorithm
{
private IVertexListGraph visitedGraph;
private VertexIntDictionary components;
private VertexIntDictionary discoverTimes;
private VertexVertexDictionary roots;
private Stack stack;
int count;
int dfsTime;
/// <summary>
/// Construct a strong component algorithm
/// </summary>
/// <param name="g">graph to apply algorithm on</param>
/// <exception cref="ArgumentNullException">graph is null</exception>
public StrongComponentsAlgorithm(IVertexListGraph g)
{
if (g==null)
throw new ArgumentNullException("g");
this.visitedGraph = g;
this.components = new VertexIntDictionary();
this.roots = new VertexVertexDictionary();
this.discoverTimes = new VertexIntDictionary();
this.stack = new Stack();
this.count = 0;
this.dfsTime = 0;
}
/// <summary>
/// Construct a strong component algorithm
/// </summary>
/// <param name="g">graph to apply algorithm on</param>
/// <param name="components">component map to record results</param>
/// <exception cref="ArgumentNullException">graph is null</exception>
public StrongComponentsAlgorithm(
IVertexListGraph g,
VertexIntDictionary components)
{
if (g==null)
throw new ArgumentNullException("g");
if (components==null)
throw new ArgumentNullException("components");
this.visitedGraph = g;
this.components = components;
this.roots = new VertexVertexDictionary();
this.discoverTimes = new VertexIntDictionary();
this.stack = new Stack();
this.count = 0;
this.dfsTime = 0;
}
/// <summary>
/// Visited graph
/// </summary>
public IVertexListGraph VisitedGraph
{
get
{
return this.visitedGraph;
}
}
/// <summary>
/// Component map
/// </summary>
public VertexIntDictionary Components
{
get
{
return this.components;
}
}
/// <summary>
/// Root map
/// </summary>
public VertexVertexDictionary Roots
{
get
{
return this.roots;
}
}
/// <summary>
/// Vertex discory times
/// </summary>
public VertexIntDictionary DiscoverTimes
{
get
{
return this.discoverTimes;
}
}
/// <summary>
/// Gets the number of strongly connected components in the graph
/// </summary>
/// <value>
/// Number of strongly connected components
/// </value>
public int Count
{
get
{
return this.count;
}
}
/// <summary>
/// Used internally
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void DiscoverVertex(Object sender, VertexEventArgs args)
{
IVertex v = args.Vertex;
this.Roots[v]=v;
this.Components[v]=int.MaxValue;
this.DiscoverTimes[v]=dfsTime++;
this.stack.Push(v);
}
/// <summary>
/// Used internally
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void FinishVertex(Object sender, VertexEventArgs args)
{
IVertex v = args.Vertex;
foreach(IEdge e in VisitedGraph.OutEdges(v))
{
IVertex w = e.Target;
if (this.Components[w] == int.MaxValue)
this.Roots[v]=MinDiscoverTime(this.Roots[v], this.Roots[w]);
}
if (Roots[v] == v)
{
IVertex w=null;
do
{
w = (IVertex)this.stack.Peek();
this.stack.Pop();
this.Components[w]=count;
}
while (w != v);
++count;
}
}
internal IVertex MinDiscoverTime(IVertex u, IVertex v)
{
if (this.DiscoverTimes[u]<this.DiscoverTimes[v])
return u;
else
return v;
}
/// <summary>
/// Executes the algorithm
/// </summary>
/// <remarks>
/// The output of the algorithm is recorded in the component property
/// Components, which will contain numbers giving the component ID
/// assigned to each vertex.
/// </remarks>
/// <returns>The number of components is the return value of the function.</returns>
public int Compute()
{
this.Components.Clear();
this.Roots.Clear();
this.DiscoverTimes.Clear();
count = 0;
dfsTime = 0;
DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(VisitedGraph);
dfs.DiscoverVertex += new VertexEventHandler(this.DiscoverVertex);
dfs.FinishVertex += new VertexEventHandler(this.FinishVertex);
dfs.Compute();
return count;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using gciv = Google.Cloud.Iam.V1;
using lro = Google.LongRunning;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.ResourceManager.V3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedFoldersClientTest
{
[xunit::FactAttribute]
public void GetFolderRequestObject()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFolderRequest request = new GetFolderRequest
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
};
Folder expectedResponse = new Folder
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
Parent = "parent7858e4d0",
DisplayName = "display_name137f65c2",
State = Folder.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFolder(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
Folder response = client.GetFolder(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFolderRequestObjectAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFolderRequest request = new GetFolderRequest
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
};
Folder expectedResponse = new Folder
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
Parent = "parent7858e4d0",
DisplayName = "display_name137f65c2",
State = Folder.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFolderAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Folder>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
Folder responseCallSettings = await client.GetFolderAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Folder responseCancellationToken = await client.GetFolderAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFolder()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFolderRequest request = new GetFolderRequest
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
};
Folder expectedResponse = new Folder
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
Parent = "parent7858e4d0",
DisplayName = "display_name137f65c2",
State = Folder.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFolder(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
Folder response = client.GetFolder(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFolderAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFolderRequest request = new GetFolderRequest
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
};
Folder expectedResponse = new Folder
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
Parent = "parent7858e4d0",
DisplayName = "display_name137f65c2",
State = Folder.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFolderAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Folder>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
Folder responseCallSettings = await client.GetFolderAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Folder responseCancellationToken = await client.GetFolderAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFolderResourceNames()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFolderRequest request = new GetFolderRequest
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
};
Folder expectedResponse = new Folder
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
Parent = "parent7858e4d0",
DisplayName = "display_name137f65c2",
State = Folder.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFolder(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
Folder response = client.GetFolder(request.FolderName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFolderResourceNamesAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFolderRequest request = new GetFolderRequest
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
};
Folder expectedResponse = new Folder
{
FolderName = gagr::FolderName.FromFolder("[FOLDER]"),
Parent = "parent7858e4d0",
DisplayName = "display_name137f65c2",
State = Folder.Types.State.Unspecified,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
DeleteTime = new wkt::Timestamp(),
Etag = "etage8ad7218",
};
mockGrpcClient.Setup(x => x.GetFolderAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Folder>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
Folder responseCallSettings = await client.GetFolderAsync(request.FolderName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Folder responseCancellationToken = await client.GetFolderAsync(request.FolderName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicy()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request.Resource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyResourceNames()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request.ResourceAsResourceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyResourceNamesAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.ResourceAsResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.ResourceAsResourceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicy()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request.Resource, request.Policy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.Resource, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Resource, request.Policy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyResourceNames()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request.ResourceAsResourceName, request.Policy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyResourceNamesAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.Resource, request.Permissions);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsResourceNames()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.ResourceAsResourceName, request.Permissions);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsResourceNamesAsync()
{
moq::Mock<Folders.FoldersClient> mockGrpcClient = new moq::Mock<Folders.FoldersClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
FoldersClient client = new FoldersClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.IO;
using SFML.Window;
using SFML.System;
namespace SFML
{
namespace Audio
{
////////////////////////////////////////////////////////////
/// <summary>
/// Storage for audio samples defining a sound
/// </summary>
////////////////////////////////////////////////////////////
public class SoundBuffer : ObjectBase
{
////////////////////////////////////////////////////////////
/// <summary>
/// Construct a sound buffer from a file
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
/// </summary>
/// <param name="filename">Path of the sound file to load</param>
/// <exception cref="LoadingFailedException" />
////////////////////////////////////////////////////////////
public SoundBuffer(string filename) :
base(sfSoundBuffer_createFromFile(filename))
{
if (CPointer == IntPtr.Zero)
throw new LoadingFailedException("sound buffer", filename);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct a sound buffer from a custom stream.
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
/// </summary>
/// <param name="stream">Source stream to read from</param>
/// <exception cref="LoadingFailedException" />
////////////////////////////////////////////////////////////
public SoundBuffer(Stream stream) :
base(IntPtr.Zero)
{
using (StreamAdaptor adaptor = new StreamAdaptor(stream))
{
CPointer = sfSoundBuffer_createFromStream(adaptor.InputStreamPtr);
}
if (CPointer == IntPtr.Zero)
throw new LoadingFailedException("sound buffer");
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct a sound buffer from a file in memory.
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
/// </summary>
/// <param name="bytes">Byte array containing the file contents</param>
/// <exception cref="LoadingFailedException" />
////////////////////////////////////////////////////////////
public SoundBuffer(byte[] bytes) :
base(IntPtr.Zero)
{
GCHandle pin = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
CPointer = sfSoundBuffer_createFromMemory(pin.AddrOfPinnedObject(), Convert.ToUInt64(bytes.Length));
}
finally
{
pin.Free();
}
if (CPointer == IntPtr.Zero)
throw new LoadingFailedException("sound buffer");
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct a sound buffer from an array of samples
/// </summary>
/// <param name="samples">Array of samples</param>
/// <param name="channelCount">Channel count</param>
/// <param name="sampleRate">Sample rate</param>
/// <exception cref="LoadingFailedException" />
////////////////////////////////////////////////////////////
public SoundBuffer(short[] samples, uint channelCount, uint sampleRate) :
base(IntPtr.Zero)
{
unsafe
{
fixed (short* SamplesPtr = samples)
{
CPointer = sfSoundBuffer_createFromSamples(SamplesPtr, (uint)samples.Length, channelCount, sampleRate);
}
}
if (CPointer == IntPtr.Zero)
throw new LoadingFailedException("sound buffer");
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct a sound buffer from another sound buffer
/// </summary>
/// <param name="copy">Sound buffer to copy</param>
////////////////////////////////////////////////////////////
public SoundBuffer(SoundBuffer copy) :
base(sfSoundBuffer_copy(copy.CPointer))
{
}
////////////////////////////////////////////////////////////
/// <summary>
/// Save the sound buffer to an audio file.
///
/// Here is a complete list of all the supported audio formats:
/// ogg, wav, flac, aiff, au, raw, paf, svx, nist, voc, ircam,
/// w64, mat4, mat5 pvf, htk, sds, avr, sd2, caf, wve, mpc2k, rf64.
/// </summary>
/// <param name="filename">Path of the sound file to write</param>
/// <returns>True if saving has been successful</returns>
////////////////////////////////////////////////////////////
public bool SaveToFile(string filename)
{
return sfSoundBuffer_saveToFile(CPointer, filename);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Sample rate of the sound buffer.
///
/// The sample rate is the number of audio samples played per
/// second. The higher, the better the quality.
/// </summary>
////////////////////////////////////////////////////////////
public uint SampleRate
{
get { return sfSoundBuffer_getSampleRate(CPointer); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Number of channels (1 = mono, 2 = stereo)
/// </summary>
////////////////////////////////////////////////////////////
public uint ChannelCount
{
get { return sfSoundBuffer_getChannelCount(CPointer); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Total duration of the buffer
/// </summary>
////////////////////////////////////////////////////////////
public Time Duration
{
get { return sfSoundBuffer_getDuration(CPointer); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Array of audio samples stored in the buffer.
///
/// The format of the returned samples is 16 bits signed integer
/// (sf::Int16).
/// </summary>
////////////////////////////////////////////////////////////
public short[] Samples
{
get
{
short[] SamplesArray = new short[sfSoundBuffer_getSampleCount(CPointer)];
Marshal.Copy(sfSoundBuffer_getSamples(CPointer), SamplesArray, 0, SamplesArray.Length);
return SamplesArray;
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[SoundBuffer]" +
" SampleRate(" + SampleRate + ")" +
" ChannelCount(" + ChannelCount + ")" +
" Duration(" + Duration + ")";
}
////////////////////////////////////////////////////////////
/// <summary>
/// Handle the destruction of the object
/// </summary>
/// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param>
////////////////////////////////////////////////////////////
protected override void Destroy(bool disposing)
{
sfSoundBuffer_destroy(CPointer);
}
#region Imports
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfSoundBuffer_createFromFile(string Filename);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
unsafe static extern IntPtr sfSoundBuffer_createFromStream(IntPtr stream);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
unsafe static extern IntPtr sfSoundBuffer_createFromMemory(IntPtr data, ulong size);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
unsafe static extern IntPtr sfSoundBuffer_createFromSamples(short* Samples, uint SampleCount, uint ChannelsCount, uint SampleRate);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfSoundBuffer_copy(IntPtr SoundBuffer);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfSoundBuffer_destroy(IntPtr SoundBuffer);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfSoundBuffer_saveToFile(IntPtr SoundBuffer, string Filename);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfSoundBuffer_getSamples(IntPtr SoundBuffer);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern uint sfSoundBuffer_getSampleCount(IntPtr SoundBuffer);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern uint sfSoundBuffer_getSampleRate(IntPtr SoundBuffer);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern uint sfSoundBuffer_getChannelCount(IntPtr SoundBuffer);
[DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Time sfSoundBuffer_getDuration(IntPtr SoundBuffer);
#endregion
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Json
{
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Metadata.Query;
using Microsoft.Xrm.Sdk.Query;
using Newtonsoft.Json;
using Services.Query;
/// <summary>
/// A Json.NET converter for CRM SDK objects.
/// </summary>
public class CrmJsonConverter : Newtonsoft.Json.JsonConverter
{
/// <summary>
/// The concrete types that can be converted.
/// </summary>
internal static readonly Type[] CanConvertTypes =
{
typeof(Guid),
typeof(EntityFilters),
typeof(Condition),
};
/// <summary>
/// The base types that can be converted.
/// </summary>
internal static readonly Type[] CanConvertBaseTypes =
{
typeof(DataCollection<string, object>),
typeof(DataCollection<string, string>),
typeof(DataCollection<Relationship, EntityCollection>),
typeof(DataCollection<Relationship, QueryBase>),
typeof(DataCollection<DeletedMetadataFilters, DataCollection<Guid>>),
typeof(DataCollection<object>),
};
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns><c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.</returns>
public override bool CanConvert(Type objectType)
{
if (CanConvertTypes.Any(type => type == objectType))
{
return true;
}
if (CanConvertBaseTypes.Any(type => type.IsAssignableFrom(objectType)))
{
return true;
}
return false;
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// convert from actual type to surrogate type
var condition = value as Condition;
if (condition != null)
{
var jcondition = JsonCondition.Parse(condition);
serializer.Serialize(writer, jcondition);
}
if (value is Guid)
{
serializer.Serialize(writer, new JsonGuid { Value = value.ToString() });
}
if (value is EntityFilters)
{
serializer.Serialize(writer, new JsonEntityFilters { Value = (int)value });
}
CrmJsonConverter.Serialize(writer, value as DataCollection<string, object>, serializer);
CrmJsonConverter.Serialize(writer, value as DataCollection<string, string>, serializer);
CrmJsonConverter.Serialize(writer, value as DataCollection<Relationship, EntityCollection>, serializer);
CrmJsonConverter.Serialize(writer, value as DataCollection<Relationship, QueryBase>, serializer);
CrmJsonConverter.Serialize(writer, value as DataCollection<DeletedMetadataFilters, DataCollection<Guid>>, serializer);
CrmJsonConverter.Serialize(writer, value as ICollection<object>, serializer);
}
/// <summary>
/// Serializes a collection.
/// </summary>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
/// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
private static void Serialize<TKey, TValue>(JsonWriter writer, DataCollection<TKey, TValue> value, JsonSerializer serializer)
{
if (value != null)
{
if (typeof(TKey) == typeof(Relationship))
{
// serialize complex keys as lists instead
var surrogate = new JsonList<KeyValuePair<TKey, TValue>> { Value = value.ToList() };
serializer.Serialize(writer, surrogate);
}
else
{
var surrogate = value.ToDictionary(pair => pair.Key, pair => pair.Value);
serializer.Serialize(writer, surrogate);
}
}
}
/// <summary>
/// Serializes a collection.
/// </summary>
/// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
private static void Serialize(JsonWriter writer, ICollection<object> value, JsonSerializer serializer)
{
if (value != null)
{
var surrogate = value.ToList();
serializer.Serialize(writer, surrogate);
}
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// convert from surrogate type to actual type
if (existingValue is Guid)
{
var id = serializer.Deserialize<JsonGuid>(reader);
return new Guid(id.Value);
}
if (existingValue is EntityFilters)
{
var filters = serializer.Deserialize<JsonEntityFilters>(reader);
return (EntityFilters)filters.Value;
}
if (objectType == typeof(Condition))
{
var jcondition = serializer.Deserialize<JsonCondition>(reader);
return jcondition.ToCondition(Deserialize);
}
CrmJsonConverter.Deserialize(reader, existingValue as DataCollection<string, object>, serializer);
CrmJsonConverter.Deserialize(reader, existingValue as DataCollection<string, string>, serializer);
CrmJsonConverter.Deserialize(reader, existingValue as DataCollection<Relationship, EntityCollection>, serializer);
CrmJsonConverter.Deserialize(reader, existingValue as DataCollection<Relationship, QueryBase>, serializer);
CrmJsonConverter.Deserialize(reader, existingValue as DataCollection<DeletedMetadataFilters, DataCollection<Guid>>, serializer);
CrmJsonConverter.Deserialize(reader, existingValue as ICollection<object>, serializer);
return existingValue;
}
/// <summary>
/// Deserializes a collection.
/// </summary>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
/// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
private static void Deserialize<TKey, TValue>(JsonReader reader, DataCollection<TKey, TValue> existingValue, JsonSerializer serializer)
{
if (existingValue != null)
{
// scan for object references where surrogate conversion is not done automatically
var surrogate = typeof(TKey) == typeof(Relationship)
? serializer.Deserialize<JsonList<KeyValuePair<TKey, TValue>>>(reader).Value.Select(Deserialize).ToList()
: serializer.Deserialize<Dictionary<TKey, TValue>>(reader).Select(Deserialize).ToList();
// merge the surrogate with the result object
foreach (var pair in surrogate)
{
existingValue[pair.Key] = pair.Value;
}
}
}
/// <summary>
/// Deserializes a KeyValuePair.
/// </summary>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
/// <param name="pair">The pair.</param>
/// <returns>The deserialized pair.</returns>
private static KeyValuePair<TKey, TValue> Deserialize<TKey, TValue>(KeyValuePair<TKey, TValue> pair)
{
// scan for object references where surrogate conversion is not done automatically
var alias = pair.Value as AliasedValue;
if (alias != null)
{
return new KeyValuePair<TKey, TValue>(pair.Key, (TValue)(object)new AliasedValue(alias.EntityLogicalName, alias.AttributeLogicalName, Deserialize(alias.Value)));
}
return new KeyValuePair<TKey, TValue>(pair.Key, (TValue)Deserialize(pair.Value));
}
/// <summary>
/// Deserializes a collection.
/// </summary>
/// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
private static void Deserialize(JsonReader reader, ICollection<object> existingValue, JsonSerializer serializer)
{
if (existingValue != null)
{
// scan for object references where surrogate conversion is not done automatically
var surrogate = serializer.Deserialize<List<object>>(reader).Select(Deserialize);
foreach (var item in surrogate)
{
existingValue.Add(item);
}
}
}
/// <summary>
/// Deserializes a surrogate object.
/// </summary>
/// <param name="value">The surrogate.</param>
/// <returns>The object.</returns>
private static object Deserialize(object value)
{
// convert from surrogate type to actual type
if (value is long)
{
// for object references, the default json numeric type is long but the end result should be int
return Convert.ToInt32(value);
}
if (value is JsonGuid)
{
return new Guid(((JsonGuid)value).Value);
}
if (value is JsonEntityFilters)
{
return (EntityFilters)((JsonEntityFilters)value).Value;
}
if (value is JsonList<KeyValuePair<Relationship, QueryBase>>)
{
var dictionary = new RelationshipQueryCollection();
dictionary.AddRange(((JsonList<KeyValuePair<Relationship, QueryBase>>)value).Value);
return dictionary;
}
return value;
}
}
}
| |
#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
using System;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using Microsoft.Xna.Framework;
namespace GameGeometry2D {
[DataContract(Name = "bPoly", Namespace = ""), KnownType(typeof(Vector2))]
public sealed class BoundingPolygon : IEquatable<BoundingPolygon> {
public BoundingPolygon(Vector2[] vertices) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
_vertices = vertices;
}
[DataMember(Name = "vs", EmitDefaultValue = false)]
private Vector2[] _vertices;
public Vector2[] Vertices {
get { return _vertices; }
set {
Contract.Requires(value != null);
Contract.Requires(value.Length > 2);
_vertices = value;
}
}
public float Area {
get {
float result;
GetArea(Vertices, out result);
return result;
}
}
public float Perimeter {
get {
float result;
GetPerimeter(Vertices, out result);
return result;
}
}
public bool Equals(BoundingPolygon other) {
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
if (Vertices == null || other.Vertices == null || Vertices.Length != other.Vertices.Length) {
return false;
}
for (var index = 0; index < Vertices.Length; index++) {
var vertex1 = Vertices[index];
var vertex2 = other.Vertices[index];
if (!Vectors2.Equals(ref vertex1, ref vertex2)) {
return false;
}
}
return true;
}
public float GetDistance(Vector2 point) {
float result;
GetDistance(Vertices, ref point, out result);
return result;
}
public void GetDistance(ref Vector2 point, out float result) {
GetDistance(Vertices, ref point, out result);
}
public Containment Contains(Vector2 point) {
Containment result;
Contains(ref point, out result);
return result;
}
public void Contains(ref Vector2 point, out Containment result) {
ContainsInclusive(Vertices, ref point, out result);
}
public Containment Contains(BoundingCircle circle) {
Containment result;
Contains(ref circle, out result);
return result;
}
public void Contains(ref BoundingCircle circle, out Containment result) {
float distance;
GetDistance(ref circle.Center, out distance);
distance += circle.Radius;
if (distance <= 0) {
result = Containment.Contains;
} else if (distance <= circle.Radius) {
result = Containment.Intersects;
} else {
result = Containment.Disjoint;
}
}
public Containment Contains(BoundingRectangle rect) {
Containment result;
Contains(ref rect, out result);
return result;
}
public void Contains(ref BoundingRectangle rect, out Containment result) {
Contains(rect.Corners(), out result);
}
public Containment Contains(BoundingPolygon polygon) {
Contract.Requires(polygon != null);
Contract.Requires(polygon.Vertices != null);
Contract.Requires(polygon.Vertices.Length > 2);
Containment result;
Contains(ref polygon, out result);
return result;
}
public void Contains(ref BoundingPolygon polygon, out Containment result) {
if (polygon == null) { throw new ArgumentNullException("polygon"); }
Contains(polygon.Vertices, out result);
}
public float Intersects(Ray2D ray) {
float result;
Intersects(ref ray, out result);
return result;
}
public bool Intersects(BoundingRectangle rect) {
bool result;
Intersects(ref rect, out result);
return result;
}
public bool Intersects(BoundingCircle circle) {
bool result;
Intersects(ref circle, out result);
return result;
}
public bool Intersects(BoundingPolygon polygon) {
Contract.Requires(polygon != null);
Contract.Requires(polygon.Vertices != null);
Contract.Requires(polygon.Vertices.Length > 1);
bool result;
Intersects(ref polygon, out result);
return result;
}
public void Intersects(ref Ray2D ray, out float result) {
result = -1;
for (var index = 0; index < Vertices.Length; ++index) {
var index2 = (index + 1) % Vertices.Length;
float temp;
LineSegment.Intersects(ref Vertices[index], ref Vertices[index2], ref ray, out temp);
if (temp >= 0 && (result == -1 || temp < result)) {
result = temp;
}
}
}
public void Intersects(ref BoundingRectangle rect, out bool result) {
Intersects(Vertices, rect.Corners(), out result);
}
public void Intersects(ref BoundingCircle circle, out bool result) {
result = false;
for (var index = 0; index < Vertices.Length; ++index) {
var index2 = (index + 1) % Vertices.Length;
float temp;
LineSegment.GetDistance(ref Vertices[index], ref Vertices[index2], ref circle.Center, out temp);
if (temp <= circle.Radius) {
result = true;
break;
}
}
}
public void Intersects(ref BoundingPolygon polygon, out bool result) {
Contract.Requires(polygon != null);
Contract.Requires(polygon.Vertices != null);
Contract.Requires(polygon.Vertices.Length > 1);
Intersects(Vertices, polygon.Vertices, out result);
}
public override bool Equals(object obj) {
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
return obj is BoundingPolygon && Equals((BoundingPolygon) obj);
}
public override int GetHashCode() {
return (Vertices != null ? Vertices.GetHashCode() : 0);
}
private void Contains(Vector2[] otherVertexes, out Containment result) {
Contract.Requires(otherVertexes != null);
Contract.Requires(otherVertexes.Length > 2);
Containment contains;
result = Containment.Unknown;
for (var index = 0; index < Vertices.Length; ++index) {
ContainsExclusive(otherVertexes, ref Vertices[index], out contains);
if (contains == Containment.Contains) {
result = Containment.Intersects;
return;
}
}
for (var index = 0; index < otherVertexes.Length && result != Containment.Intersects; ++index) {
ContainsInclusive(Vertices, ref otherVertexes[index], out contains);
result |= contains;
}
if (result == Containment.Disjoint) {
bool test;
Intersects(Vertices, otherVertexes, out test);
if (test) { result = Containment.Intersects; }
}
}
public static Containment ContainsExclusive(Vector2[] vertices, Vector2 point) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
Containment result;
ContainsExclusive(vertices, ref point, out result);
return result;
}
public static void ContainsExclusive(Vector2[] vertices, ref Vector2 point, out Containment result) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
var intersectionCount = 0;
Vector2 v1, v2;
v1 = vertices[vertices.Length - 1];
for (var index = 0; index < vertices.Length; ++index, v1 = v2) {
v2 = vertices[index];
var t1 = (v1.Y <= point.Y);
if (t1 ^ (v2.Y <= point.Y)) {
var temp = ((point.Y - v1.Y) * (v2.X - v1.X) - (point.X - v1.X) * (v2.Y - v1.Y));
if (t1) {
if (temp > 0) { intersectionCount++; }
} else {
if (temp < 0) { intersectionCount--; }
}
}
}
result = (intersectionCount != 0) ? (Containment.Contains) : (Containment.Disjoint);
}
public static Containment ContainsInclusive(Vector2[] vertices, Vector2 point) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
Containment result;
ContainsInclusive(vertices, ref point, out result);
return result;
}
public static void ContainsInclusive(Vector2[] vertices, ref Vector2 point, out Containment result) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
var count = 0; // the crossing count
var v1 = vertices[vertices.Length - 1];
Vector2 v2;
for (var index = 0; index < vertices.Length; index++, v1 = v2) {
v2 = vertices[index];
if (((v1.Y <= point.Y) ^ (v2.Y <= point.Y)) ||
(v1.Y.NearlyEquals(point.Y)) || (v2.Y.NearlyEquals(point.Y))) {
var xIntersection = (v1.X + ((point.Y - v1.Y) / (v2.Y - v1.Y)) * (v2.X - v1.X));
if (point.X < xIntersection) // P.X < intersect
{
++count;
} else if (xIntersection.NearlyEquals(point.X)) {
result = Containment.Contains;
return;
}
}
}
result = ((count & 1) != 0) ? (Containment.Contains) : (Containment.Disjoint); //true if odd.
}
public static bool Intersects(Vector2[] vertexes1, Vector2[] vertexes2) {
Contract.Requires(vertexes1 != null);
Contract.Requires(vertexes1.Length > 1);
Contract.Requires(vertexes2 != null);
Contract.Requires(vertexes2.Length > 1);
bool result;
Intersects(vertexes1, vertexes2, out result);
return result;
}
public static void Intersects(Vector2[] vertexes1, Vector2[] vertexes2, out bool result) {
Contract.Requires(vertexes1 != null);
Contract.Requires(vertexes1.Length > 1);
Contract.Requires(vertexes2 != null);
Contract.Requires(vertexes2.Length > 1);
var v1 = vertexes1[vertexes1.Length - 1];
Vector2 v2;
var v3 = vertexes2[vertexes2.Length - 1];
Vector2 v4;
result = false;
for (var index1 = 0; index1 < vertexes1.Length; ++index1, v1 = v2) {
v2 = vertexes1[index1];
for (var index2 = 0; index2 < vertexes2.Length; ++index2, v3 = v4) {
v4 = vertexes2[index2];
LineSegment.Intersects(ref v1, ref v2, ref v3, ref v4, out result);
if (result) { return; }
}
}
}
public static float GetDistance(Vector2[] vertices, Vector2 point) {
float result;
GetDistance(vertices, ref point, out result);
return result;
}
public static void GetDistance(Vector2[] vertices, ref Vector2 point, out float result) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
var count = 0; //intersection count
var v1 = vertices[vertices.Length - 1];
Vector2 v2;
var goodDistance = float.PositiveInfinity;
for (var index = 0; index < vertices.Length; ++index, v1 = v2) {
v2 = vertices[index];
var t1 = (v1.Y <= point.Y);
if (t1 ^ (v2.Y <= point.Y)) {
var temp = ((point.Y - v1.Y) * (v2.X - v1.X) - (point.X - v1.X) * (v2.Y - v1.Y));
if (t1) { if (temp > 0) { count++; } } else { if (temp < 0) { count--; } }
}
float distance;
LineSegment.GetDistanceSq(ref v1, ref v2, ref point, out distance);
if (distance < goodDistance) { goodDistance = distance; }
}
result = (float) Math.Sqrt(goodDistance);
if (count != 0) {
result = -result;
}
}
/// <summary> Calculates the centroid of a polygon.</summary>
/// <param name="vertices">The vertices of the polygon.</param>
/// <returns>The centroid of a polygon.</returns>
/// <remarks>This is also known as center of gravity/mass.</remarks>
public static Vector2 GetCentroid(Vector2[] vertices) {
Vector2 result;
GetCentroid(vertices, out result);
return result;
}
/// <summary> Calculates the centroid of a polygon.</summary>
/// <param name="vertices">The vertices of the polygon.</param>
/// <param name="centroid">The centroid of a polygon.</param>
/// <remarks>This is also known as center of gravity/mass.</remarks>
public static void GetCentroid(Vector2[] vertices, out Vector2 centroid) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
centroid = Vector2.Zero;
float temp;
float area = 0;
var v1 = vertices[vertices.Length - 1];
Vector2 v2;
for (var index = 0; index < vertices.Length; ++index, v1 = v2) {
v2 = vertices[index];
Vectors2.ZCross(ref v1, ref v2, out temp);
area += temp;
centroid.X += ((v1.X + v2.X) * temp);
centroid.Y += ((v1.Y + v2.Y) * temp);
}
temp = 1 / (Math.Abs(area) * 3);
centroid.X *= temp;
centroid.Y *= temp;
}
/// <summary>Calculates the area of a polygon.</summary>
/// <param name="vertices">The vertices of the polygon.</param>
/// <returns>the area.</returns>
public static float GetArea(Vector2[] vertices) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
float result;
GetArea(vertices, out result);
return result;
}
/// <summary>
/// Calculates the area of a polygon.
/// </summary>
/// <param name="vertices">The vertices of the polygon.</param>
/// <param name="result">the area.</param>
public static void GetArea(Vector2[] vertices, out float result) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
float area = 0;
var v1 = vertices[vertices.Length - 1];
Vector2 v2;
for (var index = 0; index < vertices.Length; ++index, v1 = v2) {
v2 = vertices[index];
float temp;
Vectors2.ZCross(ref v1, ref v2, out temp);
area += temp;
}
result = Math.Abs(area * .5f);
}
public static float GetPerimeter(Vector2[] vertices) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
float result;
GetPerimeter(vertices, out result);
return result;
}
public static void GetPerimeter(Vector2[] vertices, out float result) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 2);
var v1 = vertices[vertices.Length - 1];
Vector2 v2;
result = 0;
for (var index = 0; index < vertices.Length; ++index, v1 = v2) {
v2 = vertices[index];
float dist;
Vector2.Distance(ref v1, ref v2, out dist);
result += dist;
}
}
public static float GetInertia(Vector2[] vertices) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 0);
float result;
GetInertia(vertices, out result);
return result;
}
public static void GetInertia(Vector2[] vertices, out float result) {
Contract.Requires(vertices != null);
Contract.Requires(vertices.Length > 0);
if (vertices.Length == 1) {
result = 0;
return;
}
float denom = 0;
float numer = 0;
var v1 = vertices[vertices.Length - 1];
Vector2 v2;
for (var index = 0; index < vertices.Length; index++, v1 = v2) {
v2 = vertices[index];
float a, b, c, d;
Vector2.Dot(ref v2, ref v2, out a);
Vector2.Dot(ref v2, ref v1, out b);
Vector2.Dot(ref v1, ref v1, out c);
Vectors2.ZCross(ref v1, ref v2, out d);
d = Math.Abs(d);
numer += d;
denom += (a + b + c) * d;
}
result = denom / (numer * 6);
}
public static bool operator ==(BoundingPolygon left, BoundingPolygon right) {
return Equals(left, right);
}
public static bool operator !=(BoundingPolygon left, BoundingPolygon right) {
return !Equals(left, right);
}
}
}
| |
#region License
/*
* WebHeaderCollection.cs
*
* This code is derived from WebHeaderCollection.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2003 Ximian, Inc. (http://www.ximian.com)
* Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Lawrence Pit <loz@cable.a2000.nl>
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
* - Miguel de Icaza <miguel@novell.com>
*/
#endregion
#pragma warning disable 0618
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides a collection of the HTTP headers associated with a request or response.
/// </summary>
[Serializable]
[ComVisible (true)]
public class WebHeaderCollection : NameValueCollection, ISerializable
{
#region Private Fields
private static readonly Dictionary<string, HttpHeaderInfo> _headers;
private bool _internallyUsed;
private HttpHeaderType _state;
#endregion
#region Static Constructor
static WebHeaderCollection ()
{
_headers =
new Dictionary<string, HttpHeaderInfo> (StringComparer.InvariantCultureIgnoreCase) {
{
"Accept",
new HttpHeaderInfo (
"Accept",
HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
},
{
"AcceptCharset",
new HttpHeaderInfo (
"Accept-Charset",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"AcceptEncoding",
new HttpHeaderInfo (
"Accept-Encoding",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"AcceptLanguage",
new HttpHeaderInfo (
"Accept-Language",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"AcceptRanges",
new HttpHeaderInfo (
"Accept-Ranges",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Age",
new HttpHeaderInfo (
"Age",
HttpHeaderType.Response)
},
{
"Allow",
new HttpHeaderInfo (
"Allow",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Authorization",
new HttpHeaderInfo (
"Authorization",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"CacheControl",
new HttpHeaderInfo (
"Cache-Control",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Connection",
new HttpHeaderInfo (
"Connection",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValue)
},
{
"ContentEncoding",
new HttpHeaderInfo (
"Content-Encoding",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"ContentLanguage",
new HttpHeaderInfo (
"Content-Language",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"ContentLength",
new HttpHeaderInfo (
"Content-Length",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"ContentLocation",
new HttpHeaderInfo (
"Content-Location",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ContentMd5",
new HttpHeaderInfo (
"Content-MD5",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ContentRange",
new HttpHeaderInfo (
"Content-Range",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ContentType",
new HttpHeaderInfo (
"Content-Type",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"Cookie",
new HttpHeaderInfo (
"Cookie",
HttpHeaderType.Request)
},
{
"Cookie2",
new HttpHeaderInfo (
"Cookie2",
HttpHeaderType.Request)
},
{
"Date",
new HttpHeaderInfo (
"Date",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"Expect",
new HttpHeaderInfo (
"Expect",
HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
},
{
"Expires",
new HttpHeaderInfo (
"Expires",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ETag",
new HttpHeaderInfo (
"ETag",
HttpHeaderType.Response)
},
{
"From",
new HttpHeaderInfo (
"From",
HttpHeaderType.Request)
},
{
"Host",
new HttpHeaderInfo (
"Host",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"IfMatch",
new HttpHeaderInfo (
"If-Match",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"IfModifiedSince",
new HttpHeaderInfo (
"If-Modified-Since",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"IfNoneMatch",
new HttpHeaderInfo (
"If-None-Match",
HttpHeaderType.Request | HttpHeaderType.MultiValue)
},
{
"IfRange",
new HttpHeaderInfo (
"If-Range",
HttpHeaderType.Request)
},
{
"IfUnmodifiedSince",
new HttpHeaderInfo (
"If-Unmodified-Since",
HttpHeaderType.Request)
},
{
"KeepAlive",
new HttpHeaderInfo (
"Keep-Alive",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"LastModified",
new HttpHeaderInfo (
"Last-Modified",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"Location",
new HttpHeaderInfo (
"Location",
HttpHeaderType.Response)
},
{
"MaxForwards",
new HttpHeaderInfo (
"Max-Forwards",
HttpHeaderType.Request)
},
{
"Pragma",
new HttpHeaderInfo (
"Pragma",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"ProxyAuthenticate",
new HttpHeaderInfo (
"Proxy-Authenticate",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"ProxyAuthorization",
new HttpHeaderInfo (
"Proxy-Authorization",
HttpHeaderType.Request)
},
{
"ProxyConnection",
new HttpHeaderInfo (
"Proxy-Connection",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"Public",
new HttpHeaderInfo (
"Public",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Range",
new HttpHeaderInfo (
"Range",
HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
},
{
"Referer",
new HttpHeaderInfo (
"Referer",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"RetryAfter",
new HttpHeaderInfo (
"Retry-After",
HttpHeaderType.Response)
},
{
"SecWebSocketAccept",
new HttpHeaderInfo (
"Sec-WebSocket-Accept",
HttpHeaderType.Response | HttpHeaderType.Restricted)
},
{
"SecWebSocketExtensions",
new HttpHeaderInfo (
"Sec-WebSocket-Extensions",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValueInRequest)
},
{
"SecWebSocketKey",
new HttpHeaderInfo (
"Sec-WebSocket-Key",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"SecWebSocketProtocol",
new HttpHeaderInfo (
"Sec-WebSocket-Protocol",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValueInRequest)
},
{
"SecWebSocketVersion",
new HttpHeaderInfo (
"Sec-WebSocket-Version",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValueInResponse)
},
{
"Server",
new HttpHeaderInfo (
"Server",
HttpHeaderType.Response)
},
{
"SetCookie",
new HttpHeaderInfo (
"Set-Cookie",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"SetCookie2",
new HttpHeaderInfo (
"Set-Cookie2",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Te",
new HttpHeaderInfo (
"TE",
HttpHeaderType.Request)
},
{
"Trailer",
new HttpHeaderInfo (
"Trailer",
HttpHeaderType.Request | HttpHeaderType.Response)
},
{
"TransferEncoding",
new HttpHeaderInfo (
"Transfer-Encoding",
HttpHeaderType.Request |
HttpHeaderType.Response |
HttpHeaderType.Restricted |
HttpHeaderType.MultiValue)
},
{
"Translate",
new HttpHeaderInfo (
"Translate",
HttpHeaderType.Request)
},
{
"Upgrade",
new HttpHeaderInfo (
"Upgrade",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"UserAgent",
new HttpHeaderInfo (
"User-Agent",
HttpHeaderType.Request | HttpHeaderType.Restricted)
},
{
"Vary",
new HttpHeaderInfo (
"Vary",
HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Via",
new HttpHeaderInfo (
"Via",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"Warning",
new HttpHeaderInfo (
"Warning",
HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue)
},
{
"WwwAuthenticate",
new HttpHeaderInfo (
"WWW-Authenticate",
HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValue)
}
};
}
#endregion
#region Internal Constructors
internal WebHeaderCollection (HttpHeaderType state, bool internallyUsed)
{
_state = state;
_internallyUsed = internallyUsed;
}
#endregion
#region Protected Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebHeaderCollection"/> class from
/// the specified <see cref="SerializationInfo"/> and <see cref="StreamingContext"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that contains the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the source for the deserialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// An element with the specified name isn't found in <paramref name="serializationInfo"/>.
/// </exception>
protected WebHeaderCollection (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (serializationInfo == null)
throw new ArgumentNullException ("serializationInfo");
try {
_internallyUsed = serializationInfo.GetBoolean ("InternallyUsed");
_state = (HttpHeaderType) serializationInfo.GetInt32 ("State");
var cnt = serializationInfo.GetInt32 ("Count");
for (var i = 0; i < cnt; i++) {
base.Add (
serializationInfo.GetString (i.ToString ()),
serializationInfo.GetString ((cnt + i).ToString ()));
}
}
catch (SerializationException ex) {
throw new ArgumentException (ex.Message, "serializationInfo", ex);
}
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebHeaderCollection"/> class.
/// </summary>
public WebHeaderCollection ()
{
}
#endregion
#region Internal Properties
internal HttpHeaderType State {
get {
return _state;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets all header names in the collection.
/// </summary>
/// <value>
/// An array of <see cref="string"/> that contains all header names in the collection.
/// </value>
public override string[] AllKeys {
get {
return base.AllKeys;
}
}
/// <summary>
/// Gets the number of headers in the collection.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of headers in the collection.
/// </value>
public override int Count {
get {
return base.Count;
}
}
/// <summary>
/// Gets or sets the specified request <paramref name="header"/> in the collection.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the request <paramref name="header"/>.
/// </value>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to get or set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public string this[HttpRequestHeader header] {
get {
return Get (Convert (header));
}
set {
Add (header, value);
}
}
/// <summary>
/// Gets or sets the specified response <paramref name="header"/> in the collection.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the response <paramref name="header"/>.
/// </value>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to get or set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public string this[HttpResponseHeader header] {
get {
return Get (Convert (header));
}
set {
Add (header, value);
}
}
/// <summary>
/// Gets a collection of header names in the collection.
/// </summary>
/// <value>
/// A <see cref="NameObjectCollectionBase.KeysCollection"/> that contains
/// all header names in the collection.
/// </value>
public override NameObjectCollectionBase.KeysCollection Keys {
get {
return base.Keys;
}
}
#endregion
#region Private Methods
private void add (string name, string value, bool ignoreRestricted)
{
var act = ignoreRestricted
? (Action <string, string>) addWithoutCheckingNameAndRestricted
: addWithoutCheckingName;
doWithCheckingState (act, checkName (name), value, true);
}
private void addWithoutCheckingName (string name, string value)
{
doWithoutCheckingName (base.Add, name, value);
}
private void addWithoutCheckingNameAndRestricted (string name, string value)
{
base.Add (name, checkValue (value));
}
private static int checkColonSeparated (string header)
{
var idx = header.IndexOf (':');
if (idx == -1)
throw new ArgumentException ("No colon could be found.", "header");
return idx;
}
private static HttpHeaderType checkHeaderType (string name)
{
var info = getHeaderInfo (name);
return info == null
? HttpHeaderType.Unspecified
: info.IsRequest && !info.IsResponse
? HttpHeaderType.Request
: !info.IsRequest && info.IsResponse
? HttpHeaderType.Response
: HttpHeaderType.Unspecified;
}
private static string checkName (string name)
{
if (name == null || name.Length == 0)
throw new ArgumentNullException ("name");
name = name.Trim ();
if (!IsHeaderName (name))
throw new ArgumentException ("Contains invalid characters.", "name");
return name;
}
private void checkRestricted (string name)
{
if (!_internallyUsed && isRestricted (name, true))
throw new ArgumentException ("This header must be modified with the appropiate property.");
}
private void checkState (bool response)
{
if (_state == HttpHeaderType.Unspecified)
return;
if (response && _state == HttpHeaderType.Request)
throw new InvalidOperationException (
"This collection has already been used to store the request headers.");
if (!response && _state == HttpHeaderType.Response)
throw new InvalidOperationException (
"This collection has already been used to store the response headers.");
}
private static string checkValue (string value)
{
if (value == null || value.Length == 0)
return String.Empty;
value = value.Trim ();
if (value.Length > 65535)
throw new ArgumentOutOfRangeException ("value", "Greater than 65,535 characters.");
if (!IsHeaderValue (value))
throw new ArgumentException ("Contains invalid characters.", "value");
return value;
}
private static string convert (string key)
{
HttpHeaderInfo info;
return _headers.TryGetValue (key, out info) ? info.Name : String.Empty;
}
private void doWithCheckingState (
Action <string, string> action, string name, string value, bool setState)
{
var type = checkHeaderType (name);
if (type == HttpHeaderType.Request)
doWithCheckingState (action, name, value, false, setState);
else if (type == HttpHeaderType.Response)
doWithCheckingState (action, name, value, true, setState);
else
action (name, value);
}
private void doWithCheckingState (
Action <string, string> action, string name, string value, bool response, bool setState)
{
checkState (response);
action (name, value);
if (setState && _state == HttpHeaderType.Unspecified)
_state = response ? HttpHeaderType.Response : HttpHeaderType.Request;
}
private void doWithoutCheckingName (Action <string, string> action, string name, string value)
{
checkRestricted (name);
action (name, checkValue (value));
}
private static HttpHeaderInfo getHeaderInfo (string name)
{
foreach (var info in _headers.Values)
if (info.Name.Equals (name, StringComparison.InvariantCultureIgnoreCase))
return info;
return null;
}
private static bool isRestricted (string name, bool response)
{
var info = getHeaderInfo (name);
return info != null && info.IsRestricted (response);
}
private void removeWithoutCheckingName (string name, string unuse)
{
checkRestricted (name);
base.Remove (name);
}
private void setWithoutCheckingName (string name, string value)
{
doWithoutCheckingName (base.Set, name, value);
}
#endregion
#region Internal Methods
internal static string Convert (HttpRequestHeader header)
{
return convert (header.ToString ());
}
internal static string Convert (HttpResponseHeader header)
{
return convert (header.ToString ());
}
internal void InternalRemove (string name)
{
base.Remove (name);
}
internal void InternalSet (string header, bool response)
{
var pos = checkColonSeparated (header);
InternalSet (header.Substring (0, pos), header.Substring (pos + 1), response);
}
internal void InternalSet (string name, string value, bool response)
{
value = checkValue (value);
if (IsMultiValue (name, response))
base.Add (name, value);
else
base.Set (name, value);
}
internal static bool IsHeaderName (string name)
{
return name != null && name.Length > 0 && name.IsToken ();
}
internal static bool IsHeaderValue (string value)
{
return value.IsText ();
}
internal static bool IsMultiValue (string headerName, bool response)
{
if (headerName == null || headerName.Length == 0)
return false;
var info = getHeaderInfo (headerName);
return info != null && info.IsMultiValue (response);
}
internal string ToStringMultiValue (bool response)
{
var buff = new StringBuilder ();
Count.Times (
i => {
var key = GetKey (i);
if (IsMultiValue (key, response))
foreach (var val in GetValues (i))
buff.AppendFormat ("{0}: {1}\r\n", key, val);
else
buff.AppendFormat ("{0}: {1}\r\n", key, Get (i));
});
return buff.Append ("\r\n").ToString ();
}
#endregion
#region Protected Methods
/// <summary>
/// Adds a header to the collection without checking if the header is on
/// the restricted header list.
/// </summary>
/// <param name="headerName">
/// A <see cref="string"/> that represents the name of the header to add.
/// </param>
/// <param name="headerValue">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> or <paramref name="headerValue"/> contains invalid characters.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="headerValue"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the <paramref name="headerName"/>.
/// </exception>
protected void AddWithoutValidate (string headerName, string headerValue)
{
add (headerName, headerValue, true);
}
#endregion
#region Public Methods
/// <summary>
/// Adds the specified <paramref name="header"/> to the collection.
/// </summary>
/// <param name="header">
/// A <see cref="string"/> that represents the header with the name and value separated by
/// a colon (<c>':'</c>).
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="header"/> is <see langword="null"/>, empty, or the name part of
/// <paramref name="header"/> is empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> doesn't contain a colon.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The name or value part of <paramref name="header"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of the value part of <paramref name="header"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the <paramref name="header"/>.
/// </exception>
public void Add (string header)
{
if (header == null || header.Length == 0)
throw new ArgumentNullException ("header");
var pos = checkColonSeparated (header);
add (header.Substring (0, pos), header.Substring (pos + 1), false);
}
/// <summary>
/// Adds the specified request <paramref name="header"/> with
/// the specified <paramref name="value"/> to the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public void Add (HttpRequestHeader header, string value)
{
doWithCheckingState (addWithoutCheckingName, Convert (header), value, false, true);
}
/// <summary>
/// Adds the specified response <paramref name="header"/> with
/// the specified <paramref name="value"/> to the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public void Add (HttpResponseHeader header, string value)
{
doWithCheckingState (addWithoutCheckingName, Convert (header), value, true, true);
}
/// <summary>
/// Adds a header with the specified <paramref name="name"/> and
/// <paramref name="value"/> to the collection.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the header <paramref name="name"/>.
/// </exception>
public override void Add (string name, string value)
{
add (name, value, false);
}
/// <summary>
/// Removes all headers from the collection.
/// </summary>
public override void Clear ()
{
base.Clear ();
_state = HttpHeaderType.Unspecified;
}
/// <summary>
/// Get the value of the header at the specified <paramref name="index"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the value of the header.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the header to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public override string Get (int index)
{
return base.Get (index);
}
/// <summary>
/// Get the value of the header with the specified <paramref name="name"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the value of the header if found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to find.
/// </param>
public override string Get (string name)
{
return base.Get (name);
}
/// <summary>
/// Gets the enumerator used to iterate through the collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> instance used to iterate through the collection.
/// </returns>
public override IEnumerator GetEnumerator ()
{
return base.GetEnumerator ();
}
/// <summary>
/// Get the name of the header at the specified <paramref name="index"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the header name.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the header to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public override string GetKey (int index)
{
return base.GetKey (index);
}
/// <summary>
/// Gets an array of header values stored in the specified <paramref name="index"/> position of
/// the collection.
/// </summary>
/// <returns>
/// An array of <see cref="string"/> that receives the header values if found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the header to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public override string[] GetValues (int index)
{
var vals = base.GetValues (index);
return vals != null && vals.Length > 0 ? vals : null;
}
/// <summary>
/// Gets an array of header values stored in the specified <paramref name="header"/>.
/// </summary>
/// <returns>
/// An array of <see cref="string"/> that receives the header values if found;
/// otherwise, <see langword="null"/>.
/// </returns>
/// <param name="header">
/// A <see cref="string"/> that represents the name of the header to find.
/// </param>
public override string[] GetValues (string header)
{
var vals = base.GetValues (header);
return vals != null && vals.Length > 0 ? vals : null;
}
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize
/// the <see cref="WebHeaderCollection"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[SecurityPermission (
SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (serializationInfo == null)
throw new ArgumentNullException ("serializationInfo");
serializationInfo.AddValue ("InternallyUsed", _internallyUsed);
serializationInfo.AddValue ("State", (int) _state);
var cnt = Count;
serializationInfo.AddValue ("Count", cnt);
cnt.Times (
i => {
serializationInfo.AddValue (i.ToString (), GetKey (i));
serializationInfo.AddValue ((cnt + i).ToString (), Get (i));
});
}
/// <summary>
/// Determines whether the specified header can be set for the request.
/// </summary>
/// <returns>
/// <c>true</c> if the header is restricted; otherwise, <c>false</c>.
/// </returns>
/// <param name="headerName">
/// A <see cref="string"/> that represents the name of the header to test.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> contains invalid characters.
/// </exception>
public static bool IsRestricted (string headerName)
{
return isRestricted (checkName (headerName), false);
}
/// <summary>
/// Determines whether the specified header can be set for the request or the response.
/// </summary>
/// <returns>
/// <c>true</c> if the header is restricted; otherwise, <c>false</c>.
/// </returns>
/// <param name="headerName">
/// A <see cref="string"/> that represents the name of the header to test.
/// </param>
/// <param name="response">
/// <c>true</c> if does the test for the response; for the request, <c>false</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> contains invalid characters.
/// </exception>
public static bool IsRestricted (string headerName, bool response)
{
return isRestricted (checkName (headerName), response);
}
/// <summary>
/// Implements the <see cref="ISerializable"/> interface and raises the deserialization event
/// when the deserialization is complete.
/// </summary>
/// <param name="sender">
/// An <see cref="object"/> that represents the source of the deserialization event.
/// </param>
public override void OnDeserialization (object sender)
{
}
/// <summary>
/// Removes the specified request <paramref name="header"/> from the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to remove.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="header"/> is a restricted header.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public void Remove (HttpRequestHeader header)
{
doWithCheckingState (removeWithoutCheckingName, Convert (header), null, false, false);
}
/// <summary>
/// Removes the specified response <paramref name="header"/> from the collection.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to remove.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="header"/> is a restricted header.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public void Remove (HttpResponseHeader header)
{
doWithCheckingState (removeWithoutCheckingName, Convert (header), null, true, false);
}
/// <summary>
/// Removes the specified header from the collection.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the header <paramref name="name"/>.
/// </exception>
public override void Remove (string name)
{
doWithCheckingState (removeWithoutCheckingName, checkName (name), null, false);
}
/// <summary>
/// Sets the specified request <paramref name="header"/> to the specified value.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpRequestHeader"/> enum values, represents
/// the request header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the request header to set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the request <paramref name="header"/>.
/// </exception>
public void Set (HttpRequestHeader header, string value)
{
doWithCheckingState (setWithoutCheckingName, Convert (header), value, false, true);
}
/// <summary>
/// Sets the specified response <paramref name="header"/> to the specified value.
/// </summary>
/// <param name="header">
/// One of the <see cref="HttpResponseHeader"/> enum values, represents
/// the response header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the response header to set.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the response <paramref name="header"/>.
/// </exception>
public void Set (HttpResponseHeader header, string value)
{
doWithCheckingState (setWithoutCheckingName, Convert (header), value, true, true);
}
/// <summary>
/// Sets the specified header to the specified value.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the header to set.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or empty.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65,535 characters.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance doesn't allow
/// the header <paramref name="name"/>.
/// </exception>
public override void Set (string name, string value)
{
doWithCheckingState (setWithoutCheckingName, checkName (name), value, true);
}
/// <summary>
/// Converts the current <see cref="WebHeaderCollection"/> to an array of <see cref="byte"/>.
/// </summary>
/// <returns>
/// An array of <see cref="byte"/> that receives the converted current
/// <see cref="WebHeaderCollection"/>.
/// </returns>
public byte[] ToByteArray ()
{
return Encoding.UTF8.GetBytes (ToString ());
}
/// <summary>
/// Returns a <see cref="string"/> that represents the current
/// <see cref="WebHeaderCollection"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the current <see cref="WebHeaderCollection"/>.
/// </returns>
public override string ToString ()
{
var buff = new StringBuilder ();
Count.Times (i => buff.AppendFormat ("{0}: {1}\r\n", GetKey (i), Get (i)));
return buff.Append ("\r\n").ToString ();
}
#endregion
#region Explicit Interface Implementations
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize
/// the current <see cref="WebHeaderCollection"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[SecurityPermission (
SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.SerializationFormatter,
SerializationFormatter = true)]
void ISerializable.GetObjectData (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData (serializationInfo, streamingContext);
}
#endregion
}
}
#pragma warning restore 0618
| |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// 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 Castle.VSNetIntegration.CastleWizards
{
using System;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;
using Castle.VSNetIntegration.CastleWizards.Dialogs.Panels;
using Castle.VSNetIntegration.CastleWizards.Shared;
using Castle.VSNetIntegration.CastleWizards.Shared.Dialogs;
using Castle.VSNetIntegration.Shared;
using EnvDTE;
using Constants=Castle.VSNetIntegration.CastleWizards.Shared.Constants;
using EnvConstants = EnvDTE.Constants;
[Guid("9FF77D9F-E4FC-47EE-8E8B-0079FC2F2478")]
[ProgId("Castle.MonoRailProjectWizardVS8")]
[ComDefaultInterface(typeof(IDTWizard))]
[ComVisibleAttribute(true)]
public class MonoRailProjectWizard : BaseProjectWizard
{
private MRPanel optionsPanel = new MRPanel();
private ContainerIntegrationPanel integrationPanel = new ContainerIntegrationPanel();
protected override void AddPanels(WizardDialog dlg)
{
dlg.AddPanel(optionsPanel);
dlg.AddPanel(integrationPanel);
}
protected override String WizardTitle
{
get { return "New MonoRail project"; }
}
protected override void AddExtensions(IList extensions)
{
extensions.Add(new TestProjectExtension());
extensions.Add(new ATMExtension());
extensions.Add(new ARIntegrationExtension());
extensions.Add(new NHIntegrationExtension());
extensions.Add(new LoggingIntegrationExtension());
}
protected override void AddProjects(ExtensionContext context)
{
String projectFile = context.GetTemplateFileName(@"CSharp\MRProject\MRProject.csproj");
Utils.EnsureDirExists(LocalProjectPath);
Project project =
context.DteInstance.Solution.AddFromTemplate(projectFile, LocalProjectPath, ProjectName + ".csproj", Exclusive);
project.Properties.Item("DefaultNamespace").Value = NameSpace;
Utils.PerformReplacesOn(project, NameSpace, LocalProjectPath, "Controllers\\BaseController.cs");
Utils.PerformReplacesOn(project, NameSpace, LocalProjectPath, "Controllers\\HomeController.cs");
Utils.PerformReplacesOn(project, NameSpace, LocalProjectPath, "Controllers\\LoginController.cs");
Utils.PerformReplacesOn(project, NameSpace, LocalProjectPath, "Controllers\\ContactController.cs");
Utils.PerformReplacesOn(project, NameSpace, LocalProjectPath, "Models\\ContactInfo.cs");
Utils.PerformReplacesOn(project, NameSpace, LocalProjectPath, "Models\\Country.cs");
Utils.PerformReplacesOn(project, NameSpace, LocalProjectPath, "global.asax");
context.Projects.Add(Constants.ProjectMain, project);
AddGlobalApplication(project);
AddHomeViews(project);
AddLoginViews(project);
AddContactViews(project);
AddLayout(project);
AddRescue(project);
CreateXmlDomForConfig(project, MRConfigConstants.Web);
UpdateReferences(project);
UpdateProjectToUseCassini(project);
base.AddProjects(context);
}
protected override void PostProcess(ExtensionContext context)
{
ProcessWebConfig();
base.PostProcess(context);
PersistWebConfig();
}
private void ProcessWebConfig()
{
Project project = Context.Projects[Constants.ProjectMain];
XmlDocument webConfigDoc = (XmlDocument) Context.Properties[MRConfigConstants.Web];
XmlElement mrNode = (XmlElement) webConfigDoc.SelectSingleNode("configuration/monorail");
if (!HasEnabledWindsorIntegration)
{
XmlElement controllersElem = webConfigDoc.CreateElement("controllers");
XmlElement assemblyElem = webConfigDoc.CreateElement("assembly");
controllersElem.AppendChild(assemblyElem);
assemblyElem.AppendChild(webConfigDoc.CreateTextNode(ProjectName));
mrNode.AppendChild(controllersElem);
}
else
{
mrNode.SetAttribute("useWindsorIntegration", "true");
XmlNode configSectionsNode = webConfigDoc.SelectSingleNode("configuration/configSections");
XmlElement castleSectionElem = webConfigDoc.CreateElement("section");
castleSectionElem.SetAttribute("name", "castle");
castleSectionElem.SetAttribute("type", "Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor");
configSectionsNode.AppendChild(castleSectionElem);
XmlElement castleElem = webConfigDoc.CreateElement("castle");
XmlElement includePropElem = webConfigDoc.CreateElement("include");
XmlElement includeFacElem = webConfigDoc.CreateElement("include");
XmlElement includeControllersElem = webConfigDoc.CreateElement("include");
XmlElement includeComponentsElem = webConfigDoc.CreateElement("include");
includePropElem.SetAttribute("uri", "file://Config/properties.config");
includeFacElem.SetAttribute("uri", "file://Config/facilities.config");
includeControllersElem.SetAttribute("uri", "file://Config/controllers.config");
includeComponentsElem.SetAttribute("uri", "file://Config/components.config");
castleElem.AppendChild(includePropElem);
castleElem.AppendChild(includeFacElem);
castleElem.AppendChild(includeControllersElem);
castleElem.AppendChild(includeComponentsElem);
webConfigDoc.DocumentElement.AppendChild(webConfigDoc.CreateComment("Container configuration. For more information see http://www.castleproject.org/container/documentation/trunk/manual/windsorconfigref.html"));
webConfigDoc.DocumentElement.AppendChild(webConfigDoc.CreateComment("and http://www.castleproject.org/container/documentation/trunk/usersguide/compparams.html"));
webConfigDoc.DocumentElement.AppendChild(castleElem);
ProjectItem configItem = project.ProjectItems.AddFolder("config", EnvConstants.vsProjectItemKindPhysicalFolder);
// Controllers.config
String projectFile = Context.GetTemplateFileName(@"CSharp\MRProject\Config\controllers.config");
configItem.ProjectItems.AddFromTemplate(projectFile, MRConfigConstants.Controllers);
// Facilities.config
projectFile = Context.GetTemplateFileName(@"CSharp\MRProject\Config\facilities.config");
configItem.ProjectItems.AddFromTemplate(projectFile, MRConfigConstants.Facilities);
// Properties.config
projectFile = Context.GetTemplateFileName(@"CSharp\MRProject\Config\properties.config");
configItem.ProjectItems.AddFromTemplate(projectFile, MRConfigConstants.Properties);
// Components.config
projectFile = Context.GetTemplateFileName(@"CSharp\MRProject\Config\components.config");
configItem.ProjectItems.AddFromTemplate(projectFile, MRConfigConstants.Components);
Utils.CreateXmlDomForConfig(Context, project, configItem.ProjectItems.Item(MRConfigConstants.Properties),
MRConfigConstants.PropertiesConfig);
Utils.CreateXmlDomForConfig(Context, project, configItem.ProjectItems.Item(MRConfigConstants.Facilities),
MRConfigConstants.FacilitiesConfig);
Utils.CreateXmlDomForConfig(Context, project, configItem.ProjectItems.Item(MRConfigConstants.Components),
MRConfigConstants.ComponentsConfig);
XmlDocument controllersDom =
Utils.CreateXmlDomForConfig(Context, project, configItem.ProjectItems.Item(MRConfigConstants.Controllers),
MRConfigConstants.ControllersConfig);
RegisterControllers(controllersDom);
}
AddViewEngineConfiguration(webConfigDoc, mrNode);
AddRoutingConfiguration(webConfigDoc, mrNode);
}
private void RegisterControllers(XmlDocument dom)
{
RegisterController(dom, "home.controller", "HomeController");
RegisterController(dom, "login.controller", "LoginController");
RegisterController(dom, "contact.controller", "ContactController");
}
private void RegisterController(XmlDocument dom, string name, string ns)
{
XmlElement compElem = dom.CreateElement("component");
compElem.SetAttribute("id", name);
compElem.SetAttribute("type", String.Format("{0}.Controllers.{1}, {0}", Context.ProjectName, ns));
dom.DocumentElement.SelectSingleNode("components").AppendChild(compElem);
}
private void AddRoutingConfiguration(XmlDocument webConfigDoc, XmlElement mrNode)
{
if (!optionsPanel.EnableRouting) return;
XmlElement routingElem = webConfigDoc.CreateElement("routing");
XmlElement rule1 = webConfigDoc.CreateElement("rule");
XmlElement rule1pattern = webConfigDoc.CreateElement("pattern");
XmlElement rule1replace = webConfigDoc.CreateElement("replace");
routingElem.AppendChild(rule1);
rule1.AppendChild(rule1pattern);
rule1.AppendChild(rule1replace);
rule1pattern.AppendChild( webConfigDoc.CreateTextNode(@"(/blog/posts/)(\d+)/(\d+)/(.)*$") );
rule1replace.AppendChild( webConfigDoc.CreateCDataSection(" /blog/view.castle?year=$2&month=$3 ") );
mrNode.AppendChild(webConfigDoc.CreateComment("For more information on routing see http://www.castleproject.org/monorail/documentation/trunk/advanced/routing.html"));
mrNode.AppendChild(routingElem);
// Select Single Node: configuration/system.web/httpModules
XmlElement httpModules = (XmlElement) webConfigDoc.DocumentElement.SelectSingleNode("/configuration/system.web/httpModules");
// Add <add name="routing" type="Castle.MonoRail.Framework.RoutingModule, Castle.MonoRail.Framework" />
XmlElement addRoutingElem = webConfigDoc.CreateElement("add");
addRoutingElem.SetAttribute("name", "routing");
addRoutingElem.SetAttribute("type", "Castle.MonoRail.Framework.RoutingModule, Castle.MonoRail.Framework");
httpModules.InsertBefore(addRoutingElem, httpModules.FirstChild);
}
private void AddViewEngineConfiguration(XmlDocument webConfigDoc, XmlElement mrNode)
{
if (!optionsPanel.VeWebForms)
{
XmlElement viewEngineElem = webConfigDoc.CreateElement("viewEngines");
viewEngineElem.SetAttribute("viewPathRoot", "Views");
XmlElement addElem = webConfigDoc.CreateElement("add");
addElem.SetAttribute("xhtml", "false");
if (optionsPanel.VeNVelocity)
{
addElem.SetAttribute("type",
"Castle.MonoRail.Framework.Views.NVelocity.NVelocityViewEngine, Castle.MonoRail.Framework.Views.NVelocity");
}
else if (optionsPanel.VeBrail)
{
addElem.SetAttribute("type",
"Castle.MonoRail.Views.Brail.BooViewEngine, Castle.MonoRail.Views.Brail");
AddBrailCommonConfiguration(webConfigDoc);
}
else if (optionsPanel.VeWebForms)
{
addElem.SetAttribute("type",
"Castle.MonoRail.Framework.Views.Aspx.WebFormsViewEngine, Castle.MonoRail.Framework");
}
viewEngineElem.AppendChild(addElem);
mrNode.AppendChild(viewEngineElem);
}
}
private void AddBrailCommonConfiguration(XmlDocument webConfigDoc)
{
XmlNode configSectionsNode = webConfigDoc.SelectSingleNode("configuration/configSections");
XmlElement castleSectionElem = webConfigDoc.CreateElement("section");
castleSectionElem.SetAttribute("name", "brail");
castleSectionElem.SetAttribute("type", "Castle.MonoRail.Views.Brail.BrailConfigurationSection, Castle.MonoRail.Views.Brail");
configSectionsNode.AppendChild(castleSectionElem);
XmlComment comment = webConfigDoc.CreateComment("For more on Brail " +
"configuration see http://www.castleproject.org/monorail/documentation/trunk/viewengines/brail/index.html");
XmlElement brailElem = webConfigDoc.CreateElement("brail");
brailElem.SetAttribute("debug", "false");
brailElem.SetAttribute("saveToDisk", "false");
brailElem.SetAttribute("saveDirectory", "Brail_Generated_Code");
brailElem.SetAttribute("batch", "true");
brailElem.SetAttribute("commonScriptsDirectory", "CommonScripts");
XmlElement refElem = webConfigDoc.CreateElement("reference");
refElem.SetAttribute("assembly", "Castle.MonoRail.Framework");
brailElem.AppendChild(refElem);
webConfigDoc.DocumentElement.AppendChild(comment);
webConfigDoc.DocumentElement.AppendChild(brailElem);
}
private void AddGlobalApplication(Project project)
{
String globalAppFile;
if (HasEnabledWindsorIntegration)
{
globalAppFile = Context.GetTemplateFileName(@"CSharp\MRProject\ContainerGlobalApplication.cs");
}
else
{
globalAppFile = Context.GetTemplateFileName(@"CSharp\MRProject\SimpleGlobalApplication.cs");
}
project.ProjectItems.AddFromTemplate(globalAppFile, "GlobalApplication.cs");
Utils.PerformReplacesOn(project, NameSpace, LocalProjectPath, "GlobalApplication.cs");
}
private void UpdateProjectToUseCassini(Project project)
{
ConfigurationManager confMng = project.ConfigurationManager;
for (int i = 1; i <= confMng.Count; i++)
{
Configuration configuration = confMng.Item(i,".NET");
configuration.Properties.Item("StartAction").Value =
VSLangProj.prjStartAction.prjStartActionProgram;
configuration.Properties.Item("StartWorkingDirectory").Value = LocalProjectPath;
configuration.Properties.Item("StartProgram").Value = Context.CassiniLocation;
configuration.Properties.Item("StartArguments").Value =
String.Format("\"{0}\" {1} {2}", LocalProjectPath, 81, "/");
}
}
private void AddHomeViews(Project project)
{
AddView(project, "Home", "Index");
}
private void AddLoginViews(Project project)
{
AddView(project, "Login", "Index");
AddView(project, "Login", "authenticate");
}
private void AddContactViews(Project project)
{
AddView(project, "Contact", "index");
AddView(project, "Contact", "confirmation");
}
private void AddView(Project project, string controller, string action)
{
String fileExtension = ViewFileExtension();
String viewFile = String.Format("{0}.{1}", action, fileExtension);
String viewTemplateFile = Context.GetTemplateFileName(String.Format(@"CSharp\MRProject\ViewsPlaceHolder\{0}\{1}",
controller, viewFile));
project.ProjectItems.Item("Views").ProjectItems.Item(controller).ProjectItems.AddFromTemplate(viewTemplateFile, viewFile);
}
private string ViewFileExtension()
{
if (optionsPanel.VeNVelocity)
{
return "vm";
}
else if (optionsPanel.VeBrail)
{
return "brail";
}
else
{
return "aspx";
}
}
private void AddRescue(Project project)
{
String viewTemplateFile;
String viewFile;
if (optionsPanel.VeNVelocity)
{
viewFile = "generalerror.vm";
viewTemplateFile = Context.GetTemplateFileName(@"CSharp\MRProject\rescue_default.vm");
}
else if (optionsPanel.VeBrail)
{
viewFile = "generalerror.brail";
viewTemplateFile = Context.GetTemplateFileName(@"CSharp\MRProject\rescue_default.brail");
}
else
{
viewFile = "generalerror.aspx";
viewTemplateFile = Context.GetTemplateFileName(@"CSharp\MRProject\rescue_default.aspx");
}
project.ProjectItems.Item("Views").
ProjectItems.Item("rescues").
ProjectItems.AddFromTemplate(viewTemplateFile, viewFile);
}
private void AddLayout(Project project)
{
String viewTemplateFile;
String viewFile;
if (optionsPanel.VeNVelocity)
{
viewFile = "default.vm";
viewTemplateFile = Context.GetTemplateFileName(@"CSharp\MRProject\ViewsPlaceHolder\layout_default.vm");
}
else if (optionsPanel.VeBrail)
{
viewFile = "default.brail";
viewTemplateFile = Context.GetTemplateFileName(@"CSharp\MRProject\ViewsPlaceHolder\layout_default.brail");
}
else
{
viewFile = "default.aspx";
viewTemplateFile = Context.GetTemplateFileName(@"CSharp\MRProject\ViewsPlaceHolder\layout_default.aspx");
}
project.ProjectItems.Item("Views").
ProjectItems.Item("layouts").
ProjectItems.AddFromTemplate(viewTemplateFile, viewFile);
}
private void UpdateReferences(Project project)
{
if (optionsPanel.VeNVelocity)
{
Utils.AddReference(project, "Castle.MonoRail.Framework.Views.NVelocity.dll");
Utils.AddReference(project, "NVelocity.dll");
}
else if (optionsPanel.VeBrail)
{
// Utils.AddReference(project, "anrControls.Markdown.NET.dll");
// Utils.AddReference(project, "Boo.Lang.Compiler.dll");
// Utils.AddReference(project, "Boo.Lang.dll");
// Utils.AddReference(project, "Boo.Lang.Parser.dll");
Utils.AddReference(project, "Castle.MonoRail.Views.Brail");
}
if (HasEnabledWindsorIntegration)
{
Utils.AddReference(project, "Castle.DynamicProxy.dll");
Utils.AddReference(project, "Castle.MicroKernel.dll");
Utils.AddReference(project, "Castle.Core.dll");
Utils.AddReference(project, "Castle.Windsor.dll");
Utils.AddReference(project, "Castle.MonoRail.WindsorExtension.dll");
}
}
private XmlDocument CreateXmlDomForConfig(Project project, String file)
{
return Utils.CreateXmlDomForConfig(Context, project, file);
}
private void PersistWebConfig()
{
Project project = Context.Projects[Constants.ProjectMain];
IList configFiles = (IList) Context.Properties[Constants.ConfigFileList];
foreach(String file in configFiles)
{
ProjectItem item;
if (file.IndexOf("\\") > -1)
{
string[] p = file.Split('\\');
item = project.ProjectItems.Item(p[0]);
for (int i = 1; i < p.Length; i++)
{
item = item.ProjectItems.Item(p[i]);
}
}
else
{
item = project.ProjectItems.Item(file);
}
Window codeWindow = item.Open(EnvConstants.vsViewKindCode);
codeWindow.Activate();
TextDocument objTextDoc = ( ( EnvDTE.TextDocument )(
codeWindow.Document.Object( "TextDocument" ) ) );
EditPoint objEditPt = objTextDoc.StartPoint.CreateEditPoint();
objEditPt.StartOfDocument();
objEditPt.Delete(objTextDoc.EndPoint);
XmlDocument webConfigDoc = (XmlDocument) Context.Properties[file];
String tempFile = Path.GetTempFileName();
XmlTextWriter writer = new XmlTextWriter(tempFile, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.Indentation = 1;
writer.IndentChar = '\t';
webConfigDoc.Save(writer);
writer.Close();
objEditPt.InsertFromFile(tempFile);
codeWindow.Close(vsSaveChanges.vsSaveChangesYes);
File.Delete(tempFile);
}
}
private bool HasEnabledWindsorIntegration
{
get { return ((bool) Context.Properties["enableWindsorIntegration"]); }
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="PathGeometry.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media
{
sealed partial class PathGeometry : Geometry
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new PathGeometry Clone()
{
return (PathGeometry)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new PathGeometry CloneCurrentValue()
{
return (PathGeometry)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void FillRulePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PathGeometry target = ((PathGeometry) d);
target.PropertyChanged(FillRuleProperty);
}
private static void FiguresPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PathGeometry target = ((PathGeometry) d);
target.FiguresPropertyChangedHook(e);
target.PropertyChanged(FiguresProperty);
}
#region Public Properties
/// <summary>
/// FillRule - FillRule. Default value is FillRule.EvenOdd.
/// </summary>
public FillRule FillRule
{
get
{
return (FillRule) GetValue(FillRuleProperty);
}
set
{
SetValueInternal(FillRuleProperty, FillRuleBoxes.Box(value));
}
}
/// <summary>
/// Figures - PathFigureCollection. Default value is new FreezableDefaultValueFactory(PathFigureCollection.Empty).
/// </summary>
public PathFigureCollection Figures
{
get
{
return (PathFigureCollection) GetValue(FiguresProperty);
}
set
{
SetValueInternal(FiguresProperty, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new PathGeometry();
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <SecurityNote>
/// Critical: This code calls into an unsafe code block
/// TreatAsSafe: This code does not return any critical data.It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
{
ManualUpdateResource(channel, skipOnChannelCheck);
base.UpdateResource(channel, skipOnChannelCheck);
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_PATHGEOMETRY))
{
Transform vTransform = Transform;
if (vTransform != null) ((DUCE.IResource)vTransform).AddRefOnChannel(channel);
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
}
return _duceResource.GetHandle(channel);
}
internal override void ReleaseOnChannelCore(DUCE.Channel channel)
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
Transform vTransform = Transform;
if (vTransform != null) ((DUCE.IResource)vTransform).ReleaseOnChannel(channel);
ReleaseOnChannelAnimations(channel);
}
}
internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
{
// Note that we are in a lock here already.
return _duceResource.GetHandle(channel);
}
internal override int GetChannelCountCore()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
internal override DUCE.Channel GetChannelCore(int index)
{
// Note that we are in a lock here already.
return _duceResource.GetChannel(index);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
//
// This property finds the correct initial size for the _effectiveValues store on the
// current DependencyObject as a performance optimization
//
// This includes:
// Figures
//
internal override int EffectiveValuesInitialSize
{
get
{
return 1;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the PathGeometry.FillRule property.
/// </summary>
public static readonly DependencyProperty FillRuleProperty;
/// <summary>
/// The DependencyProperty for the PathGeometry.Figures property.
/// </summary>
public static readonly DependencyProperty FiguresProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
internal const FillRule c_FillRule = FillRule.EvenOdd;
internal static PathFigureCollection s_Figures = PathFigureCollection.Empty;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static PathGeometry()
{
// We check our static default fields which are of type Freezable
// to make sure that they are not mutable, otherwise we will throw
// if these get touched by more than one thread in the lifetime
// of your app. (Windows OS Bug #947272)
//
Debug.Assert(s_Figures == null || s_Figures.IsFrozen,
"Detected context bound default value PathGeometry.s_Figures (See OS Bug #947272).");
// Initializations
Type typeofThis = typeof(PathGeometry);
FillRuleProperty =
RegisterProperty("FillRule",
typeof(FillRule),
typeofThis,
FillRule.EvenOdd,
new PropertyChangedCallback(FillRulePropertyChanged),
new ValidateValueCallback(System.Windows.Media.ValidateEnums.IsFillRuleValid),
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
FiguresProperty =
RegisterProperty("Figures",
typeof(PathFigureCollection),
typeofThis,
new FreezableDefaultValueFactory(PathFigureCollection.Empty),
new PropertyChangedCallback(FiguresPropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
/*
The MIT License(MIT)
Copyright(c) 2015 IgorSoft
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.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Authentication;
using System.Threading.Tasks;
using Newtonsoft.Json;
using OneDrive;
using IgorSoft.CloudFS.Authentication;
using static IgorSoft.CloudFS.Authentication.OAuth.Constants;
namespace IgorSoft.CloudFS.Gateways.OneDrive_Legacy.OAuth
{
internal static class OAuthAuthenticator
{
private const string LIVE_LOGIN_DESKTOP_URI = "https://login.live.com/oauth20_desktop.srf";
private const string LIVE_LOGIN_AUTHORIZE_URI = "https://login.live.com/oauth20_authorize.srf";
private const string LIVE_LOGIN_TOKEN_URI = "https://login.live.com/oauth20_token.srf";
private const string ONEDRIVE_API_URI = "https://api.onedrive.com/v1.0";
private static BrowserLogOn logOn;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Used for JSON deserialization")]
private class AppTokenResponse
{
[JsonProperty(Parameters.TokenType)]
public string TokenType { get; set; }
[JsonProperty(Parameters.Scope)]
public string Scope { get; set; }
[JsonProperty(Parameters.AccessToken)]
public string AccessToken { get; set; }
[JsonProperty(Parameters.ExpiresIn)]
public int AccessTokenExpirationDuration { get; set; }
[JsonProperty(Parameters.RefreshToken)]
public string RefreshToken { get; set; }
}
private static string LoadRefreshToken(string account, string settingsPassPhrase)
{
var refreshTokens = Properties.Settings.Default.RefreshTokens;
var setting = refreshTokens?.SingleOrDefault(s => s.Account == account);
return setting?.RefreshToken.DecryptUsing(settingsPassPhrase);
}
private static void SaveRefreshToken(string account, string refreshToken, string settingsPassPhrase)
{
var refreshTokens = Properties.Settings.Default.RefreshTokens;
if (refreshTokens != null) {
var setting = refreshTokens.SingleOrDefault(s => s.Account == account);
if (setting != null)
refreshTokens.Remove(setting);
} else {
refreshTokens = Properties.Settings.Default.RefreshTokens = new System.Collections.ObjectModel.Collection<OAuth.RefreshTokenSetting>();
}
refreshTokens.Insert(0, new RefreshTokenSetting() { Account = account, RefreshToken = refreshToken.EncryptUsing(settingsPassPhrase) });
Properties.Settings.Default.Save();
}
private static Uri GetAuthenticationUri(string clientId)
{
var queryStringBuilder = new global::OneDrive.QueryStringBuilder();
queryStringBuilder.Add(Parameters.ClientId, clientId);
queryStringBuilder.Add(Parameters.Scope, string.Join(" ", (new [] { Scope.Basic, Scope.OfflineAccess, Scope.Signin, Scope.OneDriveReadWrite }).Select(s => s.GetDescription())));
queryStringBuilder.Add(Parameters.RedirectUri, LIVE_LOGIN_DESKTOP_URI);
queryStringBuilder.Add(Parameters.ResponseType, ResponseTypes.Code);
queryStringBuilder.Add("display", "popup");
return new UriBuilder(LIVE_LOGIN_AUTHORIZE_URI) { Query = queryStringBuilder.ToString() }.Uri;
}
private static async Task<AppTokenResponse> RedeemAccessTokenAsync(string clientId, string clientSecret, string code)
{
var queryStringBuilder = new global::OneDrive.QueryStringBuilder();
queryStringBuilder.Add(Parameters.ClientId, clientId);
queryStringBuilder.Add(Parameters.ClientSecret, clientSecret);
queryStringBuilder.Add(Parameters.RedirectUri, LIVE_LOGIN_DESKTOP_URI);
queryStringBuilder.Add(Parameters.Code, code);
queryStringBuilder.Add(Parameters.GrantType, GrantTypes.AuthorizationCode);
var response = await PostQueryAsync(LIVE_LOGIN_TOKEN_URI, queryStringBuilder.ToString());
return JsonConvert.DeserializeObject<AppTokenResponse>(response);
}
private static async Task<AppTokenResponse> RedeemRefreshTokenAsync(string clientId, string clientSecret, string refreshToken)
{
var queryStringBuilder = new global::OneDrive.QueryStringBuilder();
queryStringBuilder.Add(Parameters.ClientId, clientId);
queryStringBuilder.Add(Parameters.ClientSecret, clientSecret);
queryStringBuilder.Add(Parameters.RedirectUri, LIVE_LOGIN_DESKTOP_URI);
queryStringBuilder.Add(Parameters.RefreshToken, refreshToken);
queryStringBuilder.Add(Parameters.GrantType, GrantTypes.RefreshToken);
var response = await PostQueryAsync(LIVE_LOGIN_TOKEN_URI, queryStringBuilder.ToString());
return JsonConvert.DeserializeObject<AppTokenResponse>(response);
}
private static async Task<string> PostQueryAsync(string uriString, string queryString)
{
var httpWebRequest = WebRequest.CreateHttp(uriString);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
var stream = await httpWebRequest.GetRequestStreamAsync();
using (var writer = new StreamWriter(stream)) {
await writer.WriteAsync(queryString);
await writer.FlushAsync();
}
var response = await httpWebRequest.GetResponseAsync() as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.OK) {
using (var reader = new StreamReader(response.GetResponseStream())) {
return await reader.ReadToEndAsync();
}
}
return null;
}
private static string GetAuthCode(string account, Uri authenticationUri, Uri redirectUri)
{
string authCode = null;
if (logOn == null)
logOn = new BrowserLogOn(AsyncOperationManager.SynchronizationContext);
EventHandler<AuthenticatedEventArgs> callback = (s, e) => authCode = e.Parameters[Parameters.Code]?.TrimStart('M');
logOn.Authenticated += callback;
logOn.Show("OneDrive-Legacy", account, authenticationUri, redirectUri);
logOn.Authenticated -= callback;
return authCode;
}
public static async Task<ODConnection> LoginAsync(string account, string code, string settingsPassPhrase)
{
if (string.IsNullOrEmpty(account))
throw new ArgumentNullException(nameof(account));
var refreshToken = LoadRefreshToken(account, settingsPassPhrase);
AppTokenResponse response = null;
if (!string.IsNullOrEmpty(refreshToken))
response = await RedeemRefreshTokenAsync(Secrets.CLIENT_ID, Secrets.CLIENT_SECRET, refreshToken);
if (response == null) {
if (string.IsNullOrEmpty(code)) {
var authenticationUri = GetAuthenticationUri(Secrets.CLIENT_ID);
code = GetAuthCode(account, authenticationUri, new Uri(LIVE_LOGIN_DESKTOP_URI));
if (string.IsNullOrEmpty(code))
throw new AuthenticationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.RetrieveAuthenticationCodeFromUri, authenticationUri.ToString()));
}
response = await RedeemAccessTokenAsync(Secrets.CLIENT_ID, Secrets.CLIENT_SECRET, code);
}
SaveRefreshToken(account, response?.RefreshToken ?? refreshToken, settingsPassPhrase);
return response != null ? new ODConnection(ONEDRIVE_API_URI, response.AccessToken) : null;
}
public static void PurgeRefreshToken(string account)
{
var refreshTokens = Properties.Settings.Default.RefreshTokens;
if (refreshTokens == null)
return;
var settings = refreshTokens.Where(s => account == null || s.Account == account).ToArray();
foreach (var setting in settings)
refreshTokens.Remove(setting);
if (!refreshTokens.Any())
Properties.Settings.Default.RefreshTokens = null;
Properties.Settings.Default.Save();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace HackathonBackend.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// 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.Linq;
namespace System.Collections.Immutable
{
/// <summary>
/// A set of initialization methods for instances of <see cref="ImmutableSortedDictionary{TKey, TValue}"/>.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public static class ImmutableSortedDictionary
{
/// <summary>
/// Returns an empty collection.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <returns>The immutable collection.</returns>
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>()
{
return ImmutableSortedDictionary<TKey, TValue>.Empty;
}
/// <summary>
/// Returns an empty collection.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <returns>The immutable collection.</returns>
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>(IComparer<TKey> keyComparer)
{
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer);
}
/// <summary>
/// Returns an empty collection.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <returns>The immutable collection.</returns>
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer);
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return ImmutableSortedDictionary<TKey, TValue>.Empty.AddRange(items);
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IComparer<TKey> keyComparer, IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer).AddRange(items);
}
/// <summary>
/// Creates a new immutable collection prefilled with the specified items.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="items">The items to prepopulate.</param>
/// <returns>The new immutable collection.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(items);
}
/// <summary>
/// Creates a new immutable sorted dictionary builder.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <returns>The immutable collection builder.</returns>
[Pure]
public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>()
{
return Create<TKey, TValue>().ToBuilder();
}
/// <summary>
/// Creates a new immutable sorted dictionary builder.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <returns>The immutable collection builder.</returns>
[Pure]
public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IComparer<TKey> keyComparer)
{
return Create<TKey, TValue>(keyComparer).ToBuilder();
}
/// <summary>
/// Creates a new immutable sorted dictionary builder.
/// </summary>
/// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <returns>The immutable collection builder.</returns>
[Pure]
public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
return Create<TKey, TValue>(keyComparer, valueComparer).ToBuilder();
}
/// <summary>
/// Constructs an immutable sorted dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <typeparam name="TValue">The type of value in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param>
/// <param name="keyComparer">The key comparer to use for the map.</param>
/// <param name="valueComparer">The value comparer to use for the map.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(source, nameof(source));
Requires.NotNull(keySelector, nameof(keySelector));
Requires.NotNull(elementSelector, nameof(elementSelector));
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer)
.AddRange(source.Select(element => new KeyValuePair<TKey, TValue>(keySelector(element), elementSelector(element))));
}
/// <summary>
/// Returns an immutable copy of the current contents of the builder's collection.
/// </summary>
/// <param name="builder">The builder to create the immutable map from.</param>
/// <returns>An immutable map.</returns>
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this ImmutableSortedDictionary<TKey, TValue>.Builder builder)
{
Requires.NotNull(builder, nameof(builder));
return builder.ToImmutable();
}
/// <summary>
/// Constructs an immutable sorted dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <typeparam name="TValue">The type of value in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param>
/// <param name="keyComparer">The key comparer to use for the map.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IComparer<TKey> keyComparer)
{
return ToImmutableSortedDictionary(source, keySelector, elementSelector, keyComparer, null);
}
/// <summary>
/// Constructs an immutable sorted dictionary based on some transformation of a sequence.
/// </summary>
/// <typeparam name="TSource">The type of element in the sequence.</typeparam>
/// <typeparam name="TKey">The type of key in the resulting map.</typeparam>
/// <typeparam name="TValue">The type of value in the resulting map.</typeparam>
/// <param name="source">The sequence to enumerate to generate the map.</param>
/// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param>
/// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param>
/// <returns>The immutable map.</returns>
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector)
{
return ToImmutableSortedDictionary(source, keySelector, elementSelector, null, null);
}
/// <summary>
/// Creates an immutable sorted dictionary given a sequence of key=value pairs.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="source">The sequence of key=value pairs.</param>
/// <param name="keyComparer">The key comparer to use when building the immutable map.</param>
/// <param name="valueComparer">The value comparer to use for the immutable map.</param>
/// <returns>An immutable map.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(source, nameof(source));
Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null);
var existingDictionary = source as ImmutableSortedDictionary<TKey, TValue>;
if (existingDictionary != null)
{
return existingDictionary.WithComparers(keyComparer, valueComparer);
}
return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(source);
}
/// <summary>
/// Creates an immutable sorted dictionary given a sequence of key=value pairs.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="source">The sequence of key=value pairs.</param>
/// <param name="keyComparer">The key comparer to use when building the immutable map.</param>
/// <returns>An immutable map.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IComparer<TKey> keyComparer)
{
return ToImmutableSortedDictionary(source, keyComparer, null);
}
/// <summary>
/// Creates an immutable sorted dictionary given a sequence of key=value pairs.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="source">The sequence of key=value pairs.</param>
/// <returns>An immutable map.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
[Pure]
public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source)
{
return ToImmutableSortedDictionary(source, null, null);
}
}
}
| |
// 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.Immutable;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Moq;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion
{
public abstract class AbstractCompletionProviderTests<TWorkspaceFixture> : TestBase, IClassFixture<TWorkspaceFixture>
where TWorkspaceFixture : TestWorkspaceFixture, new()
{
protected readonly Mock<ICompletionSession> MockCompletionSession;
protected TWorkspaceFixture WorkspaceFixture;
protected AbstractCompletionProviderTests(TWorkspaceFixture workspaceFixture)
{
MockCompletionSession = new Mock<ICompletionSession>(MockBehavior.Strict);
this.WorkspaceFixture = workspaceFixture;
}
public override void Dispose()
{
this.WorkspaceFixture.CloseTextViewAsync().Wait();
base.Dispose();
}
protected static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position)
{
var service = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent;
return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty;
}
internal CompletionServiceWithProviders GetCompletionService(Workspace workspace)
{
return CreateCompletionService(workspace, ImmutableArray.Create(CreateCompletionProvider()));
}
internal abstract CompletionServiceWithProviders CreateCompletionService(
Workspace workspace, ImmutableArray<CompletionProvider> exclusiveProviders);
protected abstract string ItemPartiallyWritten(string expectedItemOrNull);
protected abstract Task<TestWorkspace> CreateWorkspaceAsync(string fileContents);
protected abstract Task BaseVerifyWorkerAsync(
string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull,
SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority);
internal static CompletionHelper GetCompletionHelper(Document document)
{
return CompletionHelper.GetHelper(document);
}
internal Task<CompletionList> GetCompletionListAsync(
CompletionService service,
Document document, int position, CompletionTrigger triggerInfo, OptionSet options = null)
{
return service.GetCompletionsAsync(document, position, triggerInfo, options: options);
}
protected async Task CheckResultsAsync(
Document document, int position, string expectedItemOrNull, string expectedDescriptionOrNull, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority)
{
var code = (await document.GetTextAsync()).ToString();
CompletionTrigger trigger = CompletionTrigger.Default;
if (usePreviousCharAsTrigger)
{
trigger = CompletionTrigger.CreateInsertionTrigger(insertedCharacter: code.ElementAt(position - 1));
}
var completionService = GetCompletionService(document.Project.Solution.Workspace);
var completionList = await GetCompletionListAsync(completionService, document, position, trigger);
var items = completionList == null ? ImmutableArray<CompletionItem>.Empty : completionList.Items;
if (checkForAbsence)
{
if (items == null)
{
return;
}
if (expectedItemOrNull == null)
{
Assert.Empty(items);
}
else
{
AssertEx.None(
items,
c => CompareItems(c.DisplayText, expectedItemOrNull) &&
(expectedDescriptionOrNull != null ? completionService.GetDescriptionAsync(document, c).Result.Text == expectedDescriptionOrNull : true));
}
}
else
{
if (expectedItemOrNull == null)
{
Assert.NotEmpty(items);
}
else
{
AssertEx.Any(items, c => CompareItems(c.DisplayText, expectedItemOrNull)
&& (expectedDescriptionOrNull != null ? completionService.GetDescriptionAsync(document, c).Result.Text == expectedDescriptionOrNull : true)
&& (glyph.HasValue ? c.Tags.SequenceEqual(GlyphTags.GetTags((Glyph)glyph.Value)) : true)
&& (matchPriority.HasValue ? (int)c.Rules.MatchPriority == matchPriority.Value : true ));
}
}
}
private Task VerifyAsync(
string markup, string expectedItemOrNull, string expectedDescriptionOrNull,
SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority)
{
string code;
int position;
MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out code, out position);
return VerifyWorkerAsync(
code, position, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority);
}
protected async Task VerifyCustomCommitProviderAsync(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind? sourceCodeKind = null, char? commitChar = null)
{
string code;
int position;
MarkupTestFile.GetPosition(markupBeforeCommit.NormalizeLineEndings(), out code, out position);
if (sourceCodeKind.HasValue)
{
await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, sourceCodeKind.Value, commitChar);
}
else
{
await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Regular, commitChar);
await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Script, commitChar);
}
}
protected async Task VerifyProviderCommitAsync(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit,
char? commitChar, string textTypedSoFar, SourceCodeKind? sourceCodeKind = null)
{
string code;
int position;
MarkupTestFile.GetPosition(markupBeforeCommit.NormalizeLineEndings(), out code, out position);
expectedCodeAfterCommit = expectedCodeAfterCommit.NormalizeLineEndings();
if (sourceCodeKind.HasValue)
{
await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, sourceCodeKind.Value);
}
else
{
await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, SourceCodeKind.Regular);
await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, SourceCodeKind.Script);
}
}
protected virtual bool CompareItems(string actualItem, string expectedItem)
{
return actualItem.Equals(expectedItem);
}
protected async Task VerifyItemExistsAsync(
string markup, string expectedItem, string expectedDescriptionOrNull = null,
SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false,
int? glyph = null, int? matchPriority = null)
{
if (sourceCodeKind.HasValue)
{
await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull,
sourceCodeKind.Value, usePreviousCharAsTrigger, checkForAbsence: false,
glyph: glyph, matchPriority: matchPriority);
}
else
{
await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority);
await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Script, usePreviousCharAsTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority);
}
}
protected async Task VerifyItemIsAbsentAsync(
string markup, string expectedItem, string expectedDescriptionOrNull = null,
SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false)
{
if (sourceCodeKind.HasValue)
{
await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind.Value, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null);
}
else
{
await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null);
await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Script, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null);
}
}
protected async Task VerifyAnyItemExistsAsync(
string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false)
{
if (sourceCodeKind.HasValue)
{
await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind.Value, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null);
}
else
{
await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null);
await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null);
}
}
protected async Task VerifyNoItemsExistAsync(string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false)
{
if (sourceCodeKind.HasValue)
{
await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind.Value, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null);
}
else
{
await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null);
await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null);
}
}
internal abstract CompletionProvider CreateCompletionProvider();
/// <summary>
/// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts.
/// </summary>
/// <param name="code">The source code (not markup).</param>
/// <param name="expectedItemOrNull">The expected item. If this is null, verifies that *any* item shows up for this CompletionProvider (or no items show up if checkForAbsence is true).</param>
/// <param name="expectedDescriptionOrNull">If this is null, the Description for the item is ignored.</param>
/// <param name="usePreviousCharAsTrigger">Whether or not the previous character in markup should be used to trigger IntelliSense for this provider. If false, invokes it through the invoke IntelliSense command.</param>
/// <param name="checkForAbsence">If true, checks for absence of a specific item (or that no items are returned from this CompletionProvider)</param>
protected virtual async Task VerifyWorkerAsync(
string code, int position,
string expectedItemOrNull, string expectedDescriptionOrNull,
SourceCodeKind sourceCodeKind,
bool usePreviousCharAsTrigger, bool checkForAbsence,
int? glyph, int? matchPriority)
{
Glyph? expectedGlyph = null;
if (glyph.HasValue)
{
expectedGlyph = (Glyph)glyph.Value;
}
var document1 = await WorkspaceFixture.UpdateDocumentAsync(code, sourceCodeKind);
await CheckResultsAsync(document1, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority);
if (await CanUseSpeculativeSemanticModelAsync(document1, position))
{
var document2 = await WorkspaceFixture.UpdateDocumentAsync(code, sourceCodeKind, cleanBeforeUpdate: false);
await CheckResultsAsync(document2, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority);
}
}
/// <summary>
/// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts.
/// </summary>
/// <param name="codeBeforeCommit">The source code (not markup).</param>
/// <param name="position">Position where intellisense is invoked.</param>
/// <param name="itemToCommit">The item to commit from the completion provider.</param>
/// <param name="expectedCodeAfterCommit">The expected code after commit.</param>
protected virtual async Task VerifyCustomCommitProviderWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind sourceCodeKind, char? commitChar = null)
{
var document1 = await WorkspaceFixture.UpdateDocumentAsync(codeBeforeCommit, sourceCodeKind);
await VerifyCustomCommitProviderCheckResultsAsync(document1, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar);
if (await CanUseSpeculativeSemanticModelAsync(document1, position))
{
var document2 = await WorkspaceFixture.UpdateDocumentAsync(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false);
await VerifyCustomCommitProviderCheckResultsAsync(document2, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar);
}
}
private async Task VerifyCustomCommitProviderCheckResultsAsync(Document document, string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar)
{
var workspace = await WorkspaceFixture.GetWorkspaceAsync();
SetWorkspaceOptions(workspace);
var textBuffer = workspace.Documents.Single().TextBuffer;
var service = GetCompletionService(workspace);
var items = (await GetCompletionListAsync(service, document, position, CompletionTrigger.Default)).Items;
var firstItem = items.First(i => CompareItems(i.DisplayText, itemToCommit));
var customCommitCompletionProvider = service.ExclusiveProviders?[0] as ICustomCommitCompletionProvider;
if (customCommitCompletionProvider != null)
{
var completionRules = GetCompletionHelper(document);
var textView = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().GetTextView();
VerifyCustomCommitWorker(service, customCommitCompletionProvider, firstItem, completionRules, textView, textBuffer, codeBeforeCommit, expectedCodeAfterCommit, commitChar);
}
else
{
await VerifyCustomCommitWorkerAsync(service, document, firstItem, codeBeforeCommit, expectedCodeAfterCommit, commitChar);
}
}
protected virtual void SetWorkspaceOptions(TestWorkspace workspace)
{
}
internal async Task VerifyCustomCommitWorkerAsync(
CompletionServiceWithProviders service,
Document document,
CompletionItem completionItem,
string codeBeforeCommit,
string expectedCodeAfterCommit,
char? commitChar = null)
{
int expectedCaretPosition;
string actualExpectedCode = null;
MarkupTestFile.GetPosition(expectedCodeAfterCommit, out actualExpectedCode, out expectedCaretPosition);
if (commitChar.HasValue &&
!Controller.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value, commitChar.Value.ToString()))
{
Assert.Equal(codeBeforeCommit, actualExpectedCode);
return;
}
var commit = await service.GetChangeAsync(document, completionItem, commitChar, CancellationToken.None);
var text = await document.GetTextAsync();
var newText = text.WithChanges(commit.TextChange);
var newDoc = document.WithText(newText);
document.Project.Solution.Workspace.TryApplyChanges(newDoc.Project.Solution);
var textBuffer = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().TextBuffer;
var textView = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().GetTextView();
string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString();
var caretPosition = commit.NewPosition != null ? commit.NewPosition.Value : textView.Caret.Position.BufferPosition.Position;
Assert.Equal(actualExpectedCode, actualCodeAfterCommit);
Assert.Equal(expectedCaretPosition, caretPosition);
}
internal virtual void VerifyCustomCommitWorker(
CompletionService service,
ICustomCommitCompletionProvider customCommitCompletionProvider,
CompletionItem completionItem,
CompletionHelper completionRules,
ITextView textView,
ITextBuffer textBuffer,
string codeBeforeCommit,
string expectedCodeAfterCommit,
char? commitChar = null)
{
int expectedCaretPosition;
string actualExpectedCode = null;
MarkupTestFile.GetPosition(expectedCodeAfterCommit, out actualExpectedCode, out expectedCaretPosition);
if (commitChar.HasValue &&
!Controller.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value, commitChar.Value.ToString()))
{
Assert.Equal(codeBeforeCommit, actualExpectedCode);
return;
}
customCommitCompletionProvider.Commit(completionItem, textView, textBuffer, textView.TextSnapshot, commitChar);
string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString();
var caretPosition = textView.Caret.Position.BufferPosition.Position;
Assert.Equal(actualExpectedCode, actualCodeAfterCommit);
Assert.Equal(expectedCaretPosition, caretPosition);
}
/// <summary>
/// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts.
/// </summary>
/// <param name="codeBeforeCommit">The source code (not markup).</param>
/// <param name="position">Position where intellisense is invoked.</param>
/// <param name="itemToCommit">The item to commit from the completion provider.</param>
/// <param name="expectedCodeAfterCommit">The expected code after commit.</param>
protected virtual async Task VerifyProviderCommitWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit,
char? commitChar, string textTypedSoFar, SourceCodeKind sourceCodeKind)
{
var document1 = await WorkspaceFixture.UpdateDocumentAsync(codeBeforeCommit, sourceCodeKind);
await VerifyProviderCommitCheckResultsAsync(document1, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar);
if (await CanUseSpeculativeSemanticModelAsync(document1, position))
{
var document2 = await WorkspaceFixture.UpdateDocumentAsync(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false);
await VerifyProviderCommitCheckResultsAsync(document2, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar);
}
}
private async Task VerifyProviderCommitCheckResultsAsync(
Document document, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitCharOpt, string textTypedSoFar)
{
var workspace = await WorkspaceFixture.GetWorkspaceAsync();
var textBuffer = workspace.Documents.Single().TextBuffer;
var textSnapshot = textBuffer.CurrentSnapshot.AsText();
var service = GetCompletionService(workspace);
var items = (await GetCompletionListAsync(service, document, position, CompletionTrigger.Default)).Items;
var firstItem = items.First(i => CompareItems(i.DisplayText, itemToCommit));
var completionRules = GetCompletionHelper(document);
var commitChar = commitCharOpt ?? '\t';
var text = await document.GetTextAsync();
if (commitChar == '\t' ||
Controller.IsCommitCharacter(service.GetRules(), firstItem, commitChar, textTypedSoFar + commitChar))
{
var textChange = (await service.GetChangeAsync(document, firstItem, commitChar, CancellationToken.None)).TextChange;
// Adjust TextChange to include commit character, so long as it isn't TAB.
if (commitChar != '\t')
{
textChange = new TextChange(textChange.Span, textChange.NewText.TrimEnd(commitChar) + commitChar);
}
text = text.WithChanges(textChange);
}
else
{
// nothing was committed, but we should insert the commit character.
var textChange = new TextChange(new TextSpan(firstItem.Span.End, 0), commitChar.ToString());
text = text.WithChanges(textChange);
}
Assert.Equal(expectedCodeAfterCommit, text.ToString());
}
protected async Task VerifyItemInEditorBrowsableContextsAsync(
string markup, string referencedCode, string item, int expectedSymbolsSameSolution, int expectedSymbolsMetadataReference,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false)
{
await VerifyItemWithMetadataReferenceAsync(markup, referencedCode, item, expectedSymbolsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers);
await VerifyItemWithProjectReferenceAsync(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers);
// If the source and referenced languages are different, then they cannot be in the same project
if (sourceLanguage == referencedLanguage)
{
await VerifyItemInSameProjectAsync(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, hideAdvancedMembers);
}
}
private Task VerifyItemWithMetadataReferenceAsync(string markup, string metadataReferenceCode, string expectedItem, int expectedSymbols,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataReferenceCode));
return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers);
}
protected Task VerifyItemWithAliasedMetadataReferencesAsync(string markup, string metadataAlias, string expectedItem, int expectedSymbols,
string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" Aliases=""{3}, global"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose"">
<Document FilePath=""ReferencedDocument"">
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataAlias));
return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers);
}
protected Task VerifyItemWithProjectReferenceAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<ProjectReference>ReferencedProject</ProjectReference>
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
<Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode));
return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers);
}
private Task VerifyItemInSameProjectAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, bool hideAdvancedMembers)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<Document FilePath=""ReferencedDocument"">
{2}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup), SecurityElement.Escape(referencedCode));
return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers);
}
private async Task VerifyItemWithReferenceWorkerAsync(
string xmlString, string expectedItem, int expectedSymbols, bool hideAdvancedMembers)
{
using (var testWorkspace = await TestWorkspace.CreateAsync(xmlString))
{
var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var solution = testWorkspace.CurrentSolution;
var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id;
var document = solution.GetDocument(documentId);
testWorkspace.Options = testWorkspace.Options.WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers);
var triggerInfo = CompletionTrigger.Default;
var completionService = GetCompletionService(testWorkspace);
var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo);
if (expectedSymbols >= 1)
{
AssertEx.Any(completionList.Items, c => CompareItems(c.DisplayText, expectedItem));
var item = completionList.Items.First(c => CompareItems(c.DisplayText, expectedItem));
var description = await completionService.GetDescriptionAsync(document, item);
if (expectedSymbols == 1)
{
Assert.DoesNotContain("+", description.Text, StringComparison.Ordinal);
}
else
{
Assert.Contains(GetExpectedOverloadSubstring(expectedSymbols), description.Text, StringComparison.Ordinal);
}
}
else
{
if (completionList != null)
{
AssertEx.None(completionList.Items, c => CompareItems(c.DisplayText, expectedItem));
}
}
}
}
protected Task VerifyItemWithMscorlib45Async(string markup, string expectedItem, string expectedDescription, string sourceLanguage)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferencesNet45=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(markup));
return VerifyItemWithMscorlib45WorkerAsync(xmlString, expectedItem, expectedDescription);
}
private async Task VerifyItemWithMscorlib45WorkerAsync(
string xmlString, string expectedItem, string expectedDescription)
{
using (var testWorkspace = await TestWorkspace.CreateAsync(xmlString))
{
var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var solution = testWorkspace.CurrentSolution;
var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id;
var document = solution.GetDocument(documentId);
var triggerInfo = CompletionTrigger.Default;
var completionService = GetCompletionService(testWorkspace);
var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo);
var item = completionList.Items.FirstOrDefault(i => i.DisplayText == expectedItem);
Assert.Equal(expectedDescription, (await completionService.GetDescriptionAsync(document, item)).Text);
}
}
private const char NonBreakingSpace = (char)0x00A0;
private string GetExpectedOverloadSubstring(int expectedSymbols)
{
if (expectedSymbols <= 1)
{
throw new ArgumentOutOfRangeException(nameof(expectedSymbols));
}
return "+" + NonBreakingSpace + (expectedSymbols - 1) + NonBreakingSpace + FeaturesResources.overload;
}
protected async Task VerifyItemInLinkedFilesAsync(string xmlString, string expectedItem, string expectedDescription)
{
using (var testWorkspace = await TestWorkspace.CreateAsync(xmlString))
{
var position = testWorkspace.Documents.First().CursorPosition.Value;
var solution = testWorkspace.CurrentSolution;
var textContainer = testWorkspace.Documents.First().TextBuffer.AsTextContainer();
var currentContextDocumentId = testWorkspace.GetDocumentIdInCurrentContext(textContainer);
var document = solution.GetDocument(currentContextDocumentId);
var triggerInfo = CompletionTrigger.Default;
var completionService = GetCompletionService(testWorkspace);
var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo);
var item = completionList.Items.Single(c => c.DisplayText == expectedItem);
Assert.NotNull(item);
if (expectedDescription != null)
{
var actualDescription = (await completionService.GetDescriptionAsync(document, item)).Text;
Assert.Equal(expectedDescription, actualDescription);
}
}
}
protected Task VerifyAtPositionAsync(
string code, int position, string insertText, bool usePreviousCharAsTrigger,
string expectedItemOrNull, string expectedDescriptionOrNull,
SourceCodeKind sourceCodeKind, bool checkForAbsence,
int? glyph, int? matchPriority)
{
code = code.Substring(0, position) + insertText + code.Substring(position);
position += insertText.Length;
return BaseVerifyWorkerAsync(code, position,
expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence,
glyph, matchPriority);
}
protected Task VerifyAtPositionAsync(
string code, int position, bool usePreviousCharAsTrigger,
string expectedItemOrNull, string expectedDescriptionOrNull,
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority)
{
return VerifyAtPositionAsync(
code, position, string.Empty, usePreviousCharAsTrigger,
expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence,
glyph, matchPriority);
}
protected async Task VerifyAtEndOfFileAsync(
string code, int position, string insertText, bool usePreviousCharAsTrigger,
string expectedItemOrNull, string expectedDescriptionOrNull,
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority)
{
// only do this if the placeholder was at the end of the text.
if (code.Length != position)
{
return;
}
code = code.Substring(startIndex: 0, length: position) + insertText;
position += insertText.Length;
await BaseVerifyWorkerAsync(
code, position, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority);
}
protected Task VerifyAtPosition_ItemPartiallyWrittenAsync(
string code, int position, bool usePreviousCharAsTrigger,
string expectedItemOrNull, string expectedDescriptionOrNull,
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority)
{
return VerifyAtPositionAsync(
code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger,
expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, checkForAbsence, glyph, matchPriority);
}
protected Task VerifyAtEndOfFileAsync(
string code, int position, bool usePreviousCharAsTrigger,
string expectedItemOrNull, string expectedDescriptionOrNull,
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority)
{
return VerifyAtEndOfFileAsync(code, position, string.Empty, usePreviousCharAsTrigger,
expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, checkForAbsence, glyph, matchPriority);
}
protected Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync(
string code, int position, bool usePreviousCharAsTrigger,
string expectedItemOrNull, string expectedDescriptionOrNull,
SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority)
{
return VerifyAtEndOfFileAsync(
code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger,
expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence,
glyph, matchPriority);
}
protected async Task VerifyTextualTriggerCharacterAsync(
string markup, bool shouldTriggerWithTriggerOnLettersEnabled, bool shouldTriggerWithTriggerOnLettersDisabled)
{
await VerifyTextualTriggerCharacterWorkerAsync(markup, expectedTriggerCharacter: shouldTriggerWithTriggerOnLettersEnabled, triggerOnLetter: true);
await VerifyTextualTriggerCharacterWorkerAsync(markup, expectedTriggerCharacter: shouldTriggerWithTriggerOnLettersDisabled, triggerOnLetter: false);
}
private async Task VerifyTextualTriggerCharacterWorkerAsync(
string markup, bool expectedTriggerCharacter, bool triggerOnLetter)
{
using (var workspace = await CreateWorkspaceAsync(markup))
{
var document = workspace.Documents.Single();
var position = document.CursorPosition.Value;
var text = document.TextBuffer.CurrentSnapshot.AsText();
var options = workspace.Options.WithChangedOption(
CompletionOptions.TriggerOnTypingLetters, document.Project.Language, triggerOnLetter);
var trigger = CompletionTrigger.CreateInsertionTrigger(text[position]);
var service = GetCompletionService(workspace);
var isTextualTriggerCharacterResult = service.ShouldTriggerCompletion(text, position + 1, trigger, options: options);
if (expectedTriggerCharacter)
{
var assertText = "'" + text.ToString(new TextSpan(position, 1)) + "' expected to be textual trigger character";
Assert.True(isTextualTriggerCharacterResult, assertText);
}
else
{
var assertText = "'" + text.ToString(new TextSpan(position, 1)) + "' expected to NOT be textual trigger character";
Assert.False(isTextualTriggerCharacterResult, assertText);
}
}
}
protected async Task VerifyCommonCommitCharactersAsync(string initialMarkup, string textTypedSoFar)
{
var commitCharacters = new[]
{
' ', '{', '}', '[', ']', '(', ')', '.', ',', ':',
';', '+', '-', '*', '/', '%', '&', '|', '^', '!',
'~', '=', '<', '>', '?', '@', '#', '\'', '\"', '\\'
};
await VerifyCommitCharactersAsync(initialMarkup, textTypedSoFar, commitCharacters);
}
protected async Task VerifyCommitCharactersAsync(string initialMarkup, string textTypedSoFar, char[] validChars, char[] invalidChars = null)
{
Assert.NotNull(validChars);
invalidChars = invalidChars ?? new[] { 'x' };
using (var workspace = await CreateWorkspaceAsync(initialMarkup))
{
var hostDocument = workspace.DocumentWithCursor;
var documentId = workspace.GetDocumentId(hostDocument);
var document = workspace.CurrentSolution.GetDocument(documentId);
var position = hostDocument.CursorPosition.Value;
var service = GetCompletionService(workspace);
var completionList = await GetCompletionListAsync(service, document, position, CompletionTrigger.Default);
var item = completionList.Items.First(i => i.DisplayText.StartsWith(textTypedSoFar));
foreach (var ch in validChars)
{
Assert.True(Controller.IsCommitCharacter(
service.GetRules(), item, ch, textTypedSoFar + ch), $"Expected '{ch}' to be a commit character");
}
foreach (var ch in invalidChars)
{
Assert.False(Controller.IsCommitCharacter(
service.GetRules(), item, ch, textTypedSoFar + ch), $"Expected '{ch}' NOT to be a commit character");
}
}
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
internal class VS2005AutoHideStrip : AutoHideStripBase
{
private class TabVS2005 : Tab
{
internal TabVS2005(IDockContent content)
: base(content)
{
}
private int m_tabX = 0;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth = 0;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
}
private const int _ImageHeight = 16;
private const int _ImageWidth = 16;
private const int _ImageGapTop = 2;
private const int _ImageGapLeft = 4;
private const int _ImageGapRight = 2;
private const int _ImageGapBottom = 2;
private const int _TextGapLeft = 0;
private const int _TextGapRight = 0;
private const int _TabGapTop = 3;
private const int _TabGapLeft = 4;
private const int _TabGapBetween = 10;
#region Customizable Properties
public Font TextFont
{
get { return DockPanel.Skin.AutoHideStripSkin.TextFont; }
}
private static StringFormat _stringFormatTabHorizontal;
private StringFormat StringFormatTabHorizontal
{
get
{
if (_stringFormatTabHorizontal == null)
{
_stringFormatTabHorizontal = new StringFormat();
_stringFormatTabHorizontal.Alignment = StringAlignment.Near;
_stringFormatTabHorizontal.LineAlignment = StringAlignment.Center;
_stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap;
_stringFormatTabHorizontal.Trimming = StringTrimming.None;
}
if (RightToLeft == RightToLeft.Yes)
_stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
else
_stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft;
return _stringFormatTabHorizontal;
}
}
private static StringFormat _stringFormatTabVertical;
private StringFormat StringFormatTabVertical
{
get
{
if (_stringFormatTabVertical == null)
{
_stringFormatTabVertical = new StringFormat();
_stringFormatTabVertical.Alignment = StringAlignment.Near;
_stringFormatTabVertical.LineAlignment = StringAlignment.Center;
_stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical;
_stringFormatTabVertical.Trimming = StringTrimming.None;
}
if (RightToLeft == RightToLeft.Yes)
_stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
else
_stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft;
return _stringFormatTabVertical;
}
}
private static int ImageHeight
{
get { return _ImageHeight; }
}
private static int ImageWidth
{
get { return _ImageWidth; }
}
private static int ImageGapTop
{
get { return _ImageGapTop; }
}
private static int ImageGapLeft
{
get { return _ImageGapLeft; }
}
private static int ImageGapRight
{
get { return _ImageGapRight; }
}
private static int ImageGapBottom
{
get { return _ImageGapBottom; }
}
private static int TextGapLeft
{
get { return _TextGapLeft; }
}
private static int TextGapRight
{
get { return _TextGapRight; }
}
private static int TabGapTop
{
get { return _TabGapTop; }
}
private static int TabGapLeft
{
get { return _TabGapLeft; }
}
private static int TabGapBetween
{
get { return _TabGapBetween; }
}
private static Pen PenTabBorder
{
get { return SystemPens.GrayText; }
}
#endregion
private static Matrix _matrixIdentity = new Matrix();
private static Matrix MatrixIdentity
{
get { return _matrixIdentity; }
}
private static DockState[] _dockStates;
private static DockState[] DockStates
{
get
{
if (_dockStates == null)
{
_dockStates = new DockState[4];
_dockStates[0] = DockState.DockLeftAutoHide;
_dockStates[1] = DockState.DockRightAutoHide;
_dockStates[2] = DockState.DockTopAutoHide;
_dockStates[3] = DockState.DockBottomAutoHide;
}
return _dockStates;
}
}
private static GraphicsPath _graphicsPath;
internal static GraphicsPath GraphicsPath
{
get
{
if (_graphicsPath == null)
_graphicsPath = new GraphicsPath();
return _graphicsPath;
}
}
public VS2005AutoHideStrip(DockPanel panel)
: base(panel)
{
SetStyle(ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
BackColor = SystemColors.ControlLight;
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
Color startColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.StartColor;
Color endColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.EndColor;
LinearGradientMode gradientMode = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode))
{
g.FillRectangle(brush, ClientRectangle);
}
DrawTabStrip(g);
}
protected override void OnLayout(LayoutEventArgs levent)
{
CalculateTabs();
base.OnLayout(levent);
}
private void DrawTabStrip(Graphics g)
{
DrawTabStrip(g, DockState.DockTopAutoHide);
DrawTabStrip(g, DockState.DockBottomAutoHide);
DrawTabStrip(g, DockState.DockLeftAutoHide);
DrawTabStrip(g, DockState.DockRightAutoHide);
}
private void DrawTabStrip(Graphics g, DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return;
Matrix matrixIdentity = g.Transform;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
Matrix matrixRotated = new Matrix();
matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
g.Transform = matrixRotated;
}
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2005 tab in pane.AutoHideTabs)
DrawTab(g, tab);
}
g.Transform = matrixIdentity;
}
private void CalculateTabs()
{
CalculateTabs(DockState.DockTopAutoHide);
CalculateTabs(DockState.DockBottomAutoHide);
CalculateTabs(DockState.DockLeftAutoHide);
CalculateTabs(DockState.DockRightAutoHide);
}
private void CalculateTabs(DockState dockState)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight / ImageHeight);
int x = TabGapLeft + rectTabStrip.X;
foreach (Pane pane in GetPanes(dockState))
{
foreach (TabVS2005 tab in pane.AutoHideTabs)
{
int width = imageWidth + ImageGapLeft + ImageGapRight +
TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width +
TextGapLeft + TextGapRight;
tab.TabX = x;
tab.TabWidth = width;
x += width;
}
x += TabGapBetween;
}
}
private Rectangle RtlTransform(Rectangle rect, DockState dockState)
{
Rectangle rectTransformed;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
rectTransformed = rect;
else
rectTransformed = DrawHelper.RtlTransform(this, rect);
return rectTransformed;
}
private GraphicsPath GetTabOutline(TabVS2005 tab, bool transformed, bool rtlTransform)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTab = GetTabRectangle(tab, transformed);
if (rtlTransform)
rectTab = RtlTransform(rectTab, dockState);
bool upTab = (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockBottomAutoHide);
DrawHelper.GetRoundedCornerTab(GraphicsPath, rectTab, upTab);
return GraphicsPath;
}
private void DrawTab(Graphics g, TabVS2005 tab)
{
Rectangle rectTabOrigin = GetTabRectangle(tab);
if (rectTabOrigin.IsEmpty)
return;
DockState dockState = tab.Content.DockHandler.DockState;
IDockContent content = tab.Content;
GraphicsPath path = GetTabOutline(tab, false, true);
Color startColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.StartColor;
Color endColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.EndColor;
LinearGradientMode gradientMode = DockPanel.Skin.AutoHideStripSkin.TabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectTabOrigin, startColor, endColor, gradientMode), path);
g.DrawPath(PenTabBorder, path);
// Set no rotate for drawing icon and text
using (Matrix matrixRotate = g.Transform)
{
g.Transform = MatrixIdentity;
// Draw the icon
Rectangle rectImage = rectTabOrigin;
rectImage.X += ImageGapLeft;
rectImage.Y += ImageGapTop;
int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom;
int imageWidth = ImageWidth;
if (imageHeight > ImageHeight)
imageWidth = ImageWidth * (imageHeight / ImageHeight);
rectImage.Height = imageHeight;
rectImage.Width = imageWidth;
rectImage = GetTransformedRectangle(dockState, rectImage);
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
{
// The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right.
Rectangle rectTransform = RtlTransform(rectImage, dockState);
Point[] rotationPoints =
{
new Point(rectTransform.X + rectTransform.Width, rectTransform.Y),
new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height),
new Point(rectTransform.X, rectTransform.Y)
};
using (Icon rotatedIcon = new Icon(((Form)content).Icon, 16, 16))
{
g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints);
}
}
else
{
// Draw the icon normally without any rotation.
g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState));
}
// Draw the text
Rectangle rectText = rectTabOrigin;
rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft;
rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState);
Color textColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.TextColor;
if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide)
g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabVertical);
else
g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabHorizontal);
// Set rotate back
g.Transform = matrixRotate;
}
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState)
{
return GetLogicalTabStripRectangle(dockState, false);
}
private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed)
{
if (!DockHelper.IsDockStateAutoHide(dockState))
return Rectangle.Empty;
int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count;
int rightPanes = GetPanes(DockState.DockRightAutoHide).Count;
int topPanes = GetPanes(DockState.DockTopAutoHide).Count;
int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count;
int x, y, width, height;
height = MeasureHeight();
if (dockState == DockState.DockLeftAutoHide && leftPanes > 0)
{
x = 0;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockRightAutoHide && rightPanes > 0)
{
x = Width - height;
if (leftPanes != 0 && x < height)
x = height;
y = (topPanes == 0) ? 0 : height;
width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockTopAutoHide && topPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = 0;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0)
{
x = leftPanes == 0 ? 0 : height;
y = Height - height;
if (topPanes != 0 && y < height)
y = height;
width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height);
}
else
return Rectangle.Empty;
if (width == 0 || height == 0)
{
return Rectangle.Empty;
}
var rect = new Rectangle(x, y, width, height);
return transformed ? GetTransformedRectangle(dockState, rect) : rect;
}
private Rectangle GetTabRectangle(TabVS2005 tab)
{
return GetTabRectangle(tab, false);
}
private Rectangle GetTabRectangle(TabVS2005 tab, bool transformed)
{
DockState dockState = tab.Content.DockHandler.DockState;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
if (rectTabStrip.IsEmpty)
return Rectangle.Empty;
int x = tab.TabX;
int y = rectTabStrip.Y +
(dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ?
0 : TabGapTop);
int width = tab.TabWidth;
int height = rectTabStrip.Height - TabGapTop;
if (!transformed)
return new Rectangle(x, y, width, height);
else
return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height));
}
private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect)
{
if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide)
return rect;
PointF[] pts = new PointF[1];
// the center of the rectangle
pts[0].X = (float)rect.X + (float)rect.Width / 2;
pts[0].Y = (float)rect.Y + (float)rect.Height / 2;
Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState);
using (var matrix = new Matrix())
{
matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2,
(float)rectTabStrip.Y + (float)rectTabStrip.Height / 2));
matrix.TransformPoints(pts);
}
return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F),
(int)(pts[0].Y - (float)rect.Width / 2 + .5F),
rect.Height, rect.Width);
}
protected override IDockContent HitTest(Point ptMouse)
{
foreach (DockState state in DockStates)
{
Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true);
if (!rectTabStrip.Contains(ptMouse))
continue;
foreach (Pane pane in GetPanes(state))
{
foreach (TabVS2005 tab in pane.AutoHideTabs)
{
GraphicsPath path = GetTabOutline(tab, true, true);
if (path.IsVisible(ptMouse))
return tab.Content;
}
}
}
return null;
}
protected internal override int MeasureHeight()
{
return Math.Max(ImageGapBottom +
ImageGapTop + ImageHeight,
TextFont.Height) + TabGapTop;
}
protected override void OnRefreshChanges()
{
CalculateTabs();
Invalidate();
}
protected override AutoHideStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2005(content);
}
}
}
| |
// 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.Xml;
using System.Xml.Schema;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace System.Xml.Xsl
{
/// <summary>
/// XmlQualifiedName extends XmlQualifiedName to support wildcards and adds nametest functionality
/// Following are the examples:
/// {A}:B XmlQualifiedNameTest.New("B", "A") Match QName with namespace A and local name B
/// * XmlQualifiedNameTest.New(null, null) Match any QName
/// {A}:* XmlQualifiedNameTest.New(null, "A") Match QName with namespace A and any local name
/// XmlQualifiedNameTest.New("A", false)
/// *:B XmlQualifiedNameTest.New("B", null) Match QName with any namespace and local name B
/// ~{A}:* XmlQualifiedNameTest.New("B", "A") Match QName with namespace not A and any local name
/// {~A}:B only as a result of the intersection Match QName with namespace not A and local name B
/// </summary>
internal class XmlQualifiedNameTest : XmlQualifiedName
{
private readonly bool _exclude;
private const string wildcard = "*";
private static readonly XmlQualifiedNameTest s_wc = XmlQualifiedNameTest.New(wildcard, wildcard);
/// <summary>
/// Full wildcard
/// </summary>
public static XmlQualifiedNameTest Wildcard
{
get { return s_wc; }
}
/// <summary>
/// Constructor
/// </summary>
private XmlQualifiedNameTest(string name, string ns, bool exclude) : base(name, ns)
{
_exclude = exclude;
}
/// <summary>
/// Construct new from name and namespace. Returns singleton Wildcard in case full wildcard
/// </summary>
public static XmlQualifiedNameTest New(string name, string ns)
{
if (ns == null && name == null)
{
return Wildcard;
}
else
{
return new XmlQualifiedNameTest(name == null ? wildcard : name, ns == null ? wildcard : ns, false);
}
}
/// <summary>
/// True if matches any name and any namespace
/// </summary>
public bool IsWildcard
{
get { return (object)this == (object)Wildcard; }
}
/// <summary>
/// True if matches any name
/// </summary>
public bool IsNameWildcard
{
get { return (object)this.Name == (object)wildcard; }
}
/// <summary>
/// True if matches any namespace
/// </summary>
public bool IsNamespaceWildcard
{
get { return (object)this.Namespace == (object)wildcard; }
}
private bool IsNameSubsetOf(XmlQualifiedNameTest other)
{
return other.IsNameWildcard || this.Name == other.Name;
}
// BUGBUG - exclude local
private bool IsNamespaceSubsetOf(XmlQualifiedNameTest other)
{
return other.IsNamespaceWildcard
|| (_exclude == other._exclude && this.Namespace == other.Namespace)
|| (other._exclude && !_exclude && this.Namespace != other.Namespace);
}
/// <summary>
/// True if this matches every QName other does
/// </summary>
public bool IsSubsetOf(XmlQualifiedNameTest other)
{
return IsNameSubsetOf(other) && IsNamespaceSubsetOf(other);
}
/// <summary>
/// Return true if the result of intersection with other is not empty
/// </summary>
public bool HasIntersection(XmlQualifiedNameTest other)
{
return (IsNamespaceSubsetOf(other) || other.IsNamespaceSubsetOf(this)) && (IsNameSubsetOf(other) || other.IsNameSubsetOf(this));
}
/// <summary>
/// String representation
/// </summary>
public override string ToString()
{
if ((object)this == (object)Wildcard)
{
return "*";
}
else
{
if (this.Namespace.Length == 0)
{
return this.Name;
}
else if ((object)this.Namespace == (object)wildcard)
{
return "*:" + this.Name;
}
else if (_exclude)
{
return "{~" + this.Namespace + "}:" + this.Name;
}
else
{
return "{" + this.Namespace + "}:" + this.Name;
}
}
}
#if SchemaTypeImport
/// <summary>
/// Construct new from XmlQualifiedName. Returns singleton Wildcard in case full wildcard
/// </summary>
public static XmlQualifiedNameTest New(XmlQualifiedName name) {
if (name.IsEmpty) {
return Wildcard;
}
else {
return new XmlQualifiedNameTest(name.Name, name.Namespace, false);
}
}
/// <summary>
/// Construct new "exclusion" name test
/// </summary>
public static XmlQualifiedNameTest New(string ns, bool exclude) {
Debug.Assert(ns != null);
return new XmlQualifiedNameTest(wildcard, ns, exclude);
}
/// <summary>
/// Return the result of intersection with other
/// </summary>
public XmlQualifiedNameTest Intersect(XmlQualifiedNameTest other) {
// Namespace
// this\other ~y * y
// ~x x=y ? this|other : null this x!=y ? other : null
// * other this|other other
// x x!=y ? this : null this x=y ? this|other : null
XmlQualifiedNameTest namespaceFrom = IsNamespaceSubsetOf(other) ? this : other.IsNamespaceSubsetOf(this) ? other : null;
XmlQualifiedNameTest nameFrom = IsNameSubsetOf(other) ? this : other.IsNameSubsetOf(this) ? other : null;
if ((object)namespaceFrom == (object)nameFrom) {
return namespaceFrom;
}
else if (namespaceFrom == null || nameFrom == null) {
return null;
}
else {
return new XmlQualifiedNameTest(nameFrom.Name, namespaceFrom.Namespace, namespaceFrom.ExcludeNamespace);
}
}
/// <summary>
/// True if neither name nor namespace is a wildcard
/// </summary>
public bool IsSingleName {
get { return (object)this.Name != (object)wildcard && (object)this.Namespace != (object)wildcard && this.exclude == false; }
}
/// <summary>
/// True if matches any namespace other then this.Namespace
/// </summary>
public bool ExcludeNamespace {
get { return this.exclude; }
}
#endif
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace OpenMetaverse.Imaging
{
#if !NO_UNSAFE
/// <summary>
/// A Wrapper around openjpeg to encode and decode images to and from byte arrays
/// </summary>
public class OpenJPEG
{
/// <summary>TGA Header size</summary>
public const int TGA_HEADER_SIZE = 32;
/// <summary>
/// Defines the beginning and ending file positions of a layer in an
/// LRCP-progression JPEG2000 file
/// </summary>
public struct J2KLayerInfo
{
public int Start;
public int End;
public int Size { get { return End - Start; } }
public override string ToString()
{
return String.Format("Start: {0} End: {1} Size: {2}", Start, End, Size);
}
}
/// <summary>
/// This structure is used to marshal both encoded and decoded images.
/// MUST MATCH THE STRUCT IN dotnet.h!
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct MarshalledImage
{
public IntPtr encoded; // encoded image data
public int length; // encoded image length
public int dummy; // padding for 64-bit alignment
public IntPtr decoded; // decoded image, contiguous components
public int width; // width of decoded image
public int height; // height of decoded image
public int layers; // layer count
public int resolutions; // resolution count
public int components; // component count
public int packet_count; // packet count
public IntPtr packets; // pointer to the packets array
}
/// <summary>
/// Information about a single packet in a JPEG2000 stream
/// </summary>
private struct MarshalledPacket
{
/// <summary>Packet start position</summary>
public int start_pos;
/// <summary>Packet header end position</summary>
public int end_ph_pos;
/// <summary>Packet end position</summary>
public int end_pos;
public override string ToString()
{
return String.Format("start_pos: {0} end_ph_pos: {1} end_pos: {2}",
start_pos, end_ph_pos, end_pos);
}
}
// allocate encoded buffer based on length field
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetAllocEncoded(ref MarshalledImage image);
// allocate decoded buffer based on width and height fields
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetAllocDecoded(ref MarshalledImage image);
// free buffers
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetFree(ref MarshalledImage image);
// encode raw to jpeg2000
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetEncode(ref MarshalledImage image, bool lossless);
// decode jpeg2000 to raw
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetDecode(ref MarshalledImage image);
// decode jpeg2000 to raw, get jpeg2000 file info
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("openjpeg-dotnet.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern bool DotNetDecodeWithInfo(ref MarshalledImage image);
/// <summary>
/// Encode a <seealso cref="ManagedImage"/> object into a byte array
/// </summary>
/// <param name="image">The <seealso cref="ManagedImage"/> object to encode</param>
/// <param name="lossless">true to enable lossless conversion, only useful for small images ie: sculptmaps</param>
/// <returns>A byte array containing the encoded Image object</returns>
public static byte[] Encode(ManagedImage image, bool lossless)
{
if (
(image.Channels & ManagedImage.ImageChannels.Color) == 0 ||
((image.Channels & ManagedImage.ImageChannels.Bump) != 0 && (image.Channels & ManagedImage.ImageChannels.Alpha) == 0))
throw new ArgumentException("JPEG2000 encoding is not supported for this channel combination");
MarshalledImage marshalled = new MarshalledImage();
// allocate and copy to input buffer
marshalled.width = image.Width;
marshalled.height = image.Height;
marshalled.components = 3;
if ((image.Channels & ManagedImage.ImageChannels.Alpha) != 0) marshalled.components++;
if ((image.Channels & ManagedImage.ImageChannels.Bump) != 0) marshalled.components++;
if (!DotNetAllocDecoded(ref marshalled))
throw new Exception("LibslAllocDecoded failed");
int n = image.Width * image.Height;
if ((image.Channels & ManagedImage.ImageChannels.Color) != 0)
{
Marshal.Copy(image.Red, 0, marshalled.decoded, n);
Marshal.Copy(image.Green, 0, (IntPtr)(marshalled.decoded.ToInt64() + n), n);
Marshal.Copy(image.Blue, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 2), n);
}
if ((image.Channels & ManagedImage.ImageChannels.Alpha) != 0) Marshal.Copy(image.Alpha, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 3), n);
if ((image.Channels & ManagedImage.ImageChannels.Bump) != 0) Marshal.Copy(image.Bump, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 4), n);
// codec will allocate output buffer
if (!DotNetEncode(ref marshalled, lossless))
throw new Exception("LibslEncode failed");
// copy output buffer
byte[] encoded = new byte[marshalled.length];
Marshal.Copy(marshalled.encoded, encoded, 0, marshalled.length);
// free buffers
DotNetFree(ref marshalled);
return encoded;
}
/// <summary>
/// Encode a <seealso cref="ManagedImage"/> object into a byte array
/// </summary>
/// <param name="image">The <seealso cref="ManagedImage"/> object to encode</param>
/// <returns>a byte array of the encoded image</returns>
public static byte[] Encode(ManagedImage image)
{
return Encode(image, false);
}
/// <summary>
/// Decode JPEG2000 data to an <seealso cref="System.Drawing.Image"/> and
/// <seealso cref="ManagedImage"/>
/// </summary>
/// <param name="encoded">JPEG2000 encoded data</param>
/// <param name="managedImage">ManagedImage object to decode to</param>
/// <param name="image">Image object to decode to</param>
/// <returns>True if the decode succeeds, otherwise false</returns>
public static bool DecodeToImage(byte[] encoded, out ManagedImage managedImage, out Image image)
{
managedImage = null;
image = null;
if (DecodeToImage(encoded, out managedImage))
{
try
{
image = LoadTGAClass.LoadTGA(new MemoryStream(managedImage.ExportTGA()));
return true;
}
catch (Exception ex)
{
Logger.Log("Failed to export and load TGA data from decoded image", Helpers.LogLevel.Error, ex);
return false;
}
}
else
{
return false;
}
}
/// <summary>
///
/// </summary>
/// <param name="encoded"></param>
/// <param name="managedImage"></param>
/// <returns></returns>
public static bool DecodeToImage(byte[] encoded, out ManagedImage managedImage)
{
MarshalledImage marshalled = new MarshalledImage();
// Allocate and copy to input buffer
marshalled.length = encoded.Length;
DotNetAllocEncoded(ref marshalled);
Marshal.Copy(encoded, 0, marshalled.encoded, encoded.Length);
// Codec will allocate output buffer
DotNetDecode(ref marshalled);
int n = marshalled.width * marshalled.height;
switch (marshalled.components)
{
case 1: // Grayscale
managedImage = new ManagedImage(marshalled.width, marshalled.height,
ManagedImage.ImageChannels.Color);
Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n);
Buffer.BlockCopy(managedImage.Red, 0, managedImage.Green, 0, n);
Buffer.BlockCopy(managedImage.Red, 0, managedImage.Blue, 0, n);
break;
case 2: // Grayscale + alpha
managedImage = new ManagedImage(marshalled.width, marshalled.height,
ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha);
Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n);
Buffer.BlockCopy(managedImage.Red, 0, managedImage.Green, 0, n);
Buffer.BlockCopy(managedImage.Red, 0, managedImage.Blue, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Alpha, 0, n);
break;
case 3: // RGB
managedImage = new ManagedImage(marshalled.width, marshalled.height,
ManagedImage.ImageChannels.Color);
Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n);
break;
case 4: // RGBA
managedImage = new ManagedImage(marshalled.width, marshalled.height,
ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha);
Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 3)), managedImage.Alpha, 0, n);
break;
case 5: // RGBBA
managedImage = new ManagedImage(marshalled.width, marshalled.height,
ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha | ManagedImage.ImageChannels.Bump);
Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n);
// Bump comes before alpha in 5 channel encode
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 3)), managedImage.Bump, 0, n);
Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 4)), managedImage.Alpha, 0, n);
break;
default:
Logger.Log("Decoded image with unhandled number of components: " + marshalled.components,
Helpers.LogLevel.Error);
DotNetFree(ref marshalled);
managedImage = null;
return false;
}
DotNetFree(ref marshalled);
return true;
}
/// <summary>
///
/// </summary>
/// <param name="encoded"></param>
/// <param name="layerInfo"></param>
/// <param name="components"></param>
/// <returns></returns>
public static bool DecodeLayerBoundaries(byte[] encoded, out J2KLayerInfo[] layerInfo, out int components)
{
bool success = false;
layerInfo = null;
components = 0;
MarshalledImage marshalled = new MarshalledImage();
// Allocate and copy to input buffer
marshalled.length = encoded.Length;
DotNetAllocEncoded(ref marshalled);
Marshal.Copy(encoded, 0, marshalled.encoded, encoded.Length);
// Run the decode
if (DotNetDecodeWithInfo(ref marshalled))
{
components = marshalled.components;
// Sanity check
if (marshalled.layers * marshalled.resolutions * marshalled.components == marshalled.packet_count)
{
// Manually marshal the array of opj_packet_info structs
MarshalledPacket[] packets = new MarshalledPacket[marshalled.packet_count];
int offset = 0;
for (int i = 0; i < marshalled.packet_count; i++)
{
MarshalledPacket packet;
packet.start_pos = Marshal.ReadInt32(marshalled.packets, offset);
offset += 4;
packet.end_ph_pos = Marshal.ReadInt32(marshalled.packets, offset);
offset += 4;
packet.end_pos = Marshal.ReadInt32(marshalled.packets, offset);
offset += 4;
// Skip the distortion field. WARNING: It looks like there is alignment
// padding in here as well, this needs to be tested on different platforms
offset += 12;
packets[i] = packet;
}
layerInfo = new J2KLayerInfo[marshalled.layers];
for (int i = 0; i < marshalled.layers; i++)
{
int packetsPerLayer = marshalled.packet_count / marshalled.layers;
MarshalledPacket startPacket = packets[packetsPerLayer * i];
MarshalledPacket endPacket = packets[(packetsPerLayer * (i + 1)) - 1];
layerInfo[i].Start = startPacket.start_pos;
layerInfo[i].End = endPacket.end_pos;
}
success = true;
}
else
{
Logger.Log(String.Format(
"Packet count mismatch in JPEG2000 stream. layers={0} resolutions={1} components={2} packets={3}",
marshalled.layers, marshalled.resolutions, marshalled.components, marshalled.packet_count),
Helpers.LogLevel.Warning);
}
}
DotNetFree(ref marshalled);
return success;
}
/// <summary>
/// Encode a <seealso cref="System.Drawing.Bitmap"/> object into a byte array
/// </summary>
/// <param name="bitmap">The source <seealso cref="System.Drawing.Bitmap"/> object to encode</param>
/// <param name="lossless">true to enable lossless decoding</param>
/// <returns>A byte array containing the source Bitmap object</returns>
public unsafe static byte[] EncodeFromImage(Bitmap bitmap, bool lossless)
{
BitmapData bd;
ManagedImage decoded;
int bitmapWidth = bitmap.Width;
int bitmapHeight = bitmap.Height;
int pixelCount = bitmapWidth * bitmapHeight;
int i;
if ((bitmap.PixelFormat & PixelFormat.Alpha) != 0 || (bitmap.PixelFormat & PixelFormat.PAlpha) != 0)
{
// Four layers, RGBA
decoded = new ManagedImage(bitmapWidth, bitmapHeight,
ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha);
bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte* pixel = (byte*)bd.Scan0;
for (i = 0; i < pixelCount; i++)
{
// GDI+ gives us BGRA and we need to turn that in to RGBA
decoded.Blue[i] = *(pixel++);
decoded.Green[i] = *(pixel++);
decoded.Red[i] = *(pixel++);
decoded.Alpha[i] = *(pixel++);
}
}
else if (bitmap.PixelFormat == PixelFormat.Format16bppGrayScale)
{
// One layer
decoded = new ManagedImage(bitmapWidth, bitmapHeight,
ManagedImage.ImageChannels.Color);
bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight),
ImageLockMode.ReadOnly, PixelFormat.Format16bppGrayScale);
byte* pixel = (byte*)bd.Scan0;
for (i = 0; i < pixelCount; i++)
{
// Normalize 16-bit data down to 8-bit
ushort origVal = (byte)(*(pixel) + (*(pixel + 1) << 8));
byte val = (byte)(((double)origVal / (double)UInt32.MaxValue) * (double)Byte.MaxValue);
decoded.Red[i] = val;
decoded.Green[i] = val;
decoded.Blue[i] = val;
pixel += 2;
}
}
else
{
// Three layers, RGB
decoded = new ManagedImage(bitmapWidth, bitmapHeight,
ManagedImage.ImageChannels.Color);
bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight),
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
byte* pixel = (byte*)bd.Scan0;
for (i = 0; i < pixelCount; i++)
{
decoded.Blue[i] = *(pixel++);
decoded.Green[i] = *(pixel++);
decoded.Red[i] = *(pixel++);
}
}
bitmap.UnlockBits(bd);
byte[] encoded = Encode(decoded, lossless);
return encoded;
}
}
#endif
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using NLog.Internal;
/// <summary>
/// Represents simple XML element with case-insensitive attribute semantics.
/// </summary>
internal class NLogXmlElement : ILoggingConfigurationElement
{
/// <summary>
/// Initializes a new instance of the <see cref="NLogXmlElement"/> class.
/// </summary>
/// <param name="reader">The reader to initialize element from.</param>
public NLogXmlElement(XmlReader reader)
: this(reader, false)
{
}
public NLogXmlElement(XmlReader reader, bool nestedElement)
{
Parse(reader, nestedElement, out var attributes, out var children);
AttributeValues = attributes ?? ArrayHelper.Empty<KeyValuePair<string, string>>();
Children = children ?? ArrayHelper.Empty<NLogXmlElement>();
}
/// <summary>
/// Gets the element name.
/// </summary>
public string LocalName { get; private set; }
/// <summary>
/// Gets the dictionary of attribute values.
/// </summary>
public IList<KeyValuePair<string,string>> AttributeValues { get; }
/// <summary>
/// Gets the collection of child elements.
/// </summary>
public IList<NLogXmlElement> Children { get; }
/// <summary>
/// Gets the value of the element.
/// </summary>
public string Value { get; private set; }
public string Name => LocalName;
public IEnumerable<KeyValuePair<string, string>> Values
{
get
{
for (int i = 0; i < Children.Count; ++i)
{
var child = Children[i];
if (SingleValueElement(child))
{
// Values assigned using nested node-elements. Maybe in combination with attributes
return AttributeValues.Concat(Children.Where(item => SingleValueElement(item)).Select(item => new KeyValuePair<string, string>(item.Name, item.Value)));
}
}
return AttributeValues;
}
}
private static bool SingleValueElement(NLogXmlElement child)
{
// Node-element that works like an attribute
return child.Children.Count == 0 && child.AttributeValues.Count == 0 && child.Value != null;
}
IEnumerable<ILoggingConfigurationElement> ILoggingConfigurationElement.Children
{
get
{
for (int i = 0; i < Children.Count; ++i)
{
var child = Children[i];
if (!SingleValueElement(child))
return Children.Where(item => !SingleValueElement(item)).Cast<ILoggingConfigurationElement>();
}
return ArrayHelper.Empty<ILoggingConfigurationElement>();
}
}
/// <summary>
/// Returns children elements with the specified element name.
/// </summary>
/// <param name="elementName">Name of the element.</param>
/// <returns>Children elements with the specified element name.</returns>
public List<NLogXmlElement> FilterChildren(string elementName)
{
var result = new List<NLogXmlElement>();
foreach (var ch in Children)
{
if (ch.LocalName.Equals(elementName, StringComparison.OrdinalIgnoreCase))
{
result.Add(ch);
}
}
return result;
}
/// <summary>
/// Asserts that the name of the element is among specified element names.
/// </summary>
/// <param name="allowedNames">The allowed names.</param>
public void AssertName(params string[] allowedNames)
{
foreach (var en in allowedNames)
{
if (LocalName.Equals(en, StringComparison.OrdinalIgnoreCase))
{
return;
}
}
throw new InvalidOperationException($"Assertion failed. Expected element name '{string.Join("|", allowedNames)}', actual: '{LocalName}'.");
}
private void Parse(XmlReader reader, bool nestedElement, out IList<KeyValuePair<string,string>> attributes, out IList<NLogXmlElement> children)
{
ParseAttributes(reader, nestedElement, out attributes);
LocalName = reader.LocalName;
children = null;
if (!reader.IsEmptyElement)
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement)
{
break;
}
if (reader.NodeType == XmlNodeType.CDATA || reader.NodeType == XmlNodeType.Text)
{
Value += reader.Value;
continue;
}
if (reader.NodeType == XmlNodeType.Element)
{
children = children ?? new List<NLogXmlElement>();
var nestedChild = nestedElement || !string.Equals(reader.LocalName, "nlog", StringComparison.OrdinalIgnoreCase);
children.Add(new NLogXmlElement(reader, nestedChild));
}
}
}
}
private void ParseAttributes(XmlReader reader, bool nestedElement, out IList<KeyValuePair<string, string>> attributes)
{
attributes = null;
if (reader.MoveToFirstAttribute())
{
do
{
if (!nestedElement && IsSpecialXmlAttribute(reader))
{
continue;
}
attributes = attributes ?? new List<KeyValuePair<string, string>>();
attributes.Add(new KeyValuePair<string, string>(reader.LocalName, reader.Value));
}
while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
}
/// <summary>
/// Special attribute we could ignore
/// </summary>
private static bool IsSpecialXmlAttribute(XmlReader reader)
{
if (reader.LocalName?.Equals("xmlns", StringComparison.OrdinalIgnoreCase) == true)
return true;
if (reader.LocalName?.Equals("schemaLocation", StringComparison.OrdinalIgnoreCase) == true && !StringHelpers.IsNullOrWhiteSpace(reader.Prefix))
return true;
if (reader.Prefix?.Equals("xsi", StringComparison.OrdinalIgnoreCase) == true)
return true;
if (reader.Prefix?.Equals("xmlns", StringComparison.OrdinalIgnoreCase) == true)
return true;
return false;
}
public override string ToString()
{
return Name;
}
}
}
| |
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace EarLab.ColorBars
{
/// <summary>
/// Summary description for ColorBarStandard.
/// </summary>
public class ColorBarStandard
{
private Color [] mColors;
private Color mOutOfRangeColor = Color.SlateGray;
private int mColorCount;
private double mMin, mMax, mCurMin, mCurMax, mStepSize;
private static int [,] DefaultColors = {{0, 0, 143},
{0, 0, 147},
{0, 0, 151},
{0, 0, 155},
{0, 0, 159},
{0, 0, 163},
{0, 0, 167},
{0, 0, 171},
{0, 0, 175},
{0, 0, 179},
{0, 0, 183},
{0, 0, 187},
{0, 0, 191},
{0, 0, 195},
{0, 0, 199},
{0, 0, 203},
{0, 0, 207},
{0, 0, 211},
{0, 0, 215},
{0, 0, 219},
{0, 0, 223},
{0, 0, 227},
{0, 0, 231},
{0, 0, 235},
{0, 0, 239},
{0, 0, 243},
{0, 0, 247},
{0, 0, 251},
{0, 0, 255},
{0, 3, 255},
{0, 7, 255},
{0, 11, 255},
{0, 15, 255},
{0, 19, 255},
{0, 23, 255},
{0, 27, 255},
{0, 31, 255},
{0, 35, 255},
{0, 39, 255},
{0, 43, 255},
{0, 47, 255},
{0, 51, 255},
{0, 55, 255},
{0, 59, 255},
{0, 63, 255},
{0, 67, 255},
{0, 71, 255},
{0, 75, 255},
{0, 79, 255},
{0, 83, 255},
{0, 87, 255},
{0, 91, 255},
{0, 95, 255},
{0, 99, 255},
{0, 103, 255},
{0, 107, 255},
{0, 111, 255},
{0, 115, 255},
{0, 119, 255},
{0, 123, 255},
{0, 127, 255},
{0, 131, 255},
{0, 135, 255},
{0, 139, 255},
{0, 143, 255},
{0, 147, 255},
{0, 151, 255},
{0, 155, 255},
{0, 159, 255},
{0, 163, 255},
{0, 167, 255},
{0, 171, 255},
{0, 175, 255},
{0, 179, 255},
{0, 183, 255},
{0, 187, 255},
{0, 191, 255},
{0, 195, 255},
{0, 199, 255},
{0, 203, 255},
{0, 207, 255},
{0, 211, 255},
{0, 215, 255},
{0, 219, 255},
{0, 223, 255},
{0, 227, 255},
{0, 231, 255},
{0, 235, 255},
{0, 239, 255},
{0, 243, 255},
{0, 247, 255},
{0, 251, 255},
{0, 255, 255},
{3, 255, 251},
{7, 255, 247},
{11, 255, 243},
{15, 255, 239},
{19, 255, 235},
{23, 255, 231},
{27, 255, 227},
{31, 255, 223},
{35, 255, 219},
{39, 255, 215},
{43, 255, 211},
{47, 255, 207},
{51, 255, 203},
{55, 255, 199},
{59, 255, 195},
{63, 255, 191},
{67, 255, 187},
{71, 255, 183},
{75, 255, 179},
{79, 255, 175},
{83, 255, 171},
{87, 255, 167},
{91, 255, 163},
{95, 255, 159},
{99, 255, 155},
{103, 255, 151},
{107, 255, 147},
{111, 255, 143},
{115, 255, 139},
{119, 255, 135},
{123, 255, 131},
{127, 255, 127},
{131, 255, 123},
{135, 255, 119},
{139, 255, 115},
{143, 255, 111},
{147, 255, 107},
{151, 255, 103},
{155, 255, 99},
{159, 255, 95},
{163, 255, 91},
{167, 255, 87},
{171, 255, 83},
{175, 255, 79},
{179, 255, 75},
{183, 255, 71},
{187, 255, 67},
{191, 255, 63},
{195, 255, 59},
{199, 255, 55},
{203, 255, 51},
{207, 255, 47},
{211, 255, 43},
{215, 255, 39},
{219, 255, 35},
{223, 255, 31},
{227, 255, 27},
{231, 255, 23},
{235, 255, 19},
{239, 255, 15},
{243, 255, 11},
{247, 255, 7},
{251, 255, 3},
{255, 255, 0},
{255, 251, 0},
{255, 247, 0},
{255, 243, 0},
{255, 239, 0},
{255, 235, 0},
{255, 231, 0},
{255, 227, 0},
{255, 223, 0},
{255, 219, 0},
{255, 215, 0},
{255, 211, 0},
{255, 207, 0},
{255, 203, 0},
{255, 199, 0},
{255, 195, 0},
{255, 191, 0},
{255, 187, 0},
{255, 183, 0},
{255, 179, 0},
{255, 175, 0},
{255, 171, 0},
{255, 167, 0},
{255, 163, 0},
{255, 159, 0},
{255, 155, 0},
{255, 151, 0},
{255, 147, 0},
{255, 143, 0},
{255, 139, 0},
{255, 135, 0},
{255, 131, 0},
{255, 127, 0},
{255, 123, 0},
{255, 119, 0},
{255, 115, 0},
{255, 111, 0},
{255, 107, 0},
{255, 103, 0},
{255, 99, 0},
{255, 95, 0},
{255, 91, 0},
{255, 87, 0},
{255, 83, 0},
{255, 79, 0},
{255, 75, 0},
{255, 71, 0},
{255, 67, 0},
{255, 63, 0},
{255, 59, 0},
{255, 55, 0},
{255, 51, 0},
{255, 47, 0},
{255, 43, 0},
{255, 39, 0},
{255, 35, 0},
{255, 31, 0},
{255, 27, 0},
{255, 23, 0},
{255, 19, 0},
{255, 15, 0},
{255, 11, 0},
{255, 7, 0},
{255, 3, 0},
{255, 0, 0},
{251, 0, 0},
{247, 0, 0},
{243, 0, 0},
{239, 0, 0},
{235, 0, 0},
{231, 0, 0},
{227, 0, 0},
{223, 0, 0},
{219, 0, 0},
{215, 0, 0},
{211, 0, 0},
{207, 0, 0},
{203, 0, 0},
{199, 0, 0},
{195, 0, 0},
{191, 0, 0},
{187, 0, 0},
{183, 0, 0},
{179, 0, 0},
{175, 0, 0},
{171, 0, 0},
{167, 0, 0},
{163, 0, 0},
{159, 0, 0},
{155, 0, 0},
{151, 0, 0},
{147, 0, 0},
{143, 0, 0},
{139, 0, 0},
{135, 0, 0},
{131, 0, 0},
{127, 0, 0}};
public Color [] Colors
{
get {return mColors;}
}
public delegate void ColorBarChangedHandler(object sender);
public event ColorBarChangedHandler ColorsChanged;
public event ColorBarChangedHandler MinMaxCurChanged;
private void OnMinMaxCurChanged()
{
if (MinMaxCurChanged != null)
MinMaxCurChanged(this);
}
private void OnColorsChanged()
{
if (ColorsChanged != null)
ColorsChanged(this);
}
public void RenderDataToBitmap(int RenderStartX, long RenderWidth, double[,] Data, ref Bitmap bmp)
{
Bitmap tempBitmap = (Bitmap)bmp.Clone();
int index;
BitmapData bmData = tempBitmap.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int stride = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
unsafe
{
byte* p = (byte*)Scan0.ToPointer();
long nOffset = stride - (RenderWidth*3);
p += RenderStartX*3;
for (int i=bmp.Height-1; i>=0; i--)
{
for(int j=0; j<RenderWidth; j++)
{
index = Math.Min(mColors.Length-1, Math.Max(0,(int)((Data[j+RenderStartX, i] - mCurMin) / mStepSize)));
p[0] = (byte)mColors[index].B;
p[1] = (byte)mColors[index].G;
p[2] = (byte)mColors[index].R;
p += 3;
}
p += nOffset;
}
}
tempBitmap.UnlockBits(bmData);
bmp = (Bitmap)tempBitmap.Clone();
}
public Color this[int index]
{
get
{
if ((index >= 0) && (index < mColorCount))
return mColors[(int)(index % mColorCount)];
else
throw new IndexOutOfRangeException("Index must be less than " + mColorCount.ToString());
}
}
public int ColorCount
{
get {return mColorCount;}
}
public Color GetColor(double Datum)
{
if ((Datum >= mCurMin) && (Datum <= mCurMax))
{
return this[(int)((double)(Datum - mCurMin) / mStepSize)];
}
else
{
if (Datum < mCurMin)
return this[0];
else
return this[mColorCount - 1];
}
}
public double Min
{
get {return mMin;}
set
{
if (mCurMin == mMin)
mCurMin = mMin = value;
else
{
mMin = value;
mCurMin = Math.Max(mCurMin, mMin);
}
if (mCurMin >= mCurMax)
{
mCurMin = mMin;
mCurMax = mMax;
}
mStepSize = (mCurMax - mCurMin) / (double)mColorCount;
this.OnMinMaxCurChanged();
}
}
public double Max
{
get {return mMax;}
set
{
if (mCurMax == mMax)
mCurMax = mMax = value;
else
{
mMax = value;
mCurMax = Math.Min(mCurMax, mMax);
}
if (mCurMax <= mMin)
{
mCurMin = mMin;
mCurMax = mMax;
}
mStepSize = (mCurMax - mCurMin) / (double)mColorCount;
this.OnMinMaxCurChanged();
}
}
public void SetMinMax(double minValue, double maxValue)
{
if (mCurMin == mMin)
mCurMin = mMin = minValue;
else
{
mMin = minValue;
mCurMin = Math.Max(mCurMin, mMin);
}
if (mCurMax == mMax)
mCurMax = mMax = maxValue;
else
{
mMax = maxValue;
mCurMax = Math.Min(mCurMax, mMax);
}
if (mCurMax <= mMin || mCurMin >= mCurMax)
{
mCurMin = mMin;
mCurMax = mMax;
}
mStepSize = (mCurMax - mCurMin) / (double)mColorCount;
this.OnMinMaxCurChanged();
}
public void SetCurMinCurMax(double curMin, double curMax)
{
mCurMin = curMin;
mCurMax = curMax;
// check for some things that *should* never happen, and which would cause incorrect behavior
if (curMin >= curMax)
throw new System.Exception("ColorBar Class, SetCurMinCurMax(): Cannot assign CurMin >= CurMax");
if (curMin < mMin || curMax > mMax)
throw new System.Exception("ColorBar Class, SetCurMinCurMax(): Cannot have CurMin or CurMax oustide Min and Max range");
mStepSize = (mCurMax - mCurMin) / (double)mColorCount;
this.OnMinMaxCurChanged();
}
public double CurMin
{
get {return mCurMin;}
set
{
mCurMin = value;
mStepSize = (mCurMax - mCurMin) / (double)mColorCount;
this.OnMinMaxCurChanged();
}
}
public double CurMax
{
get {return mCurMax;}
set
{
mCurMax = value;
mStepSize = (mCurMax - mCurMin) / (double)mColorCount;
this.OnMinMaxCurChanged();
}
}
public double StepSize
{
get {return mStepSize;}
}
public ColorBarStandard(string ColorbarFilename)
{
mColors = null;
mMin = mCurMin = 0;
mMax = mCurMax = 1600;
try
{
LoadColorBar(ColorbarFilename);
}
catch (FileNotFoundException)
{
LoadColorBarDefault();
}
}
public ColorBarStandard()
{
mColors = null;
mMin = mCurMin = 0;
mMax = mCurMax = 1600;
LoadColorBarDefault();
}
public void LoadColorBar(string fileName)
{
if (File.Exists(fileName))
{
string colorLine;
string[] colorArray;
bool redFilled, greenFilled, blueFilled;
byte redColor, greenColor, blueColor;
ArrayList colorsArray = new ArrayList();
char splitDelimiter;
using (StreamReader colorbarStream = new StreamReader(fileName))
{
colorLine = colorbarStream.ReadLine();
if (colorLine.Split(',').Length > 1)
splitDelimiter = ',';
else if (colorLine.Split(' ').Length > 1)
splitDelimiter = ' ';
else
throw new System.IO.FileLoadException("File was not of expected format.", fileName);
}
using (StreamReader colorbarStream = new StreamReader(fileName))
{
redFilled = greenFilled = blueFilled = false;
redColor = greenColor = blueColor = byte.MinValue;
while ((colorLine = colorbarStream.ReadLine()) != null)
{
//if there is a blank line, ignore it
if (colorLine.Trim() != "")
{
colorArray = colorLine.Trim().Split(splitDelimiter);
if (colorArray.Length < 3)
throw new System.IO.FileLoadException("File was not of expected format.", fileName);
for (int i=0; i<colorArray.Length; i++)
{
if (!redFilled && colorArray[i] != "")
{
redColor = (byte)(float.Parse(colorArray[i]) * 255.0f);
redFilled = true;
}
else if (!greenFilled && colorArray[i] != "")
{
greenColor = (byte)(float.Parse(colorArray[i]) * 255.0f);
greenFilled = true;
}
else if (colorArray[i] != "")
{
blueColor = (byte)(float.Parse(colorArray[i]) * 255.0f);
blueFilled = true;
}
}
if (!redFilled || !greenFilled || !blueFilled)
throw new System.IO.FileLoadException("File was not of expected format.", fileName);
colorsArray.Add(Color.FromArgb(redColor, greenColor, blueColor));
redFilled = greenFilled = blueFilled = false;
}
}
mColorCount = colorsArray.Count;
mColors = new Color[mColorCount];
colorsArray.CopyTo(0, mColors, 0, colorsArray.Count);
this.OnColorsChanged();
}
}
else
throw new System.IO.FileNotFoundException("The file was not found.", fileName);
}
public void LoadColorBarDefault()
{
mColorCount = ColorBarStandard.DefaultColors.GetLength(0);
mColors = new Color[mColorCount];
for (int i=0; i<mColorCount; i++)
mColors[i] = Color.FromArgb(ColorBarStandard.DefaultColors[i,0], ColorBarStandard.DefaultColors[i,1], ColorBarStandard.DefaultColors[i,2]);
this.OnColorsChanged();
}
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Collections.Generic;
using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core.Entities;
using TheArtOfDev.HtmlRenderer.Core.Parse;
using TheArtOfDev.HtmlRenderer.Core.Utils;
namespace TheArtOfDev.HtmlRenderer.Core.Dom
{
/// <summary>
/// Layout engine for tables executing the complex layout of tables with rows/columns/headers/etc.
/// </summary>
internal sealed class CssLayoutEngineTable
{
#region Fields and Consts
/// <summary>
/// the main box of the table
/// </summary>
private readonly CssBox _tableBox;
/// <summary>
///
/// </summary>
private CssBox _caption;
private CssBox _headerBox;
private CssBox _footerBox;
/// <summary>
/// collection of all rows boxes
/// </summary>
private readonly List<CssBox> _bodyrows = new List<CssBox>();
/// <summary>
/// collection of all columns boxes
/// </summary>
private readonly List<CssBox> _columns = new List<CssBox>();
/// <summary>
///
/// </summary>
private readonly List<CssBox> _allRows = new List<CssBox>();
private int _columnCount;
private bool _widthSpecified;
private double[] _columnWidths;
private double[] _columnMinWidths;
#endregion
/// <summary>
/// Init.
/// </summary>
/// <param name="tableBox"></param>
private CssLayoutEngineTable(CssBox tableBox)
{
_tableBox = tableBox;
}
/// <summary>
/// Get the table cells spacing for all the cells in the table.<br/>
/// Used to calculate the spacing the table has in addition to regular padding and borders.
/// </summary>
/// <param name="tableBox">the table box to calculate the spacing for</param>
/// <returns>the calculated spacing</returns>
public static double GetTableSpacing(CssBox tableBox)
{
int count = 0;
int columns = 0;
foreach (var box in tableBox.Boxes)
{
if (box.Display == CssConstants.TableColumn)
{
columns += GetSpan(box);
}
else if (box.Display == CssConstants.TableRowGroup)
{
foreach (CssBox cr in tableBox.Boxes)
{
count++;
if (cr.Display == CssConstants.TableRow)
columns = Math.Max(columns, cr.Boxes.Count);
}
}
else if (box.Display == CssConstants.TableRow)
{
count++;
columns = Math.Max(columns, box.Boxes.Count);
}
// limit the amount of rows to process for performance
if (count > 30)
break;
}
// +1 columns because padding is between the cell and table borders
return (columns + 1) * GetHorizontalSpacing(tableBox);
}
/// <summary>
///
/// </summary>
/// <param name="g"></param>
/// <param name="tableBox"> </param>
public static void PerformLayout(RGraphics g, CssBox tableBox)
{
ArgChecker.AssertArgNotNull(g, "g");
ArgChecker.AssertArgNotNull(tableBox, "tableBox");
try
{
var table = new CssLayoutEngineTable(tableBox);
table.Layout(g);
}
catch (Exception ex)
{
tableBox.HtmlContainer.ReportError(HtmlRenderErrorType.Layout, "Failed table layout", ex);
}
}
#region Private Methods
/// <summary>
/// Analyzes the Table and assigns values to this CssTable object.
/// To be called from the constructor
/// </summary>
private void Layout(RGraphics g)
{
MeasureWords(_tableBox, g);
// get the table boxes into the proper fields
AssignBoxKinds();
// Insert EmptyBoxes for vertical cell spanning.
InsertEmptyBoxes();
// Determine Row and Column Count, and ColumnWidths
var availCellSpace = CalculateCountAndWidth();
DetermineMissingColumnWidths(availCellSpace);
// Check for minimum sizes (increment widths if necessary)
EnforceMinimumSize();
// While table width is larger than it should, and width is reducible
EnforceMaximumSize();
// Ensure there's no padding
_tableBox.PaddingLeft = _tableBox.PaddingTop = _tableBox.PaddingRight = _tableBox.PaddingBottom = "0";
//Actually layout cells!
LayoutCells(g);
}
/// <summary>
/// Get the table boxes into the proper fields.
/// </summary>
private void AssignBoxKinds()
{
foreach (var box in _tableBox.Boxes)
{
switch (box.Display)
{
case CssConstants.TableCaption:
_caption = box;
break;
case CssConstants.TableRow:
_bodyrows.Add(box);
break;
case CssConstants.TableRowGroup:
foreach (CssBox childBox in box.Boxes)
if (childBox.Display == CssConstants.TableRow)
_bodyrows.Add(childBox);
break;
case CssConstants.TableHeaderGroup:
if (_headerBox != null)
_bodyrows.Add(box);
else
_headerBox = box;
break;
case CssConstants.TableFooterGroup:
if (_footerBox != null)
_bodyrows.Add(box);
else
_footerBox = box;
break;
case CssConstants.TableColumn:
for (int i = 0; i < GetSpan(box); i++)
_columns.Add(box);
break;
case CssConstants.TableColumnGroup:
if (box.Boxes.Count == 0)
{
int gspan = GetSpan(box);
for (int i = 0; i < gspan; i++)
{
_columns.Add(box);
}
}
else
{
foreach (CssBox bb in box.Boxes)
{
int bbspan = GetSpan(bb);
for (int i = 0; i < bbspan; i++)
{
_columns.Add(bb);
}
}
}
break;
}
}
if (_headerBox != null)
_allRows.AddRange(_headerBox.Boxes);
_allRows.AddRange(_bodyrows);
if (_footerBox != null)
_allRows.AddRange(_footerBox.Boxes);
}
/// <summary>
/// Insert EmptyBoxes for vertical cell spanning.
/// </summary>
private void InsertEmptyBoxes()
{
if (!_tableBox._tableFixed)
{
int currow = 0;
List<CssBox> rows = _bodyrows;
foreach (CssBox row in rows)
{
for (int k = 0; k < row.Boxes.Count; k++)
{
CssBox cell = row.Boxes[k];
int rowspan = GetRowSpan(cell);
int realcol = GetCellRealColumnIndex(row, cell); //Real column of the cell
for (int i = currow + 1; i < currow + rowspan; i++)
{
if (rows.Count > i)
{
int colcount = 0;
for (int j = 0; j < rows[i].Boxes.Count; j++)
{
if (colcount == realcol)
{
rows[i].Boxes.Insert(colcount, new CssSpacingBox(_tableBox, ref cell, currow));
break;
}
colcount++;
realcol -= GetColSpan(rows[i].Boxes[j]) - 1;
}
}
}
}
currow++;
}
_tableBox._tableFixed = true;
}
}
/// <summary>
/// Determine Row and Column Count, and ColumnWidths
/// </summary>
/// <returns></returns>
private double CalculateCountAndWidth()
{
//Columns
if (_columns.Count > 0)
{
_columnCount = _columns.Count;
}
else
{
foreach (CssBox b in _allRows)
_columnCount = Math.Max(_columnCount, b.Boxes.Count);
}
//Initialize column widths array with NaNs
_columnWidths = new double[_columnCount];
for (int i = 0; i < _columnWidths.Length; i++)
_columnWidths[i] = double.NaN;
double availCellSpace = GetAvailableCellWidth();
if (_columns.Count > 0)
{
// Fill ColumnWidths array by scanning column widths
for (int i = 0; i < _columns.Count; i++)
{
CssLength len = new CssLength(_columns[i].Width); //Get specified width
if (len.Number > 0) //If some width specified
{
if (len.IsPercentage) //Get width as a percentage
{
_columnWidths[i] = CssValueParser.ParseNumber(_columns[i].Width, availCellSpace);
}
else if (len.Unit == CssUnit.Pixels || len.Unit == CssUnit.None)
{
_columnWidths[i] = len.Number; //Get width as an absolute-pixel value
}
}
}
}
else
{
// Fill ColumnWidths array by scanning width in table-cell definitions
foreach (CssBox row in _allRows)
{
//Check for column width in table-cell definitions
for (int i = 0; i < _columnCount; i++)
{
if (i < 20 || double.IsNaN(_columnWidths[i])) // limit column width check
{
if (i < row.Boxes.Count && row.Boxes[i].Display == CssConstants.TableCell)
{
double len = CssValueParser.ParseLength(row.Boxes[i].Width, availCellSpace, row.Boxes[i]);
if (len > 0) //If some width specified
{
int colspan = GetColSpan(row.Boxes[i]);
len /= Convert.ToSingle(colspan);
for (int j = i; j < i + colspan; j++)
{
_columnWidths[j] = double.IsNaN(_columnWidths[j]) ? len : Math.Max(_columnWidths[j], len);
}
}
}
}
}
}
}
return availCellSpace;
}
/// <summary>
///
/// </summary>
/// <param name="availCellSpace"></param>
private void DetermineMissingColumnWidths(double availCellSpace)
{
double occupedSpace = 0f;
if (_widthSpecified) //If a width was specified,
{
//Assign NaNs equally with space left after gathering not-NaNs
int numOfNans = 0;
//Calculate number of NaNs and occupied space
foreach (double colWidth in _columnWidths)
{
if (double.IsNaN(colWidth))
numOfNans++;
else
occupedSpace += colWidth;
}
var orgNumOfNans = numOfNans;
double[] orgColWidths = null;
if (numOfNans < _columnWidths.Length)
{
orgColWidths = new double[_columnWidths.Length];
for (int i = 0; i < _columnWidths.Length; i++)
orgColWidths[i] = _columnWidths[i];
}
if (numOfNans > 0)
{
// Determine the max width for each column
double[] minFullWidths, maxFullWidths;
GetColumnsMinMaxWidthByContent(true, out minFullWidths, out maxFullWidths);
// set the columns that can fulfill by the max width in a loop because it changes the nanWidth
int oldNumOfNans;
do
{
oldNumOfNans = numOfNans;
for (int i = 0; i < _columnWidths.Length; i++)
{
var nanWidth = (availCellSpace - occupedSpace) / numOfNans;
if (double.IsNaN(_columnWidths[i]) && nanWidth > maxFullWidths[i])
{
_columnWidths[i] = maxFullWidths[i];
numOfNans--;
occupedSpace += maxFullWidths[i];
}
}
} while (oldNumOfNans != numOfNans);
if (numOfNans > 0)
{
// Determine width that will be assigned to un assigned widths
double nanWidth = (availCellSpace - occupedSpace) / numOfNans;
for (int i = 0; i < _columnWidths.Length; i++)
{
if (double.IsNaN(_columnWidths[i]))
_columnWidths[i] = nanWidth;
}
}
}
if (numOfNans == 0 && occupedSpace < availCellSpace)
{
if (orgNumOfNans > 0)
{
// spread extra width between all non width specified columns
double extWidth = (availCellSpace - occupedSpace) / orgNumOfNans;
for (int i = 0; i < _columnWidths.Length; i++)
if (orgColWidths == null || double.IsNaN(orgColWidths[i]))
_columnWidths[i] += extWidth;
}
else
{
// spread extra width between all columns with respect to relative sizes
for (int i = 0; i < _columnWidths.Length; i++)
_columnWidths[i] += (availCellSpace - occupedSpace) * (_columnWidths[i] / occupedSpace);
}
}
}
else
{
//Get the minimum and maximum full length of NaN boxes
double[] minFullWidths, maxFullWidths;
GetColumnsMinMaxWidthByContent(true, out minFullWidths, out maxFullWidths);
for (int i = 0; i < _columnWidths.Length; i++)
{
if (double.IsNaN(_columnWidths[i]))
_columnWidths[i] = minFullWidths[i];
occupedSpace += _columnWidths[i];
}
// spread extra width between all columns
for (int i = 0; i < _columnWidths.Length; i++)
{
if (maxFullWidths[i] > _columnWidths[i])
{
var temp = _columnWidths[i];
_columnWidths[i] = Math.Min(_columnWidths[i] + (availCellSpace - occupedSpace) / Convert.ToSingle(_columnWidths.Length - i), maxFullWidths[i]);
occupedSpace = occupedSpace + _columnWidths[i] - temp;
}
}
}
}
/// <summary>
/// While table width is larger than it should, and width is reductable.<br/>
/// If table max width is limited by we need to lower the columns width even if it will result in clipping<br/>
/// </summary>
private void EnforceMaximumSize()
{
int curCol = 0;
var widthSum = GetWidthSum();
while (widthSum > GetAvailableTableWidth() && CanReduceWidth())
{
while (!CanReduceWidth(curCol))
curCol++;
_columnWidths[curCol] -= 1f;
curCol++;
if (curCol >= _columnWidths.Length)
curCol = 0;
}
// if table max width is limited by we need to lower the columns width even if it will result in clipping
var maxWidth = GetMaxTableWidth();
if (maxWidth < 90999)
{
widthSum = GetWidthSum();
if (maxWidth < widthSum)
{
//Get the minimum and maximum full length of NaN boxes
double[] minFullWidths, maxFullWidths;
GetColumnsMinMaxWidthByContent(false, out minFullWidths, out maxFullWidths);
// lower all the columns to the minimum
for (int i = 0; i < _columnWidths.Length; i++)
_columnWidths[i] = minFullWidths[i];
// either min for all column is not enought and we need to lower it more resulting in clipping
// or we now have extra space so we can give it to columns than need it
widthSum = GetWidthSum();
if (maxWidth < widthSum)
{
// lower the width of columns starting from the largest one until the max width is satisfied
for (int a = 0; a < 15 && maxWidth < widthSum - 0.1; a++) // limit iteration so bug won't create infinite loop
{
int nonMaxedColumns = 0;
double largeWidth = 0f, secLargeWidth = 0f;
for (int i = 0; i < _columnWidths.Length; i++)
{
if (_columnWidths[i] > largeWidth + 0.1)
{
secLargeWidth = largeWidth;
largeWidth = _columnWidths[i];
nonMaxedColumns = 1;
}
else if (_columnWidths[i] > largeWidth - 0.1)
{
nonMaxedColumns++;
}
}
double decrease = secLargeWidth > 0 ? largeWidth - secLargeWidth : (widthSum - maxWidth) / _columnWidths.Length;
if (decrease * nonMaxedColumns > widthSum - maxWidth)
decrease = (widthSum - maxWidth) / nonMaxedColumns;
for (int i = 0; i < _columnWidths.Length; i++)
if (_columnWidths[i] > largeWidth - 0.1)
_columnWidths[i] -= decrease;
widthSum = GetWidthSum();
}
}
else
{
// spread extra width to columns that didn't reached max width where trying to spread it between all columns
for (int a = 0; a < 15 && maxWidth > widthSum + 0.1; a++) // limit iteration so bug won't create infinite loop
{
int nonMaxedColumns = 0;
for (int i = 0; i < _columnWidths.Length; i++)
if (_columnWidths[i] + 1 < maxFullWidths[i])
nonMaxedColumns++;
if (nonMaxedColumns == 0)
nonMaxedColumns = _columnWidths.Length;
bool hit = false;
double minIncrement = (maxWidth - widthSum) / nonMaxedColumns;
for (int i = 0; i < _columnWidths.Length; i++)
{
if (_columnWidths[i] + 0.1 < maxFullWidths[i])
{
minIncrement = Math.Min(minIncrement, maxFullWidths[i] - _columnWidths[i]);
hit = true;
}
}
for (int i = 0; i < _columnWidths.Length; i++)
if (!hit || _columnWidths[i] + 1 < maxFullWidths[i])
_columnWidths[i] += minIncrement;
widthSum = GetWidthSum();
}
}
}
}
}
/// <summary>
/// Check for minimum sizes (increment widths if necessary)
/// </summary>
private void EnforceMinimumSize()
{
foreach (CssBox row in _allRows)
{
foreach (CssBox cell in row.Boxes)
{
int colspan = GetColSpan(cell);
int col = GetCellRealColumnIndex(row, cell);
int affectcol = col + colspan - 1;
if (_columnWidths.Length > col && _columnWidths[col] < GetColumnMinWidths()[col])
{
double diff = GetColumnMinWidths()[col] - _columnWidths[col];
_columnWidths[affectcol] = GetColumnMinWidths()[affectcol];
if (col < _columnWidths.Length - 1)
{
_columnWidths[col + 1] -= diff;
}
}
}
}
}
/// <summary>
/// Layout the cells by the calculated table layout
/// </summary>
/// <param name="g"></param>
private void LayoutCells(RGraphics g)
{
double startx = Math.Max(_tableBox.ClientLeft + GetHorizontalSpacing(), 0);
double starty = Math.Max(_tableBox.ClientTop + GetVerticalSpacing(), 0);
double cury = starty;
double maxRight = startx;
double maxBottom = 0f;
int currentrow = 0;
for (int i = 0; i < _allRows.Count; i++)
{
var row = _allRows[i];
double curx = startx;
int curCol = 0;
for (int j = 0; j < row.Boxes.Count; j++)
{
CssBox cell = row.Boxes[j];
if (curCol >= _columnWidths.Length)
break;
int rowspan = GetRowSpan(cell);
var columnIndex = GetCellRealColumnIndex(row, cell);
double width = GetCellWidth(columnIndex, cell);
cell.Location = new RPoint(curx, cury);
cell.Size = new RSize(width, 0f);
cell.PerformLayout(g); //That will automatically set the bottom of the cell
//Alter max bottom only if row is cell's row + cell's rowspan - 1
CssSpacingBox sb = cell as CssSpacingBox;
if (sb != null)
{
if (sb.EndRow == currentrow)
{
maxBottom = Math.Max(maxBottom, sb.ExtendedBox.ActualBottom);
}
}
else if (rowspan == 1)
{
maxBottom = Math.Max(maxBottom, cell.ActualBottom);
}
maxRight = Math.Max(maxRight, cell.ActualRight);
curCol++;
curx = cell.ActualRight + GetHorizontalSpacing();
}
foreach (CssBox cell in row.Boxes)
{
CssSpacingBox spacer = cell as CssSpacingBox;
if (spacer == null && GetRowSpan(cell) == 1)
{
cell.ActualBottom = maxBottom;
CssLayoutEngine.ApplyCellVerticalAlignment(g, cell);
}
else if (spacer != null && spacer.EndRow == currentrow)
{
spacer.ExtendedBox.ActualBottom = maxBottom;
CssLayoutEngine.ApplyCellVerticalAlignment(g, spacer.ExtendedBox);
}
}
cury = maxBottom + GetVerticalSpacing();
currentrow++;
}
maxRight = Math.Max(maxRight, _tableBox.Location.X + _tableBox.ActualWidth);
_tableBox.ActualRight = maxRight + GetHorizontalSpacing() + _tableBox.ActualBorderRightWidth;
_tableBox.ActualBottom = Math.Max(maxBottom, starty) + GetVerticalSpacing() + _tableBox.ActualBorderBottomWidth;
}
/// <summary>
/// Gets the spanned width of a cell (With of all columns it spans minus one).
/// </summary>
private double GetSpannedMinWidth(CssBox row, CssBox cell, int realcolindex, int colspan)
{
double w = 0f;
for (int i = realcolindex; i < row.Boxes.Count || i < realcolindex + colspan - 1; i++)
{
if (i < GetColumnMinWidths().Length)
w += GetColumnMinWidths()[i];
}
return w;
}
/// <summary>
/// Gets the cell column index checking its position and other cells colspans
/// </summary>
/// <param name="row"></param>
/// <param name="cell"></param>
/// <returns></returns>
private static int GetCellRealColumnIndex(CssBox row, CssBox cell)
{
int i = 0;
foreach (CssBox b in row.Boxes)
{
if (b.Equals(cell))
break;
i += GetColSpan(b);
}
return i;
}
/// <summary>
/// Gets the cells width, taking colspan and being in the specified column
/// </summary>
/// <param name="column"></param>
/// <param name="b"></param>
/// <returns></returns>
private double GetCellWidth(int column, CssBox b)
{
double colspan = Convert.ToSingle(GetColSpan(b));
double sum = 0f;
for (int i = column; i < column + colspan; i++)
{
if (column >= _columnWidths.Length)
break;
if (_columnWidths.Length <= i)
break;
sum += _columnWidths[i];
}
sum += (colspan - 1) * GetHorizontalSpacing();
return sum; // -b.ActualBorderLeftWidth - b.ActualBorderRightWidth - b.ActualPaddingRight - b.ActualPaddingLeft;
}
/// <summary>
/// Gets the colspan of the specified box
/// </summary>
/// <param name="b"></param>
private static int GetColSpan(CssBox b)
{
string att = b.GetAttribute("colspan", "1");
int colspan;
if (!int.TryParse(att, out colspan))
{
return 1;
}
return colspan;
}
/// <summary>
/// Gets the rowspan of the specified box
/// </summary>
/// <param name="b"></param>
private static int GetRowSpan(CssBox b)
{
string att = b.GetAttribute("rowspan", "1");
int rowspan;
if (!int.TryParse(att, out rowspan))
{
return 1;
}
return rowspan;
}
/// <summary>
/// Recursively measures words inside the box
/// </summary>
/// <param name="box">the box to measure</param>
/// <param name="g">Device to use</param>
private static void MeasureWords(CssBox box, RGraphics g)
{
if (box != null)
{
foreach (var childBox in box.Boxes)
{
childBox.MeasureWordsSize(g);
MeasureWords(childBox, g);
}
}
}
/// <summary>
/// Tells if the columns widths can be reduced,
/// by checking the minimum widths of all cells
/// </summary>
/// <returns></returns>
private bool CanReduceWidth()
{
for (int i = 0; i < _columnWidths.Length; i++)
{
if (CanReduceWidth(i))
{
return true;
}
}
return false;
}
/// <summary>
/// Tells if the specified column can be reduced,
/// by checking its minimum width
/// </summary>
/// <param name="columnIndex"></param>
/// <returns></returns>
private bool CanReduceWidth(int columnIndex)
{
if (_columnWidths.Length >= columnIndex || GetColumnMinWidths().Length >= columnIndex)
return false;
return _columnWidths[columnIndex] > GetColumnMinWidths()[columnIndex];
}
/// <summary>
/// Gets the available width for the whole table.
/// It also sets the value of WidthSpecified
/// </summary>
/// <returns></returns>
/// <remarks>
/// The table's width can be larger than the result of this method, because of the minimum
/// size that individual boxes.
/// </remarks>
private double GetAvailableTableWidth()
{
CssLength tblen = new CssLength(_tableBox.Width);
if (tblen.Number > 0)
{
_widthSpecified = true;
return CssValueParser.ParseLength(_tableBox.Width, _tableBox.ParentBox.AvailableWidth, _tableBox);
}
else
{
return _tableBox.ParentBox.AvailableWidth;
}
}
/// <summary>
/// Gets the available width for the whole table.
/// It also sets the value of WidthSpecified
/// </summary>
/// <returns></returns>
/// <remarks>
/// The table's width can be larger than the result of this method, because of the minimum
/// size that individual boxes.
/// </remarks>
private double GetMaxTableWidth()
{
var tblen = new CssLength(_tableBox.MaxWidth);
if (tblen.Number > 0)
{
_widthSpecified = true;
return CssValueParser.ParseLength(_tableBox.MaxWidth, _tableBox.ParentBox.AvailableWidth, _tableBox);
}
else
{
return 9999f;
}
}
/// <summary>
/// Calculate the min and max width for each column of the table by the content in all rows.<br/>
/// the min width possible without clipping content<br/>
/// the max width the cell content can take without wrapping<br/>
/// </summary>
/// <param name="onlyNans">if to measure only columns that have no calculated width</param>
/// <param name="minFullWidths">return the min width for each column - the min width possible without clipping content</param>
/// <param name="maxFullWidths">return the max width for each column - the max width the cell content can take without wrapping</param>
private void GetColumnsMinMaxWidthByContent(bool onlyNans, out double[] minFullWidths, out double[] maxFullWidths)
{
maxFullWidths = new double[_columnWidths.Length];
minFullWidths = new double[_columnWidths.Length];
foreach (CssBox row in _allRows)
{
for (int i = 0; i < row.Boxes.Count; i++)
{
int col = GetCellRealColumnIndex(row, row.Boxes[i]);
col = _columnWidths.Length > col ? col : _columnWidths.Length - 1;
if ((!onlyNans || double.IsNaN(_columnWidths[col])) && i < row.Boxes.Count)
{
double minWidth, maxWidth;
row.Boxes[i].GetMinMaxWidth(out minWidth, out maxWidth);
var colSpan = GetColSpan(row.Boxes[i]);
minWidth = minWidth / colSpan;
maxWidth = maxWidth / colSpan;
for (int j = 0; j < colSpan; j++)
{
minFullWidths[col + j] = Math.Max(minFullWidths[col + j], minWidth);
maxFullWidths[col + j] = Math.Max(maxFullWidths[col + j], maxWidth);
}
}
}
}
}
/// <summary>
/// Gets the width available for cells
/// </summary>
/// <returns></returns>
/// <remarks>
/// It takes away the cell-spacing from <see cref="GetAvailableTableWidth"/>
/// </remarks>
private double GetAvailableCellWidth()
{
return GetAvailableTableWidth() - GetHorizontalSpacing() * (_columnCount + 1) - _tableBox.ActualBorderLeftWidth - _tableBox.ActualBorderRightWidth;
}
/// <summary>
/// Gets the current sum of column widths
/// </summary>
/// <returns></returns>
private double GetWidthSum()
{
double f = 0f;
foreach (double t in _columnWidths)
{
if (double.IsNaN(t))
throw new Exception("CssTable Algorithm error: There's a NaN in column widths");
else
f += t;
}
//Take cell-spacing
f += GetHorizontalSpacing() * (_columnWidths.Length + 1);
//Take table borders
f += _tableBox.ActualBorderLeftWidth + _tableBox.ActualBorderRightWidth;
return f;
}
/// <summary>
/// Gets the span attribute of the tag of the specified box
/// </summary>
/// <param name="b"></param>
private static int GetSpan(CssBox b)
{
double f = CssValueParser.ParseNumber(b.GetAttribute("span"), 1);
return Math.Max(1, Convert.ToInt32(f));
}
/// <summary>
/// Gets the minimum width of each column
/// </summary>
private double[] GetColumnMinWidths()
{
if (_columnMinWidths == null)
{
_columnMinWidths = new double[_columnWidths.Length];
foreach (CssBox row in _allRows)
{
foreach (CssBox cell in row.Boxes)
{
int colspan = GetColSpan(cell);
int col = GetCellRealColumnIndex(row, cell);
int affectcol = Math.Min(col + colspan, _columnMinWidths.Length) - 1;
double spannedwidth = GetSpannedMinWidth(row, cell, col, colspan) + (colspan - 1) * GetHorizontalSpacing();
_columnMinWidths[affectcol] = Math.Max(_columnMinWidths[affectcol], cell.GetMinimumWidth() - spannedwidth);
}
}
}
return _columnMinWidths;
}
/// <summary>
/// Gets the actual horizontal spacing of the table
/// </summary>
private double GetHorizontalSpacing()
{
return _tableBox.BorderCollapse == CssConstants.Collapse ? -1f : _tableBox.ActualBorderSpacingHorizontal;
}
/// <summary>
/// Gets the actual horizontal spacing of the table
/// </summary>
private static double GetHorizontalSpacing(CssBox box)
{
return box.BorderCollapse == CssConstants.Collapse ? -1f : box.ActualBorderSpacingHorizontal;
}
/// <summary>
/// Gets the actual vertical spacing of the table
/// </summary>
private double GetVerticalSpacing()
{
return _tableBox.BorderCollapse == CssConstants.Collapse ? -1f : _tableBox.ActualBorderSpacingVertical;
}
#endregion
}
}
| |
namespace Microsoft.CodeAnalysis.CSharp
{
internal static partial class ErrorFacts
{
public static bool IsWarning(ErrorCode code)
{
switch (code)
{
case ErrorCode.WRN_InvalidMainSig:
case ErrorCode.WRN_UnreferencedEvent:
case ErrorCode.WRN_LowercaseEllSuffix:
case ErrorCode.WRN_DuplicateUsing:
case ErrorCode.WRN_NewRequired:
case ErrorCode.WRN_NewNotRequired:
case ErrorCode.WRN_NewOrOverrideExpected:
case ErrorCode.WRN_UnreachableCode:
case ErrorCode.WRN_UnreferencedLabel:
case ErrorCode.WRN_UnreferencedVar:
case ErrorCode.WRN_UnreferencedField:
case ErrorCode.WRN_IsAlwaysTrue:
case ErrorCode.WRN_IsAlwaysFalse:
case ErrorCode.WRN_ByRefNonAgileField:
case ErrorCode.WRN_UnreferencedVarAssg:
case ErrorCode.WRN_NegativeArrayIndex:
case ErrorCode.WRN_BadRefCompareLeft:
case ErrorCode.WRN_BadRefCompareRight:
case ErrorCode.WRN_PatternIsAmbiguous:
case ErrorCode.WRN_PatternStaticOrInaccessible:
case ErrorCode.WRN_PatternBadSignature:
case ErrorCode.WRN_SequentialOnPartialClass:
case ErrorCode.WRN_MainCantBeGeneric:
case ErrorCode.WRN_UnreferencedFieldAssg:
case ErrorCode.WRN_AmbiguousXMLReference:
case ErrorCode.WRN_VolatileByRef:
case ErrorCode.WRN_SameFullNameThisNsAgg:
case ErrorCode.WRN_SameFullNameThisAggAgg:
case ErrorCode.WRN_SameFullNameThisAggNs:
case ErrorCode.WRN_GlobalAliasDefn:
case ErrorCode.WRN_AlwaysNull:
case ErrorCode.WRN_CmpAlwaysFalse:
case ErrorCode.WRN_FinalizeMethod:
case ErrorCode.WRN_GotoCaseShouldConvert:
case ErrorCode.WRN_NubExprIsConstBool:
case ErrorCode.WRN_ExplicitImplCollision:
case ErrorCode.WRN_DeprecatedSymbol:
case ErrorCode.WRN_DeprecatedSymbolStr:
case ErrorCode.WRN_ExternMethodNoImplementation:
case ErrorCode.WRN_ProtectedInSealed:
case ErrorCode.WRN_PossibleMistakenNullStatement:
case ErrorCode.WRN_UnassignedInternalField:
case ErrorCode.WRN_VacuousIntegralComp:
case ErrorCode.WRN_AttributeLocationOnBadDeclaration:
case ErrorCode.WRN_InvalidAttributeLocation:
case ErrorCode.WRN_EqualsWithoutGetHashCode:
case ErrorCode.WRN_EqualityOpWithoutEquals:
case ErrorCode.WRN_EqualityOpWithoutGetHashCode:
case ErrorCode.WRN_IncorrectBooleanAssg:
case ErrorCode.WRN_NonObsoleteOverridingObsolete:
case ErrorCode.WRN_BitwiseOrSignExtend:
case ErrorCode.WRN_CoClassWithoutComImport:
case ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter:
case ErrorCode.WRN_AssignmentToLockOrDispose:
case ErrorCode.WRN_ObsoleteOverridingNonObsolete:
case ErrorCode.WRN_DebugFullNameTooLong:
case ErrorCode.WRN_ExternCtorNoImplementation:
case ErrorCode.WRN_WarningDirective:
case ErrorCode.WRN_UnreachableGeneralCatch:
case ErrorCode.WRN_DeprecatedCollectionInitAddStr:
case ErrorCode.WRN_DeprecatedCollectionInitAdd:
case ErrorCode.WRN_DefaultValueForUnconsumedLocation:
case ErrorCode.WRN_IdentifierOrNumericLiteralExpected:
case ErrorCode.WRN_EmptySwitch:
case ErrorCode.WRN_XMLParseError:
case ErrorCode.WRN_DuplicateParamTag:
case ErrorCode.WRN_UnmatchedParamTag:
case ErrorCode.WRN_MissingParamTag:
case ErrorCode.WRN_BadXMLRef:
case ErrorCode.WRN_BadXMLRefParamType:
case ErrorCode.WRN_BadXMLRefReturnType:
case ErrorCode.WRN_BadXMLRefSyntax:
case ErrorCode.WRN_UnprocessedXMLComment:
case ErrorCode.WRN_FailedInclude:
case ErrorCode.WRN_InvalidInclude:
case ErrorCode.WRN_MissingXMLComment:
case ErrorCode.WRN_XMLParseIncludeError:
case ErrorCode.WRN_ALinkWarn:
case ErrorCode.WRN_CmdOptionConflictsSource:
case ErrorCode.WRN_IllegalPragma:
case ErrorCode.WRN_IllegalPPWarning:
case ErrorCode.WRN_BadRestoreNumber:
case ErrorCode.WRN_NonECMAFeature:
case ErrorCode.WRN_ErrorOverride:
case ErrorCode.WRN_InvalidSearchPathDir:
case ErrorCode.WRN_MultiplePredefTypes:
case ErrorCode.WRN_TooManyLinesForDebugger:
case ErrorCode.WRN_CallOnNonAgileField:
case ErrorCode.WRN_InvalidNumber:
case ErrorCode.WRN_IllegalPPChecksum:
case ErrorCode.WRN_EndOfPPLineExpected:
case ErrorCode.WRN_ConflictingChecksum:
case ErrorCode.WRN_InvalidAssemblyName:
case ErrorCode.WRN_UnifyReferenceMajMin:
case ErrorCode.WRN_UnifyReferenceBldRev:
case ErrorCode.WRN_DuplicateTypeParamTag:
case ErrorCode.WRN_UnmatchedTypeParamTag:
case ErrorCode.WRN_MissingTypeParamTag:
case ErrorCode.WRN_AssignmentToSelf:
case ErrorCode.WRN_ComparisonToSelf:
case ErrorCode.WRN_DotOnDefault:
case ErrorCode.WRN_BadXMLRefTypeVar:
case ErrorCode.WRN_UnmatchedParamRefTag:
case ErrorCode.WRN_UnmatchedTypeParamRefTag:
case ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA:
case ErrorCode.WRN_CantHaveManifestForModule:
case ErrorCode.WRN_MultipleRuntimeImplementationMatches:
case ErrorCode.WRN_MultipleRuntimeOverrideMatches:
case ErrorCode.WRN_DynamicDispatchToConditionalMethod:
case ErrorCode.WRN_IsDynamicIsConfusing:
case ErrorCode.WRN_AsyncLacksAwaits:
case ErrorCode.WRN_FileAlreadyIncluded:
case ErrorCode.WRN_NoSources:
case ErrorCode.WRN_NoConfigNotOnCommandLine:
case ErrorCode.WRN_DefineIdentifierRequired:
case ErrorCode.WRN_BadUILang:
case ErrorCode.WRN_CLS_NoVarArgs:
case ErrorCode.WRN_CLS_BadArgType:
case ErrorCode.WRN_CLS_BadReturnType:
case ErrorCode.WRN_CLS_BadFieldPropType:
case ErrorCode.WRN_CLS_BadIdentifierCase:
case ErrorCode.WRN_CLS_OverloadRefOut:
case ErrorCode.WRN_CLS_OverloadUnnamed:
case ErrorCode.WRN_CLS_BadIdentifier:
case ErrorCode.WRN_CLS_BadBase:
case ErrorCode.WRN_CLS_BadInterfaceMember:
case ErrorCode.WRN_CLS_NoAbstractMembers:
case ErrorCode.WRN_CLS_NotOnModules:
case ErrorCode.WRN_CLS_ModuleMissingCLS:
case ErrorCode.WRN_CLS_AssemblyNotCLS:
case ErrorCode.WRN_CLS_BadAttributeType:
case ErrorCode.WRN_CLS_ArrayArgumentToAttribute:
case ErrorCode.WRN_CLS_NotOnModules2:
case ErrorCode.WRN_CLS_IllegalTrueInFalse:
case ErrorCode.WRN_CLS_MeaninglessOnPrivateType:
case ErrorCode.WRN_CLS_AssemblyNotCLS2:
case ErrorCode.WRN_CLS_MeaninglessOnParam:
case ErrorCode.WRN_CLS_MeaninglessOnReturn:
case ErrorCode.WRN_CLS_BadTypeVar:
case ErrorCode.WRN_CLS_VolatileField:
case ErrorCode.WRN_CLS_BadInterface:
case ErrorCode.WRN_UnobservedAwaitableExpression:
case ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation:
case ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation:
case ErrorCode.WRN_CallerMemberNameParamForUnconsumedLocation:
case ErrorCode.WRN_MainIgnored:
case ErrorCode.WRN_DelaySignButNoKey:
case ErrorCode.WRN_InvalidVersionFormat:
case ErrorCode.WRN_CallerFilePathPreferredOverCallerMemberName:
case ErrorCode.WRN_CallerLineNumberPreferredOverCallerMemberName:
case ErrorCode.WRN_CallerLineNumberPreferredOverCallerFilePath:
case ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden:
case ErrorCode.WRN_FilterIsConstant:
case ErrorCode.WRN_UnimplementedCommandLineSwitch:
case ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName:
case ErrorCode.WRN_RefCultureMismatch:
case ErrorCode.WRN_ConflictingMachineAssembly:
case ErrorCode.WRN_UnqualifiedNestedTypeInCref:
case ErrorCode.WRN_NoRuntimeMetadataVersion:
case ErrorCode.WRN_PdbLocalNameTooLong:
case ErrorCode.WRN_AnalyzerCannotBeCreated:
case ErrorCode.WRN_NoAnalyzerInAssembly:
case ErrorCode.WRN_UnableToLoadAnalyzer:
case ErrorCode.WRN_NubExprIsConstBool2:
case ErrorCode.WRN_AlignmentMagnitude:
case ErrorCode.WRN_AttributeIgnoredWhenPublicSigning:
case ErrorCode.WRN_TupleLiteralNameMismatch:
case ErrorCode.WRN_DefaultInSwitch:
return true;
default:
return false;
}
}
public static bool IsFatal(ErrorCode code)
{
switch (code)
{
case ErrorCode.FTL_MetadataCantOpenFile:
case ErrorCode.FTL_DebugEmitFailure:
case ErrorCode.FTL_BadCodepage:
case ErrorCode.FTL_InvalidTarget:
case ErrorCode.FTL_InputFileNameTooLong:
case ErrorCode.FTL_OutputFileExists:
case ErrorCode.FTL_BadChecksumAlgorithm:
return true;
default:
return false;
}
}
public static bool IsInfo(ErrorCode code)
{
switch (code)
{
case ErrorCode.INF_UnableToLoadSomeTypesInAnalyzer:
return true;
default:
return false;
}
}
public static bool IsHidden(ErrorCode code)
{
switch (code)
{
case ErrorCode.HDN_UnusedUsingDirective:
case ErrorCode.HDN_UnusedExternAlias:
return true;
default:
return false;
}
}
}
}
| |
using System;
using System.Data;
using System.Linq.Expressions;
using FluentMigrator.Exceptions;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Tests.Integration;
using Moq;
using NUnit.Framework;
namespace FluentMigrator.Tests.Unit
{
[TestFixture]
[Obsolete]
public class ObsoleteTaskExecutorTests : IntegrationTestBase
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
_migrationRunner = new Mock<IMigrationRunner>();
}
#endregion
private Mock<IMigrationRunner> _migrationRunner;
private void Verify(Expression<Action<IMigrationRunner>> func, string task, long version, int steps)
{
_migrationRunner.Setup(func).Verifiable();
var processor = new Mock<IMigrationProcessor>();
const string profile = "Debug";
var dataSet = new DataSet();
dataSet.Tables.Add(new DataTable());
processor.Setup(x => x.ReadTableData(null, It.IsAny<string>())).Returns(dataSet);
_migrationRunner.SetupGet(x => x.Processor).Returns(processor.Object);
var stepsStore = steps;
var announcer = new Mock<IAnnouncer>();
var stopWatch = new Mock<IStopWatch>();
var runnerContext = new Mock<IRunnerContext>();
runnerContext.SetupGet(x => x.Announcer).Returns(announcer.Object);
runnerContext.SetupGet(x => x.StopWatch).Returns(stopWatch.Object);
runnerContext.SetupGet(x => x.Database).Returns("sqlserver2008");
runnerContext.SetupGet(x => x.Connection).Returns(IntegrationTestOptions.SqlServer2008.ConnectionString);
runnerContext.SetupGet(x => x.Task).Returns(task);
runnerContext.SetupGet(x => x.Version).Returns(version);
runnerContext.SetupGet(x => x.Steps).Returns(() => stepsStore);
runnerContext.SetupSet(x => x.Steps = It.IsAny<int>()).Callback<int>(v => stepsStore = v);
runnerContext.SetupGet(x => x.Targets).Returns(new[] { GetType().Assembly.Location });
runnerContext.SetupGet(x => x.Profile).Returns(profile);
runnerContext.SetupGet(x => x.Namespace).Returns("FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass3");
var taskExecutor = new FakeTaskExecutor(runnerContext.Object, _migrationRunner.Object);
taskExecutor.Execute();
_migrationRunner.VerifyAll();
}
[Test]
public void InvalidProviderNameShouldThrowArgumentException()
{
var runnerContext = new Mock<IRunnerContext>();
runnerContext.SetupGet(x => x.Database).Returns("sqlWRONG");
runnerContext.SetupGet(x => x.Connection).Returns(IntegrationTestOptions.SqlServer2008.ConnectionString);
runnerContext.SetupGet(x => x.Targets).Returns(new[] { GetType().Assembly.Location });
runnerContext.SetupGet(x => x.Announcer).Returns(new Mock<IAnnouncer>().Object);
Assert.Throws<ProcessorFactoryNotFoundException>(() => new TaskExecutor(runnerContext.Object).Execute());
}
[Test]
public void ShouldCallMigrateDownIfSpecified()
{
Verify(x => x.MigrateDown(It.Is<long>(c => c == 20)), "migrate:down", 20, 0);
}
[Test]
public void ShouldCallMigrateUpByDefault()
{
Verify(x => x.MigrateUp(), null, 0, 0);
Verify(x => x.MigrateUp(), "", 0, 0);
}
[Test]
public void ShouldCallMigrateUpIfSpecified()
{
Verify(x => x.MigrateUp(), "migrate", 0, 0);
Verify(x => x.MigrateUp(), "migrate:up", 0, 0);
}
[Test]
public void ShouldCallMigrateUpWithVersionIfSpecified()
{
Verify(x => x.MigrateUp(It.Is<long>(c => c == 1)), "migrate", 1, 0);
Verify(x => x.MigrateUp(It.Is<long>(c => c == 1)), "migrate:up", 1, 0);
}
[Test]
public void ShouldCallRollbackIfSpecified()
{
Verify(x => x.Rollback(It.Is<int>(c => c == 2)), "rollback", 0, 2);
}
[Test]
public void ShouldCallRollbackIfSpecifiedAndDefaultTo1Step()
{
Verify(x => x.Rollback(It.Is<int>(c => c == 1)), "rollback", 0, 0);
}
[Test]
public void ShouldCallValidateVersionOrder()
{
Verify(x => x.ValidateVersionOrder(), "validateversionorder", 0, 0);
}
[Test]
public void ShouldCallHasMigrationsToApplyUpWithNullVersionOnNoTask()
{
VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => !version.HasValue)), "", 0);
}
[Test]
public void ShouldCallHasMigrationsToApplyUpWithVersionOnNoTask()
{
VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => version.GetValueOrDefault() == 1)), "", 1);
}
[Test]
public void ShouldCallHasMigrationsToApplyUpWithNullVersionOnMigrate()
{
VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => !version.HasValue)), "migrate", 0);
}
[Test]
public void ShouldCallHasMigrationsToApplyUpWithVersionOnMigrate()
{
VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => version.GetValueOrDefault() == 1)), "migrate", 1);
}
[Test]
public void ShouldCallHasMigrationsToApplyUpWithNullVersionOnMigrateUp()
{
VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => !version.HasValue)), "migrate:up", 0);
}
[Test]
public void ShouldCallHasMigrationsToApplyUpWithVersionOnMigrateUp()
{
VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyUp(It.Is<long?>(version => version.GetValueOrDefault() == 1)), "migrate:up", 1);
}
[Test]
public void ShouldCallHasMigrationsToApplyRollbackOnRollback()
{
VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyRollback(), "rollback", 0);
}
[Test]
public void ShouldCallHasMigrationsToApplyRollbackOnRollbackAll()
{
VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyRollback(), "rollback:all", 0);
}
[Test]
public void ShouldCallHasMigrationsToApplyDownOnRollbackToVersion()
{
VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyDown(It.Is<long>(version => version == 2)), "rollback:toversion", 2);
}
[Test]
public void ShouldCallHasMigrationsToApplyDownOnMigrateDown()
{
VerifyHasMigrationsToApply(x => x.HasMigrationsToApplyDown(It.Is<long>(version => version == 2)), "migrate:down", 2);
}
private void VerifyHasMigrationsToApply(Expression<Func<IMigrationRunner, bool>> func, string task, long version)
{
_migrationRunner.Setup(func).Verifiable();
var processor = new Mock<IMigrationProcessor>();
var dataSet = new DataSet();
dataSet.Tables.Add(new DataTable());
processor.Setup(x => x.ReadTableData(null, It.IsAny<string>())).Returns(dataSet);
_migrationRunner.SetupGet(x => x.Processor).Returns(processor.Object);
var runnerContext = new Mock<IRunnerContext>();
runnerContext.SetupGet(x => x.Task).Returns(task);
runnerContext.SetupGet(rc => rc.Version).Returns(version);
var taskExecutor = new FakeTaskExecutor(runnerContext.Object, _migrationRunner.Object);
taskExecutor.HasMigrationsToApply();
_migrationRunner.Verify(func, Times.Once());
}
internal class FakeTaskExecutor : TaskExecutor
{
private readonly IMigrationRunner _runner;
public FakeTaskExecutor(IRunnerContext runnerContext, IMigrationRunner runner) : base(runnerContext)
{
_runner = runner;
}
protected override void Initialize()
{
Runner = _runner;
}
}
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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.Text;
namespace C5
{
/// <summary>
/// <i>(Describe usage of "L:300" format string.)</i>
/// </summary>
public interface IShowable : IFormattable
{
//TODO: wonder if we should use TextWriters instead of StringBuilders?
/// <summary>
/// Format <code>this</code> using at most approximately <code>rest</code> chars and
/// append the result, possibly truncated, to stringbuilder.
/// Subtract the actual number of used chars from <code>rest</code>.
/// </summary>
/// <param name="stringbuilder"></param>
/// <param name="rest"></param>
/// <param name="formatProvider"></param>
/// <returns>True if the appended formatted string was complete (not truncated).</returns>
bool Show(StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider);
}
// ------------------------------------------------------------
// Static helper methods for Showing collections
/// <summary>
///
/// </summary>
public static class Showing
{
/// <summary>
/// Show <code>Object obj</code> by appending it to <code>stringbuilder</code>
/// </summary>
/// <param name="obj"></param>
/// <param name="stringbuilder"></param>
/// <param name="rest"></param>
/// <param name="formatProvider"></param>
/// <returns>True if <code>obj</code> was shown completely.</returns>
public static bool Show(Object obj, StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
IShowable showable;
if (rest <= 0)
return false;
else if ((showable = obj as IShowable) != null)
return showable.Show(stringbuilder, ref rest, formatProvider);
int oldLength = stringbuilder.Length;
stringbuilder.AppendFormat(formatProvider, "{0}", obj);
rest -= (stringbuilder.Length - oldLength);
return true;
}
/// <summary>
///
/// </summary>
/// <param name="showable"></param>
/// <param name="format"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public static String ShowString(IShowable showable, String format, IFormatProvider formatProvider)
{
int rest = maxLength(format);
StringBuilder sb = new StringBuilder();
showable.Show(sb, ref rest, formatProvider);
return sb.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <returns></returns>
static int maxLength(String format)
{
//TODO: validate format string
if (format == null)
return 80;
if (format.Length > 1 && format.StartsWith("L"))
{
return int.Parse(format.Substring(1));
}
else
return int.MaxValue;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="stringbuilder"></param>
/// <param name="rest"></param>
/// <param name="formatProvider"></param>
/// <returns>True if collection was shown completely</returns>
public static bool ShowCollectionValue<T>(ICollectionValue<T> items, StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
string startdelim = "{ ", enddelim = " }";
bool showIndexes = false;
bool showMultiplicities = false;
//TODO: do not test here at run time, but select code at compile time
// perhaps by delivering the print type to this metod
IList<T> list;
ICollection<T> coll = items as ICollection<T>;
if ((list = items as IList<T>) != null)
{
startdelim = "[ ";
enddelim = " ]";
//TODO: should have been (items as IIndexed<T>).IndexingSpeed
showIndexes = list.IndexingSpeed == Speed.Constant;
}
else if (coll != null)
{
if (coll.AllowsDuplicates)
{
startdelim = "{{ ";
enddelim = " }}";
if (coll.DuplicatesByCounting)
showMultiplicities = true;
}
}
stringbuilder.Append(startdelim);
rest -= 2 * startdelim.Length;
bool first = true;
bool complete = true;
int index = 0;
if (showMultiplicities)
{
foreach (KeyValuePair<T, int> p in coll.ItemMultiplicities())
{
complete = false;
if (rest <= 0)
break;
if (first)
first = false;
else
{
stringbuilder.Append(", ");
rest -= 2;
}
if (complete = Showing.Show(p.Key, stringbuilder, ref rest, formatProvider))
{
string multiplicityString = string.Format("(*{0})", p.Value);
stringbuilder.Append(multiplicityString);
rest -= multiplicityString.Length;
}
}
}
else
{
foreach (T x in items)
{
complete = false;
if (rest <= 0)
break;
if (first)
first = false;
else
{
stringbuilder.Append(", ");
rest -= 2;
}
if (showIndexes)
{
string indexString = string.Format("{0}:", index++);
stringbuilder.Append(indexString);
rest -= indexString.Length;
}
complete = Showing.Show(x, stringbuilder, ref rest, formatProvider);
}
}
if (!complete)
{
stringbuilder.Append("...");
rest -= 3;
}
stringbuilder.Append(enddelim);
return complete;
}
/// <summary>
///
/// </summary>
/// <typeparam name="K"></typeparam>
/// <typeparam name="V"></typeparam>
///
/// <param name="dictionary"></param>
/// <param name="stringbuilder"></param>
/// <param name="formatProvider"></param>
/// <param name="rest"></param>
/// <returns></returns>
public static bool ShowDictionary<K, V>(IDictionary<K, V> dictionary, StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
bool sorted = dictionary is ISortedDictionary<K, V>;
stringbuilder.Append(sorted ? "[ " : "{ ");
rest -= 4; // Account for "( " and " )"
bool first = true;
bool complete = true;
foreach (KeyValuePair<K, V> p in dictionary)
{
complete = false;
if (rest <= 0)
break;
if (first)
first = false;
else
{
stringbuilder.Append(", ");
rest -= 2;
}
complete = Showing.Show(p, stringbuilder, ref rest, formatProvider);
}
if (!complete)
{
stringbuilder.Append("...");
rest -= 3;
}
stringbuilder.Append(sorted ? " ]" : " }");
return complete;
}
}
}
| |
/*
* 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-2014-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for Instance Object
/// </summary>
public class InstanceUnmarshaller : IUnmarshaller<Instance, XmlUnmarshallerContext>, IUnmarshaller<Instance, JsonUnmarshallerContext>
{
public Instance Unmarshall(XmlUnmarshallerContext context)
{
Instance unmarshalledObject = new Instance();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("amiLaunchIndex", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.AmiLaunchIndex = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("architecture", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Architecture = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("blockDeviceMapping/item", targetDepth))
{
var unmarshaller = InstanceBlockDeviceMappingUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.BlockDeviceMappings.Add(item);
continue;
}
if (context.TestExpression("clientToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ClientToken = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ebsOptimized", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.EbsOptimized = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("hypervisor", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Hypervisor = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("iamInstanceProfile", targetDepth))
{
var unmarshaller = IamInstanceProfileUnmarshaller.Instance;
unmarshalledObject.IamInstanceProfile = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("imageId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ImageId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("instanceId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.InstanceId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("instanceLifecycle", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.InstanceLifecycle = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("instanceType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.InstanceType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("kernelId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.KernelId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("keyName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.KeyName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("launchTime", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.LaunchTime = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("monitoring", targetDepth))
{
var unmarshaller = MonitoringUnmarshaller.Instance;
unmarshalledObject.Monitoring = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("networkInterfaceSet/item", targetDepth))
{
var unmarshaller = InstanceNetworkInterfaceUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.NetworkInterfaces.Add(item);
continue;
}
if (context.TestExpression("placement", targetDepth))
{
var unmarshaller = PlacementUnmarshaller.Instance;
unmarshalledObject.Placement = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("platform", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Platform = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("privateDnsName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.PrivateDnsName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("privateIpAddress", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.PrivateIpAddress = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("productCodes/item", targetDepth))
{
var unmarshaller = ProductCodeUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.ProductCodes.Add(item);
continue;
}
if (context.TestExpression("dnsName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.PublicDnsName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ipAddress", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.PublicIpAddress = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ramdiskId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.RamdiskId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("rootDeviceName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.RootDeviceName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("rootDeviceType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.RootDeviceType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("groupSet/item", targetDepth))
{
var unmarshaller = GroupIdentifierUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.SecurityGroups.Add(item);
continue;
}
if (context.TestExpression("sourceDestCheck", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.SourceDestCheck = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("spotInstanceRequestId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.SpotInstanceRequestId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("sriovNetSupport", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.SriovNetSupport = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("instanceState", targetDepth))
{
var unmarshaller = InstanceStateUnmarshaller.Instance;
unmarshalledObject.State = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("stateReason", targetDepth))
{
var unmarshaller = StateReasonUnmarshaller.Instance;
unmarshalledObject.StateReason = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("reason", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.StateTransitionReason = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("subnetId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.SubnetId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("tagSet/item", targetDepth))
{
var unmarshaller = TagUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.Tags.Add(item);
continue;
}
if (context.TestExpression("virtualizationType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.VirtualizationType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("vpcId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.VpcId = unmarshaller.Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return unmarshalledObject;
}
}
return unmarshalledObject;
}
public Instance Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static InstanceUnmarshaller _instance = new InstanceUnmarshaller();
public static InstanceUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Orleans;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
using Orleans.Hosting;
using Orleans.Serialization;
namespace UnitTests.General
{
[TestCategory("BVT"), TestCategory("GrainCallFilter")]
public class GrainCallFilterTests : OrleansTestingBase, IClassFixture<GrainCallFilterTests.Fixture>
{
public class Fixture : BaseTestClusterFixture
{
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
builder.AddSiloBuilderConfigurator<SiloInvokerTestSiloBuilderConfigurator>();
builder.AddClientBuilderConfigurator<ClientConfigurator>();
}
private class SiloInvokerTestSiloBuilderConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder
.AddIncomingGrainCallFilter(context =>
{
if (string.Equals(context.InterfaceMethod.Name, nameof(IGrainCallFilterTestGrain.GetRequestContext)))
{
if (RequestContext.Get(GrainCallFilterTestConstants.Key) != null) throw new InvalidOperationException();
RequestContext.Set(GrainCallFilterTestConstants.Key, "1");
}
return context.Invoke();
})
.AddIncomingGrainCallFilter<GrainCallFilterWithDependencies>()
.AddOutgoingGrainCallFilter(async ctx =>
{
if (ctx.InterfaceMethod?.Name == "Echo")
{
// Concatenate the input to itself.
var orig = (string) ctx.Arguments[0];
ctx.Arguments[0] = orig + orig;
}
await ctx.Invoke();
})
.AddSimpleMessageStreamProvider("SMSProvider")
.AddMemoryGrainStorageAsDefault()
.AddMemoryGrainStorage("PubSubStore");
}
}
private class ClientConfigurator : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.AddOutgoingGrainCallFilter(async ctx =>
{
if (ctx.InterfaceMethod?.DeclaringType == typeof(IOutgoingMethodInterceptionGrain))
{
ctx.Arguments[1] = ((string) ctx.Arguments[1]).ToUpperInvariant();
}
await ctx.Invoke();
if (ctx.InterfaceMethod?.DeclaringType == typeof(IOutgoingMethodInterceptionGrain))
{
var result = (Dictionary<string, object>) ctx.Result;
result["orig"] = result["result"];
result["result"] = "intercepted!";
}
})
.AddSimpleMessageStreamProvider("SMSProvider");
}
}
}
[SuppressMessage("ReSharper", "NotAccessedField.Local")]
public class GrainCallFilterWithDependencies : IIncomingGrainCallFilter
{
private readonly SerializationManager serializationManager;
private readonly Silo silo;
private readonly IGrainFactory grainFactory;
public GrainCallFilterWithDependencies(SerializationManager serializationManager, Silo silo, IGrainFactory grainFactory)
{
this.serializationManager = serializationManager;
this.silo = silo;
this.grainFactory = grainFactory;
}
public Task Invoke(IIncomingGrainCallContext context)
{
if (string.Equals(context.ImplementationMethod.Name, nameof(IGrainCallFilterTestGrain.GetRequestContext)))
{
if (RequestContext.Get(GrainCallFilterTestConstants.Key) is string value)
{
RequestContext.Set(GrainCallFilterTestConstants.Key, value + '2');
}
}
return context.Invoke();
}
}
private readonly Fixture fixture;
public GrainCallFilterTests(Fixture fixture)
{
this.fixture = fixture;
}
/// <summary>
/// Ensures that grain call filters are invoked around method calls in the correct order.
/// </summary>
/// <returns>A <see cref="Task"/> representing the work performed.</returns>
[Fact]
public async Task GrainCallFilter_Outgoing_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IOutgoingMethodInterceptionGrain>(random.Next());
var grain2 = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next());
// This grain method reads the context and returns it
var result = await grain.EchoViaOtherGrain(grain2, "ab");
// Original arg should have been:
// 1. Converted to upper case on the way out of the client: ab -> AB.
// 2. Doubled on the way out of grain1: AB -> ABAB.
// 3. Reversed on the wya in to grain2: ABAB -> BABA.
Assert.Equal("BABA", result["orig"] as string);
Assert.NotNull(result["result"]);
Assert.Equal("intercepted!", result["result"]);
}
/// <summary>
/// Ensures that grain call filters are invoked around method calls in the correct order.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_Order_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IGrainCallFilterTestGrain>(random.Next());
// This grain method reads the context and returns it
var context = await grain.GetRequestContext();
Assert.NotNull(context);
Assert.Equal("1234", context);
}
/// <summary>
/// Ensures that the invocation interceptor is invoked for stream subscribers.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_Stream_Test()
{
var streamProvider = this.fixture.Client.GetStreamProvider("SMSProvider");
var id = Guid.NewGuid();
var stream = streamProvider.GetStream<int>(id, "InterceptedStream");
var grain = this.fixture.GrainFactory.GetGrain<IStreamInterceptionGrain>(id);
// The intercepted grain should double the value passed to the stream.
const int testValue = 43;
await stream.OnNextAsync(testValue);
var actual = await grain.GetLastStreamValue();
Assert.Equal(testValue * 2, actual);
}
/// <summary>
/// Tests that some invalid usages of invoker interceptors are denied.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_InvalidOrder_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IGrainCallFilterTestGrain>(0);
var result = await grain.CallWithBadInterceptors(false, false, false);
Assert.Equal("I will not misbehave!", result);
await Assert.ThrowsAsync<InvalidOperationException>(() => grain.CallWithBadInterceptors(true, false, false));
await Assert.ThrowsAsync<InvalidOperationException>(() => grain.CallWithBadInterceptors(false, false, true));
await Assert.ThrowsAsync<InvalidOperationException>(() => grain.CallWithBadInterceptors(false, true, false));
}
/// <summary>
/// Tests filters on just the grain level.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_GrainLevel_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(0);
var result = await grain.One();
Assert.Equal("intercepted one with no args", result);
result = await grain.Echo("stao erom tae");
Assert.Equal("eat more oats", result);// Grain interceptors should receive the MethodInfo of the implementation, not the interface.
result = await grain.NotIntercepted();
Assert.Equal("not intercepted", result);
result = await grain.SayHello();
Assert.Equal("Hello", result);
}
/// <summary>
/// Tests filters on generic grains.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_GenericGrain_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IGenericMethodInterceptionGrain<int>>(0);
var result = await grain.GetInputAsString(679);
Assert.Contains("Hah!", result);
Assert.Contains("679", result);
result = await grain.SayHello();
Assert.Equal("Hello", result);
}
/// <summary>
/// Tests filters on grains which implement multiple of the same generic interface.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_ConstructedGenericInheritance_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<ITrickyMethodInterceptionGrain>(0);
var result = await grain.GetInputAsString("2014-12-19T14:32:50Z");
Assert.Contains("Hah!", result);
Assert.Contains("2014-12-19T14:32:50Z", result);
result = await grain.SayHello();
Assert.Equal("Hello", result);
var bestNumber = await grain.GetBestNumber();
Assert.Equal(38, bestNumber);
result = await grain.GetInputAsString(true);
Assert.Contains(true.ToString(CultureInfo.InvariantCulture), result);
}
/// <summary>
/// Tests that grain call filters can handle exceptions.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_ExceptionHandling_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next());
// This grain method throws, but the exception should be handled by one of the filters and converted
// into a specific message.
var result = await grain.Throw();
Assert.NotNull(result);
Assert.Equal("EXCEPTION! Oi!", result);
}
/// <summary>
/// Tests that grain call filters can throw exceptions.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_FilterThrows_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next());
var exception = await Assert.ThrowsAsync<MethodInterceptionGrain.MyDomainSpecificException>(() => grain.FilterThrows());
Assert.NotNull(exception);
Assert.Equal("Filter THROW!", exception.Message);
}
/// <summary>
/// Tests that if a grain call filter sets an incorrect result type for <see cref="Orleans.IGrainCallContext.Result"/>,
/// an exception is thrown on the caller.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_SetIncorrectResultType_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next());
// This grain method throws, but the exception should be handled by one of the filters and converted
// into a specific message.
await Assert.ThrowsAsync<InvalidCastException>(() => grain.IncorrectResultType());
}
}
}
| |
// MbUnit Test Framework
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// MbUnit HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Reflection;
namespace MbUnit.Framework
{
using MbUnit.Framework.Xml;
/// <summary>
/// Assertion class for Database related object.
/// </summary>
public sealed class DataAssert
{
/// <summary>
/// A private constructor disallows any instances of this object.
/// </summary>
private DataAssert()
{}
/// <summary>
/// Asserts that two <see cref="DataColumn"/> are equal.
/// </summary>
/// <param name="expected">Expected <see cref="DataColumn"/> instance.</param>
/// <param name="actual">Actual <see cref="DataColumn"/> instance.</param>
public static void AreEqual(DataColumn expected, DataColumn actual)
{
// null case, trivial comparaison
if (expected==null)
Assert.AreEqual(expected,actual);
// check same type
Assert.AreEqual(expected.GetType(), actual.GetType());
foreach(PropertyInfo pi in expected.GetType().GetProperties())
{
switch(pi.Name)
{
case "Container": continue;
case "Site" : continue;
}
Assert.AreValueEqual(pi, expected, actual);
}
}
/// <summary>
/// Asserts that two <see cref="DataRow"/> are equal.
/// </summary>
/// <param name="expected">Expected <see cref="DataRow"/> instance.</param>
/// <param name="actual">Actual <see cref="DataRow"/> instance.</param>
/// <remarks>
/// <para>
/// Insipired from this
/// <a href="http://dotnetjunkies.com/WebLog/darrell.norton/archive/2003/06/05/213.aspx">
/// blog entry.</a>.
/// </para>
/// </remarks>
public static void AreEqual(DataRow expected, DataRow actual)
{
// if expected is null, trivial check
if (expected==null)
Assert.AreEqual(expected,actual);
// check number of columns
Assert.AreEqual(expected.Table.Columns.Count,
actual.Table.Columns.Count,
"DataRow column count not the same"
);
for( int currentIndex = 0; currentIndex < expected.ItemArray.Length; currentIndex++ )
{
// Check all columns except autoincrement columns
if( expected.Table.Columns[currentIndex].AutoIncrement == false )
{
Object ep = expected[currentIndex];
Object ac = actual[currentIndex];
if (ep is DateTime)
{
AreEqual((DateTime)ep, (DateTime)ac);
}
else
{
// check values are equal
Assert.AreEqual(
ep,
ac,
"DataRow comparison failed on column {0}",
expected.Table.Columns[currentIndex].ToString()
);
}
}
}
}
/// <summary>
/// Asserts that two <see cref="DateTime"/> values are equal
/// </summary>
/// <param name="expected">The expected <see cref="DateTime"/>.</param>
/// <param name="actual">The actual <see cref="DateTime"/>.</param>
static public void AreEqual(DateTime expected, DateTime actual)
{
Assert.AreEqual(expected.Year, actual.Year);
Assert.AreEqual(expected.Month, actual.Month);
Assert.AreEqual(expected.Day, actual.Day);
Assert.AreEqual(expected.Hour, actual.Hour);
Assert.AreEqual(expected.Minute, actual.Minute);
Assert.AreEqual(expected.Second, actual.Second);
// Assert.AreEqual(expected.Millisecond, actual.Millisecond);
}
/// <summary>
/// Assert that two <see cref="DataSet"/> schemas are equal.
/// </summary>
/// <param name="expected">The expected <see cref="DataSet"/>.</param>
/// <param name="actual">The actual <see cref="DataSet"/>.</param>
public static void AreSchemasEqual(DataSet expected, DataSet actual)
{
if (expected==null)
{
Assert.AreEqual(expected,actual);
return;
}
string sex = getXmlSchema(expected);
string sact = getXmlSchema(actual);
XmlAssert.XmlEquals(sex,sact);
}
/// <summary>
/// Assert that two <see cref="DataSet"/> schemas and the data they contain are equal.
/// </summary>
/// <param name="expected">The expected <see cref="DataSet"/>.</param>
/// <param name="actual">The actual <see cref="DataSet"/>.</param>
public static void AreEqual(DataSet expected, DataSet actual)
{
if (expected==null)
{
Assert.AreEqual(expected,actual);
return;
}
string sex = getXml(expected,true);
string sact = getXml(actual,true);
XmlAssert.XmlEquals(sex,sact);
}
/// <summary>
/// Assert that the data in two <see cref="DataSet"/>s are equal.
/// </summary>
/// <param name="expected">The expected <see cref="DataSet"/>.</param>
/// <param name="actual">The actual <see cref="DataSet"/>.</param>
public static void AreDataEqual(DataSet expected, DataSet actual)
{
if (expected==null)
{
Assert.AreEqual(expected,actual);
return;
}
string sex = getXml(expected,false);
string sact = getXml(actual,false);
XmlAssert.XmlEquals(sex,sact);
}
#region Private methods
private static string getXmlSchema(DataSet ds)
{
if (ds==null)
throw new ArgumentNullException("ds");
StringWriter sw = new StringWriter();
XmlTextWriter xm = new XmlTextWriter(sw);
xm.Formatting = Formatting.Indented;
ds.WriteXmlSchema(xm);
xm.Close();
return sw.ToString();
}
private static string getXml(DataSet ds, bool writeSchema)
{
if (ds==null)
throw new ArgumentNullException("ds");
StringWriter sw = new StringWriter();
XmlTextWriter xm = new XmlTextWriter(sw);
xm.Formatting = Formatting.Indented;
if (writeSchema)
ds.WriteXml(xm, XmlWriteMode.WriteSchema);
else
ds.WriteXml(xm, XmlWriteMode.IgnoreSchema);
xm.Close();
return sw.ToString();
}
#endregion
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Mono.Addins.Gui
{
internal partial class AddinInfoView
{
private global::Gtk.EventBox ebox;
private global::Gtk.VBox vbox6;
private global::Gtk.EventBox boxHeader;
private global::Gtk.HBox hbox2;
private global::Gtk.Image imageHeader;
private global::Gtk.Label labelHeader;
private global::Gtk.VBox vbox3;
private global::Gtk.HBox headerBox;
private global::Gtk.HBox boxTitle;
private global::Gtk.VBox vbox4;
private global::Gtk.Label labelName;
private global::Gtk.Label labelVersion;
private global::Gtk.ScrolledWindow scrolledwindow;
private global::Gtk.EventBox ebox2;
private global::Gtk.VBox vboxDesc;
private global::Gtk.Label labelDesc;
private global::Gtk.HBox hbox3;
private global::Gtk.Button urlButton;
private global::Gtk.EventBox eboxButs;
private global::Gtk.HBox hbox1;
private global::Gtk.Button btnInstall;
private global::Gtk.Button btnUpdate;
private global::Gtk.Button btnDisable;
private global::Gtk.Button btnUninstall;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget Mono.Addins.Gui.AddinInfoView
global::Stetic.BinContainer.Attach (this);
this.Name = "Mono.Addins.Gui.AddinInfoView";
// Container child Mono.Addins.Gui.AddinInfoView.Gtk.Container+ContainerChild
this.ebox = new global::Gtk.EventBox ();
this.ebox.Name = "ebox";
// Container child ebox.Gtk.Container+ContainerChild
this.vbox6 = new global::Gtk.VBox ();
this.vbox6.Name = "vbox6";
// Container child vbox6.Gtk.Box+BoxChild
this.boxHeader = new global::Gtk.EventBox ();
this.boxHeader.Name = "boxHeader";
// Container child boxHeader.Gtk.Container+ContainerChild
this.hbox2 = new global::Gtk.HBox ();
this.hbox2.Name = "hbox2";
this.hbox2.Spacing = 6;
// Container child hbox2.Gtk.Box+BoxChild
this.imageHeader = new global::Gtk.Image ();
this.imageHeader.Name = "imageHeader";
this.imageHeader.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-dialog-warning", global::Gtk.IconSize.Menu);
this.hbox2.Add (this.imageHeader);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.imageHeader]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child hbox2.Gtk.Box+BoxChild
this.labelHeader = new global::Gtk.Label ();
this.labelHeader.WidthRequest = 250;
this.labelHeader.Name = "labelHeader";
this.labelHeader.Xalign = 0F;
this.labelHeader.LabelProp = global::Mono.Unix.Catalog.GetString ("label1");
this.labelHeader.Wrap = true;
this.hbox2.Add (this.labelHeader);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.labelHeader]));
w2.Position = 1;
w2.Expand = false;
w2.Fill = false;
this.boxHeader.Add (this.hbox2);
this.vbox6.Add (this.boxHeader);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this.boxHeader]));
w4.Position = 0;
w4.Expand = false;
w4.Fill = false;
// Container child vbox6.Gtk.Box+BoxChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
this.vbox3.BorderWidth = ((uint)(12));
// Container child vbox3.Gtk.Box+BoxChild
this.headerBox = new global::Gtk.HBox ();
this.headerBox.Name = "headerBox";
this.headerBox.Spacing = 6;
// Container child headerBox.Gtk.Box+BoxChild
this.boxTitle = new global::Gtk.HBox ();
this.boxTitle.Name = "boxTitle";
this.boxTitle.Spacing = 6;
// Container child boxTitle.Gtk.Box+BoxChild
this.vbox4 = new global::Gtk.VBox ();
this.vbox4.Name = "vbox4";
this.vbox4.Spacing = 3;
// Container child vbox4.Gtk.Box+BoxChild
this.labelName = new global::Gtk.Label ();
this.labelName.WidthRequest = 280;
this.labelName.Name = "labelName";
this.labelName.Xalign = 0F;
this.labelName.LabelProp = global::Mono.Unix.Catalog.GetString ("<b><big>Some Addin</big></b>");
this.labelName.UseMarkup = true;
this.labelName.Wrap = true;
this.vbox4.Add (this.labelName);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.labelName]));
w5.Position = 0;
w5.Expand = false;
w5.Fill = false;
// Container child vbox4.Gtk.Box+BoxChild
this.labelVersion = new global::Gtk.Label ();
this.labelVersion.WidthRequest = 280;
this.labelVersion.Name = "labelVersion";
this.labelVersion.Xalign = 0F;
this.labelVersion.LabelProp = global::Mono.Unix.Catalog.GetString ("Version 2.6");
this.labelVersion.Wrap = true;
this.vbox4.Add (this.labelVersion);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.labelVersion]));
w6.Position = 1;
w6.Expand = false;
w6.Fill = false;
this.boxTitle.Add (this.vbox4);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.boxTitle [this.vbox4]));
w7.Position = 0;
w7.Expand = false;
w7.Fill = false;
this.headerBox.Add (this.boxTitle);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.headerBox [this.boxTitle]));
w8.Position = 0;
this.vbox3.Add (this.headerBox);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.headerBox]));
w9.Position = 0;
w9.Expand = false;
w9.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.scrolledwindow = new global::Gtk.ScrolledWindow ();
this.scrolledwindow.CanFocus = true;
this.scrolledwindow.Name = "scrolledwindow";
this.scrolledwindow.HscrollbarPolicy = ((global::Gtk.PolicyType)(2));
// Container child scrolledwindow.Gtk.Container+ContainerChild
global::Gtk.Viewport w10 = new global::Gtk.Viewport ();
w10.ShadowType = ((global::Gtk.ShadowType)(0));
// Container child GtkViewport.Gtk.Container+ContainerChild
this.ebox2 = new global::Gtk.EventBox ();
this.ebox2.Name = "ebox2";
// Container child ebox2.Gtk.Container+ContainerChild
this.vboxDesc = new global::Gtk.VBox ();
this.vboxDesc.Name = "vboxDesc";
this.vboxDesc.Spacing = 6;
// Container child vboxDesc.Gtk.Box+BoxChild
this.labelDesc = new global::Gtk.Label ();
this.labelDesc.WidthRequest = 250;
this.labelDesc.Name = "labelDesc";
this.labelDesc.Xalign = 0F;
this.labelDesc.LabelProp = global::Mono.Unix.Catalog.GetString ("Long description of the add-in. Long description of the add-in. Long description of the add-in. Long description of the add-in. Long description of the add-in. Long description of the add-in. ");
this.labelDesc.Wrap = true;
this.vboxDesc.Add (this.labelDesc);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.vboxDesc [this.labelDesc]));
w11.Position = 0;
w11.Expand = false;
w11.Fill = false;
// Container child vboxDesc.Gtk.Box+BoxChild
this.hbox3 = new global::Gtk.HBox ();
this.hbox3.Name = "hbox3";
this.hbox3.Spacing = 6;
// Container child hbox3.Gtk.Box+BoxChild
this.urlButton = new global::Gtk.Button ();
this.urlButton.CanFocus = true;
this.urlButton.Name = "urlButton";
this.urlButton.UseUnderline = true;
this.urlButton.Relief = ((global::Gtk.ReliefStyle)(2));
this.urlButton.Label = global::Mono.Unix.Catalog.GetString ("More information");
global::Gtk.Image w12 = new global::Gtk.Image ();
w12.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("web.png");
this.urlButton.Image = w12;
this.hbox3.Add (this.urlButton);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.urlButton]));
w13.Position = 0;
w13.Expand = false;
w13.Fill = false;
this.vboxDesc.Add (this.hbox3);
global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.vboxDesc [this.hbox3]));
w14.PackType = ((global::Gtk.PackType)(1));
w14.Position = 2;
w14.Expand = false;
w14.Fill = false;
this.ebox2.Add (this.vboxDesc);
w10.Add (this.ebox2);
this.scrolledwindow.Add (w10);
this.vbox3.Add (this.scrolledwindow);
global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.scrolledwindow]));
w18.Position = 1;
this.vbox6.Add (this.vbox3);
global::Gtk.Box.BoxChild w19 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this.vbox3]));
w19.Position = 1;
// Container child vbox6.Gtk.Box+BoxChild
this.eboxButs = new global::Gtk.EventBox ();
this.eboxButs.Name = "eboxButs";
// Container child eboxButs.Gtk.Container+ContainerChild
this.hbox1 = new global::Gtk.HBox ();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
// Container child hbox1.Gtk.Box+BoxChild
this.btnInstall = new global::Gtk.Button ();
this.btnInstall.CanFocus = true;
this.btnInstall.Name = "btnInstall";
this.btnInstall.UseUnderline = true;
this.btnInstall.Label = global::Mono.Unix.Catalog.GetString ("Install...");
global::Gtk.Image w20 = new global::Gtk.Image ();
w20.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("download.png");
this.btnInstall.Image = w20;
this.hbox1.Add (this.btnInstall);
global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.btnInstall]));
w21.Position = 0;
w21.Expand = false;
w21.Fill = false;
// Container child hbox1.Gtk.Box+BoxChild
this.btnUpdate = new global::Gtk.Button ();
this.btnUpdate.CanFocus = true;
this.btnUpdate.Name = "btnUpdate";
this.btnUpdate.UseUnderline = true;
this.btnUpdate.Label = global::Mono.Unix.Catalog.GetString ("Update");
global::Gtk.Image w22 = new global::Gtk.Image ();
w22.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("download.png");
this.btnUpdate.Image = w22;
this.hbox1.Add (this.btnUpdate);
global::Gtk.Box.BoxChild w23 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.btnUpdate]));
w23.Position = 1;
w23.Expand = false;
w23.Fill = false;
// Container child hbox1.Gtk.Box+BoxChild
this.btnDisable = new global::Gtk.Button ();
this.btnDisable.CanFocus = true;
this.btnDisable.Name = "btnDisable";
this.btnDisable.UseUnderline = true;
this.btnDisable.Label = global::Mono.Unix.Catalog.GetString ("Disable");
this.hbox1.Add (this.btnDisable);
global::Gtk.Box.BoxChild w24 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.btnDisable]));
w24.Position = 2;
w24.Expand = false;
w24.Fill = false;
// Container child hbox1.Gtk.Box+BoxChild
this.btnUninstall = new global::Gtk.Button ();
this.btnUninstall.CanFocus = true;
this.btnUninstall.Name = "btnUninstall";
this.btnUninstall.UseUnderline = true;
this.btnUninstall.Label = global::Mono.Unix.Catalog.GetString ("_Uninstall...");
this.hbox1.Add (this.btnUninstall);
global::Gtk.Box.BoxChild w25 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.btnUninstall]));
w25.Position = 3;
w25.Expand = false;
w25.Fill = false;
this.eboxButs.Add (this.hbox1);
this.vbox6.Add (this.eboxButs);
global::Gtk.Box.BoxChild w27 = ((global::Gtk.Box.BoxChild)(this.vbox6 [this.eboxButs]));
w27.Position = 2;
w27.Expand = false;
w27.Fill = false;
this.ebox.Add (this.vbox6);
this.Add (this.ebox);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.Hide ();
this.urlButton.Clicked += new global::System.EventHandler (this.OnUrlButtonClicked);
this.btnInstall.Clicked += new global::System.EventHandler (this.OnBtnInstallClicked);
this.btnUpdate.Clicked += new global::System.EventHandler (this.OnBtnUpdateClicked);
this.btnDisable.Clicked += new global::System.EventHandler (this.OnBtnDisableClicked);
this.btnUninstall.Clicked += new global::System.EventHandler (this.OnBtnUninstallClicked);
}
}
}
| |
//originally from Matthew Adams, who was a thorough blog on these things at http://mwadams.spaces.live.com/blog/cns!652A0FB566F633D5!133.entry
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using Palaso.Progress;
using Timer=System.Windows.Forms.Timer;
namespace Palaso.UI.WindowsForms.Progress
{
/// <summary>
/// Provides a progress dialog similar to the one shown by Windows
/// </summary>
public class ProgressDialog : Form
{
public delegate void ProgressCallback(int progress);
private Label _statusLabel;
private ProgressBar _progressBar;
private Label _progressLabel;
private Button _cancelButton;
private Timer _showWindowIfTakingLongTimeTimer;
private Timer _progressTimer;
private bool _isClosing;
private Label _overviewLabel;
private DateTime _startTime;
private IContainer components;
private BackgroundWorker _backgroundWorker;
// private ProgressState _lastHeardFromProgressState;
private ProgressState _progressState;
private TableLayoutPanel tableLayout;
private bool _workerStarted;
private bool _appUsingWaitCursor;
/// <summary>
/// Standard constructor
/// </summary>
public ProgressDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
_statusLabel.BackColor = Color.Transparent;
_progressLabel.BackColor = Color.Transparent;
_overviewLabel.BackColor = Color.Transparent;
_startTime = default(DateTime);
Text = Palaso.Reporting.UsageReporter.AppNameToUseInDialogs;
_statusLabel.Font = SystemFonts.MessageBoxFont;
_progressLabel.Font = SystemFonts.MessageBoxFont;
_overviewLabel.Font = SystemFonts.MessageBoxFont;
_statusLabel.Text = string.Empty;
_progressLabel.Text = string.Empty;
_overviewLabel.Text = string.Empty;
_cancelButton.MouseEnter += delegate
{
_appUsingWaitCursor = Application.UseWaitCursor;
_cancelButton.Cursor = Cursor = Cursors.Arrow;
Application.UseWaitCursor = false;
};
_cancelButton.MouseLeave += delegate
{
Application.UseWaitCursor = _appUsingWaitCursor;
};
//avoids the client getting null errors if he checks this when there
//has yet to be a callback from the worker
// _lastHeardFromProgressState = new NullProgressState();
}
private void HandleTableLayoutSizeChanged(object sender, EventArgs e)
{
if (!IsHandleCreated)
CreateHandle();
var desiredHeight = tableLayout.Height + Padding.Top + Padding.Bottom + (Height - ClientSize.Height);
var scn = Screen.FromControl(this);
Height = Math.Min(desiredHeight, scn.WorkingArea.Height - 20);
AutoScroll = (desiredHeight > scn.WorkingArea.Height - 20);
}
/// <summary>
/// Get / set the time in ms to delay
/// before showing the dialog
/// </summary>
private/*doesn't work yet public*/ int DelayShowInterval
{
get
{
return _showWindowIfTakingLongTimeTimer.Interval;
}
set
{
_showWindowIfTakingLongTimeTimer.Interval = value;
}
}
/// <summary>
/// Get / set the text to display in the first status panel
/// </summary>
public string StatusText
{
get
{
return _statusLabel.Text;
}
set
{
_statusLabel.Text = value;
}
}
/// <summary>
/// Description of why this dialog is even showing
/// </summary>
public string Overview
{
get
{
return _overviewLabel.Text;
}
set
{
_overviewLabel.Text = value;
}
}
/// <summary>
/// Get / set the minimum range of the progress bar
/// </summary>
public int ProgressRangeMinimum
{
get
{
return _progressBar.Minimum;
}
set
{
if (_backgroundWorker == null)
{
_progressBar.Minimum = value;
}
}
}
/// <summary>
/// Get / set the maximum range of the progress bar
/// </summary>
public int ProgressRangeMaximum
{
get
{
return _progressBar.Maximum;
}
set
{
if (_backgroundWorker != null)
{
return;
}
if (InvokeRequired)
{
Invoke(new ProgressCallback(SetMaximumCrossThread), new object[] { value });
}
else
{
_progressBar.Maximum = value;
}
}
}
private void SetMaximumCrossThread(int amount)
{
ProgressRangeMaximum = amount;
}
/// <summary>
/// Get / set the current value of the progress bar
/// </summary>
public int Progress
{
get
{
return _progressBar.Value;
}
set
{
/* these were causing weird, hard to debug (because of threads)
* failures. The debugger would reprot that value == max, so why fail?
* Debug.Assert(value <= _progressBar.Maximum);
*/
Debug.WriteLineIf(value > _progressBar.Maximum,
"***Warning progres was " + value + " but max is " + _progressBar.Maximum);
Debug.Assert(value >= _progressBar.Minimum);
if (value > _progressBar.Maximum)
{
_progressBar.Maximum = value;//not worth crashing over in Release build
}
if (value < _progressBar.Minimum)
{
return; //not worth crashing over in Release build
}
_progressBar.Value = value;
}
}
/// <summary>
/// Get/set a boolean which determines whether the form
/// will show a cancel option (true) or not (false)
/// </summary>
public bool CanCancel
{
get
{
return _cancelButton.Enabled;
}
set
{
_cancelButton.Enabled = value;
}
}
/// <summary>
/// If this is set before showing, the dialog will run the worker and respond
/// to its events
/// </summary>
public BackgroundWorker BackgroundWorker
{
get
{
return _backgroundWorker;
}
set
{
_backgroundWorker = value;
_progressBar.Minimum = 0;
_progressBar.Maximum = 100;
}
}
public ProgressState ProgressStateResult
{
get
{
return _progressState;// return _lastHeardFromProgressState;
}
}
/// <summary>
/// Gets or sets the manner in which progress should be indicated on the progress bar.
/// </summary>
public ProgressBarStyle BarStyle { get { return _progressBar.Style; } set { _progressBar.Style = value; } }
/// <summary>
/// Optional; one will be created (of some class or subclass) if you don't set it.
/// E.g. dlg.ProgressState = new BackgroundWorkerState(dlg.BackgroundWorker);
/// Also, you can use the getter to gain access to the progressstate, in order to add arguments
/// which the worker method can get at.
/// </summary>
public ProgressState ProgressState
{
get
{
if(_progressState ==null)
{
if(_backgroundWorker == null)
{
throw new ArgumentException("You must set BackgroundWorker before accessing this property.");
}
ProgressState = new BackgroundWorkerState(_backgroundWorker);
}
return _progressState;
}
set
{
if (_progressState!=null)
{
CancelRequested -= _progressState.CancelRequested;
}
_progressState = value;
CancelRequested += _progressState.CancelRequested;
_progressState.TotalNumberOfStepsChanged += OnTotalNumberOfStepsChanged;
}
}
void OnBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//BackgroundWorkerState progressState = e.Result as ProgressState;
if(e.Cancelled )
{
DialogResult = DialogResult.Cancel;
//_progressState.State = ProgressState.StateValue.Finished;
}
//NB: I don't know how to actually let the BW know there was an error
//else if (e.Error != null ||
else if (ProgressStateResult != null && (ProgressStateResult.State == ProgressState.StateValue.StoppedWithError
|| ProgressStateResult.ExceptionThatWasEncountered != null))
{
//this dialog really can't know whether this was an unexpected exception or not
//so don't do this: Reporting.ErrorReporter.ReportException(ProgressStateResult.ExceptionThatWasEncountered, this, false);
DialogResult = DialogResult.Abort;//not really matching semantics
// _progressState.State = ProgressState.StateValue.StoppedWithError;
}
else
{
DialogResult = DialogResult.OK;
// _progressState.State = ProgressState.StateValue.Finished;
}
_isClosing = true;
Close();
}
void OnBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ProgressState state = e.UserState as ProgressState;
if (state != null)
{
// _lastHeardFromProgressState = state;
StatusText = state.StatusLabel;
}
if (state == null
|| state is BackgroundWorkerState)
{
Progress = e.ProgressPercentage;
}
else
{
ProgressRangeMaximum = state.TotalNumberOfSteps;
Progress = state.NumberOfStepsCompleted;
}
}
/// <summary>
/// Show the control, but honor the
/// <see cref="DelayShowInterval"/>.
/// </summary>
private/*doesn't work yet public*/ void DelayShow()
{
// This creates the control, but doesn't
// show it; you can't use CreateControl()
// here, because it will return because
// the control is not visible
CreateHandle();
}
//************
//the problem is that our worker reports progress, and we die (only in some circumstance not nailed-down yet)
//because of a begininvoke with no window yet. Sometimes, we don't get the callback to
//the very important OnBackgroundWorker_RunWorkerCompleted
private/*doesn't work yet public*/ void ShowDialogIfTakesLongTime()
{
DelayShow();
OnStartWorker(this, null);
while((_progressState.State == ProgressState.StateValue.NotStarted
|| _progressState.State == ProgressState.StateValue.Busy) && !this.Visible)
{
Application.DoEvents();
}
}
/// <summary>
/// Close the dialog, ignoring cancel status
/// </summary>
public void ForceClose()
{
_isClosing = true;
Close();
}
/// <summary>
/// Raised when the cancel button is clicked
/// </summary>
public event EventHandler CancelRequested;
/// <summary>
/// Raises the cancelled event
/// </summary>
/// <param name="e">Event data</param>
protected virtual void OnCancelled( EventArgs e )
{
EventHandler cancelled = CancelRequested;
if( cancelled != null )
{
cancelled( this, e );
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (_showWindowIfTakingLongTimeTimer != null)
{
_showWindowIfTakingLongTimeTimer.Stop();
}
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Custom handle creation code
/// </summary>
/// <param name="e">Event data</param>
// protected override void OnHandleCreated(EventArgs e)
// {
// base.OnHandleCreated (e);
// if( !_showOnce )
// {
// // First, we don't want this to happen again
// _showOnce = true;
// // Then, start the timer which will determine whether
// // we are going to show this again
// _showWindowIfTakingLongTimeTimer.Start();
// }
// }
/// <summary>
/// Custom close handler
/// </summary>
/// <param name="e">Event data</param>
// protected override void OnClosing(CancelEventArgs e)
// {
// Debug.WriteLine("Dialog:OnClosing");
// if (_showWindowIfTakingLongTimeTimer != null)
// {
// _showWindowIfTakingLongTimeTimer.Stop();
// }
//
// if( !_isClosing )
// {
// Debug.WriteLine("Warning: OnClosing called but _isClosing=false, attempting cancel click");
// e.Cancel = true;
// _cancelButton.PerformClick();
// }
// base.OnClosing( e );
// }
#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._statusLabel = new System.Windows.Forms.Label();
this._progressBar = new System.Windows.Forms.ProgressBar();
this._cancelButton = new System.Windows.Forms.Button();
this._progressLabel = new System.Windows.Forms.Label();
this._showWindowIfTakingLongTimeTimer = new System.Windows.Forms.Timer(this.components);
this._progressTimer = new System.Windows.Forms.Timer(this.components);
this._overviewLabel = new System.Windows.Forms.Label();
this.tableLayout = new System.Windows.Forms.TableLayoutPanel();
this.tableLayout.SuspendLayout();
this.SuspendLayout();
//
// _statusLabel
//
this._statusLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._statusLabel.AutoSize = true;
this._statusLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this.tableLayout.SetColumnSpan(this._statusLabel, 2);
this._statusLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._statusLabel.Location = new System.Drawing.Point(0, 35);
this._statusLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 5);
this._statusLabel.Name = "_statusLabel";
this._statusLabel.Size = new System.Drawing.Size(355, 15);
this._statusLabel.TabIndex = 12;
this._statusLabel.Text = "#";
this._statusLabel.UseMnemonic = false;
//
// _progressBar
//
this._progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayout.SetColumnSpan(this._progressBar, 2);
this._progressBar.Location = new System.Drawing.Point(0, 55);
this._progressBar.Margin = new System.Windows.Forms.Padding(0, 0, 0, 12);
this._progressBar.Name = "_progressBar";
this._progressBar.Size = new System.Drawing.Size(355, 18);
this._progressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
this._progressBar.TabIndex = 11;
this._progressBar.Value = 1;
//
// _cancelButton
//
this._cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this._cancelButton.AutoSize = true;
this._cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this._cancelButton.Location = new System.Drawing.Point(280, 85);
this._cancelButton.Margin = new System.Windows.Forms.Padding(8, 0, 0, 0);
this._cancelButton.Name = "_cancelButton";
this._cancelButton.Size = new System.Drawing.Size(75, 23);
this._cancelButton.TabIndex = 10;
this._cancelButton.Text = "&Cancel";
this._cancelButton.Click += new System.EventHandler(this.OnCancelButton_Click);
//
// _progressLabel
//
this._progressLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._progressLabel.AutoEllipsis = true;
this._progressLabel.AutoSize = true;
this._progressLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
this._progressLabel.Location = new System.Drawing.Point(0, 90);
this._progressLabel.Margin = new System.Windows.Forms.Padding(0, 5, 0, 0);
this._progressLabel.Name = "_progressLabel";
this._progressLabel.Size = new System.Drawing.Size(272, 13);
this._progressLabel.TabIndex = 9;
this._progressLabel.Text = "#";
this._progressLabel.UseMnemonic = false;
//
// _showWindowIfTakingLongTimeTimer
//
this._showWindowIfTakingLongTimeTimer.Interval = 2000;
this._showWindowIfTakingLongTimeTimer.Tick += new System.EventHandler(this.OnTakingLongTimeTimerClick);
//
// _progressTimer
//
this._progressTimer.Enabled = true;
this._progressTimer.Interval = 1000;
this._progressTimer.Tick += new System.EventHandler(this.progressTimer_Tick);
//
// _overviewLabel
//
this._overviewLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this._overviewLabel.AutoSize = true;
this._overviewLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.tableLayout.SetColumnSpan(this._overviewLabel, 2);
this._overviewLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this._overviewLabel.Location = new System.Drawing.Point(0, 0);
this._overviewLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 20);
this._overviewLabel.Name = "_overviewLabel";
this._overviewLabel.Size = new System.Drawing.Size(355, 15);
this._overviewLabel.TabIndex = 8;
this._overviewLabel.Text = "#";
this._overviewLabel.UseMnemonic = false;
//
// tableLayout
//
this.tableLayout.AutoSize = true;
this.tableLayout.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayout.BackColor = System.Drawing.Color.Transparent;
this.tableLayout.ColumnCount = 2;
this.tableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayout.Controls.Add(this._cancelButton, 1, 3);
this.tableLayout.Controls.Add(this._overviewLabel, 0, 0);
this.tableLayout.Controls.Add(this._progressLabel, 0, 3);
this.tableLayout.Controls.Add(this._progressBar, 0, 2);
this.tableLayout.Controls.Add(this._statusLabel, 0, 1);
this.tableLayout.Dock = System.Windows.Forms.DockStyle.Top;
this.tableLayout.Location = new System.Drawing.Point(12, 12);
this.tableLayout.Name = "tableLayout";
this.tableLayout.RowCount = 4;
this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayout.Size = new System.Drawing.Size(355, 108);
this.tableLayout.TabIndex = 13;
this.tableLayout.SizeChanged += new System.EventHandler(this.HandleTableLayoutSizeChanged);
//
// ProgressDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.AutoSize = true;
this.ClientSize = new System.Drawing.Size(379, 150);
this.ControlBox = false;
this.Controls.Add(this.tableLayout);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ProgressDialog";
this.Padding = new System.Windows.Forms.Padding(12);
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Palaso";
this.Load += new System.EventHandler(this.ProgressDialog_Load);
this.Shown += new System.EventHandler(this.ProgressDialog_Shown);
this.tableLayout.ResumeLayout(false);
this.tableLayout.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void OnTakingLongTimeTimerClick(object sender, EventArgs e)
{
// Show the window now the timer has elapsed, and stop the timer
_showWindowIfTakingLongTimeTimer.Stop();
if (!this.Visible)
{
Show();
}
}
private void OnCancelButton_Click(object sender, EventArgs e)
{
_showWindowIfTakingLongTimeTimer.Stop();
if(_isClosing)
return;
Debug.WriteLine("Dialog:OnCancelButton_Click");
// Prevent further cancellation
_cancelButton.Enabled = false;
_progressTimer.Stop();
_progressLabel.Text = "Canceling...";
// Tell people we're canceling
OnCancelled( e );
if (_backgroundWorker != null && _backgroundWorker.WorkerSupportsCancellation)
{
_backgroundWorker.CancelAsync();
}
}
private void progressTimer_Tick(object sender, EventArgs e)
{
int range = _progressBar.Maximum - _progressBar.Minimum;
if( range <= 0 )
{
return;
}
if( _progressBar.Value <= 0 )
{
return;
}
if (_startTime != default(DateTime))
{
TimeSpan elapsed = DateTime.Now - _startTime;
double estimatedSeconds = (elapsed.TotalSeconds * range) / _progressBar.Value;
TimeSpan estimatedToGo = new TimeSpan(0, 0, 0, (int)(estimatedSeconds - elapsed.TotalSeconds), 0);
//_progressLabel.Text = String.Format(
// System.Globalization.CultureInfo.CurrentUICulture,
// "Elapsed: {0} Remaining: {1}",
// GetStringFor(elapsed),
// GetStringFor(estimatedToGo));
_progressLabel.Text = String.Format(
CultureInfo.CurrentUICulture,
"{0}",
//GetStringFor(elapsed),
GetStringFor(estimatedToGo));
}
}
private static string GetStringFor( TimeSpan span )
{
if( span.TotalDays > 1 )
{
return string.Format(CultureInfo.CurrentUICulture, "{0} day {1} hour", span.Days, span.Hours);
}
else if( span.TotalHours > 1 )
{
return string.Format(CultureInfo.CurrentUICulture, "{0} hour {1} minutes", span.Hours, span.Minutes);
}
else if( span.TotalMinutes > 1 )
{
return string.Format(CultureInfo.CurrentUICulture, "{0} minutes {1} seconds", span.Minutes, span.Seconds);
}
return string.Format( CultureInfo.CurrentUICulture, "{0} seconds", span.Seconds );
}
public void OnNumberOfStepsCompletedChanged(object sender, EventArgs e)
{
Progress = ((ProgressState) sender).NumberOfStepsCompleted;
//in case there is no event pump showing us (mono-threaded)
progressTimer_Tick(this, null);
Refresh();
}
public void OnTotalNumberOfStepsChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new ProgressCallback(UpdateTotal), new object[] { ((ProgressState)sender).TotalNumberOfSteps });
}
else
{
UpdateTotal(((ProgressState) sender).TotalNumberOfSteps);
}
}
private void UpdateTotal(int steps)
{
_startTime = DateTime.Now;
ProgressRangeMaximum = steps;
Refresh();
}
public void OnStatusLabelChanged(object sender, EventArgs e)
{
StatusText = ((ProgressState)sender).StatusLabel;
Refresh();
}
private void OnStartWorker(object sender, EventArgs e)
{
_workerStarted = true;
Debug.WriteLine("Dialog:StartWorker");
if (_backgroundWorker != null)
{
//BW uses percentages (unless it's using our custom ProgressState in the UserState member)
ProgressRangeMinimum = 0;
ProgressRangeMaximum = 100;
//if the actual task can't take cancelling, the caller of this should set CanCancel to false;
_backgroundWorker.WorkerSupportsCancellation = CanCancel;
_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(OnBackgroundWorker_ProgressChanged);
_backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnBackgroundWorker_RunWorkerCompleted);
_backgroundWorker.RunWorkerAsync(ProgressState);
}
}
//this is here, in addition to the OnShown handler, because of a weird bug were a certain,
//completely unrelated test (which doesn't use this class at all) can cause tests using this to
//fail because the OnShown event is never fired.
//I don't know why the orginal code we copied this from was using onshown instead of onload,
//but it may have something to do with its "delay show" feature (which I couldn't get to work,
//but which would be a terrific thing to have)
private void ProgressDialog_Load(object sender, EventArgs e)
{
if(!_workerStarted)
{
OnStartWorker(this, null);
}
}
private void ProgressDialog_Shown(object sender, EventArgs e)
{
if(!_workerStarted)
{
OnStartWorker(this, null);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// Base class for all validation attributes.
/// <para>Override <see cref="IsValid(object, ValidationContext)" /> to implement validation logic.</para>
/// </summary>
/// <remarks>
/// The properties <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> are used to
/// provide
/// a localized error message, but they cannot be set if <see cref="ErrorMessage" /> is also used to provide a
/// non-localized
/// error message.
/// </remarks>
public abstract class ValidationAttribute : Attribute
{
#region Member Fields
private string _errorMessage;
private Func<string> _errorMessageResourceAccessor;
private string _errorMessageResourceName;
private Type _errorMessageResourceType;
private volatile bool _hasBaseIsValid;
private string _defaultErrorMessage;
#endregion
#region All Constructors
/// <summary>
/// Default constructor for any validation attribute.
/// </summary>
/// <remarks>
/// This constructor chooses a very generic validation error message.
/// Developers subclassing ValidationAttribute should use other constructors
/// or supply a better message.
/// </remarks>
protected ValidationAttribute()
: this(() => SR.ValidationAttribute_ValidationError)
{
}
/// <summary>
/// Constructor that accepts a fixed validation error message.
/// </summary>
/// <param name="errorMessage">A non-localized error message to use in <see cref="ErrorMessageString" />.</param>
protected ValidationAttribute(string errorMessage)
: this(() => errorMessage)
{
}
/// <summary>
/// Allows for providing a resource accessor function that will be used by the <see cref="ErrorMessageString" />
/// property to retrieve the error message. An example would be to have something like
/// CustomAttribute() : base( () => MyResources.MyErrorMessage ) {}.
/// </summary>
/// <param name="errorMessageAccessor">The <see cref="Func{T}" /> that will return an error message.</param>
protected ValidationAttribute(Func<string> errorMessageAccessor)
{
// If null, will later be exposed as lack of error message to be able to construct accessor
_errorMessageResourceAccessor = errorMessageAccessor;
}
#endregion
#region Internal Properties
/// <summary>
/// Gets or sets and the default error message string.
/// This message will be used if the user has not set <see cref="ErrorMessage"/>
/// or the <see cref="ErrorMessageResourceType"/> and <see cref="ErrorMessageResourceName"/> pair.
/// This property was added after the public contract for DataAnnotations was created.
/// It is internal to avoid changing the DataAnnotations contract.
/// </summary>
internal string DefaultErrorMessage
{
get
{
return _defaultErrorMessage;
}
set
{
_defaultErrorMessage = value;
_errorMessageResourceAccessor = null;
CustomErrorMessageSet = true;
}
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the localized error message string, coming either from <see cref="ErrorMessage" />, or from evaluating the
/// <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> pair.
/// </summary>
protected string ErrorMessageString
{
get
{
SetupResourceAccessor();
return _errorMessageResourceAccessor();
}
}
/// <summary>
/// A flag indicating whether a developer has customized the attribute's error message by setting any one of
/// ErrorMessage, ErrorMessageResourceName, ErrorMessageResourceType or DefaultErrorMessage.
/// </summary>
internal bool CustomErrorMessageSet { get; private set; }
/// <summary>
/// A flag indicating that the attribute requires a non-null
/// <see cref= System.ComponentModel.DataAnnotations.ValidationContext /> to perform validation.
/// Base class returns false. Override in child classes as appropriate.
/// </summary>
public virtual bool RequiresValidationContext
{
get { return false; }
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets and explicit error message string.
/// </summary>
/// <value>
/// This property is intended to be used for non-localizable error messages. Use
/// <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> for localizable error messages.
/// </value>
public string ErrorMessage
{
get
{
// If _errorMessage is not set, return the default. This is done to preserve
// behavior prior to the fix where ErrorMessage showed the non-null message to use.
return _errorMessage ?? _defaultErrorMessage;
}
set
{
_errorMessage = value;
_errorMessageResourceAccessor = null;
CustomErrorMessageSet = true;
// Explicitly setting ErrorMessage also sets DefaultErrorMessage if null.
// This prevents subsequent read of ErrorMessage from returning default.
if (value == null)
{
_defaultErrorMessage = null;
}
}
}
/// <summary>
/// Gets or sets the resource name (property name) to use as the key for lookups on the resource type.
/// </summary>
/// <value>
/// Use this property to set the name of the property within <see cref="ErrorMessageResourceType" />
/// that will provide a localized error message. Use <see cref="ErrorMessage" /> for non-localized error messages.
/// </value>
public string ErrorMessageResourceName
{
get { return _errorMessageResourceName; }
set
{
_errorMessageResourceName = value;
_errorMessageResourceAccessor = null;
CustomErrorMessageSet = true;
}
}
/// <summary>
/// Gets or sets the resource type to use for error message lookups.
/// </summary>
/// <value>
/// Use this property only in conjunction with <see cref="ErrorMessageResourceName" />. They are
/// used together to retrieve localized error messages at runtime.
/// <para>
/// Use <see cref="ErrorMessage" /> instead of this pair if error messages are not localized.
/// </para>
/// </value>
public Type ErrorMessageResourceType
{
get { return _errorMessageResourceType; }
set
{
_errorMessageResourceType = value;
_errorMessageResourceAccessor = null;
CustomErrorMessageSet = true;
}
}
#endregion
#region Private Methods
/// <summary>
/// Validates the configuration of this attribute and sets up the appropriate error string accessor.
/// This method bypasses all verification once the ResourceAccessor has been set.
/// </summary>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
private void SetupResourceAccessor()
{
if (_errorMessageResourceAccessor == null)
{
string localErrorMessage = ErrorMessage;
bool resourceNameSet = !string.IsNullOrEmpty(_errorMessageResourceName);
bool errorMessageSet = !string.IsNullOrEmpty(_errorMessage);
bool resourceTypeSet = _errorMessageResourceType != null;
bool defaultMessageSet = !string.IsNullOrEmpty(_defaultErrorMessage);
// The following combinations are illegal and throw InvalidOperationException:
// 1) Both ErrorMessage and ErrorMessageResourceName are set, or
// 2) None of ErrorMessage, ErrorMessageResourceName, and DefaultErrorMessage are set.
if ((resourceNameSet && errorMessageSet) || !(resourceNameSet || errorMessageSet || defaultMessageSet))
{
throw new InvalidOperationException(
SR.ValidationAttribute_Cannot_Set_ErrorMessage_And_Resource);
}
// Must set both or neither of ErrorMessageResourceType and ErrorMessageResourceName
if (resourceTypeSet != resourceNameSet)
{
throw new InvalidOperationException(
SR.ValidationAttribute_NeedBothResourceTypeAndResourceName);
}
// If set resource type (and we know resource name too), then go setup the accessor
if (resourceNameSet)
{
SetResourceAccessorByPropertyLookup();
}
else
{
// Here if not using resource type/name -- the accessor is just the error message string,
// which we know is not empty to have gotten this far.
_errorMessageResourceAccessor = delegate
{
// We captured error message to local in case it changes before accessor runs
return localErrorMessage;
};
}
}
}
private void SetResourceAccessorByPropertyLookup()
{
if (_errorMessageResourceType != null && !string.IsNullOrEmpty(_errorMessageResourceName))
{
var property = _errorMessageResourceType
.GetTypeInfo().GetDeclaredProperty(_errorMessageResourceName);
if (property != null && !ValidationAttributeStore.IsStatic(property))
{
property = null;
}
if (property != null)
{
var propertyGetter = property.GetMethod;
// We only support internal and public properties
if (propertyGetter == null || (!propertyGetter.IsAssembly && !propertyGetter.IsPublic))
{
// Set the property to null so the exception is thrown as if the property wasn't found
property = null;
}
}
if (property == null)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
SR.ValidationAttribute_ResourceTypeDoesNotHaveProperty,
_errorMessageResourceType.FullName,
_errorMessageResourceName));
}
if (property.PropertyType != typeof(string))
{
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
SR.ValidationAttribute_ResourcePropertyNotStringType,
property.Name,
_errorMessageResourceType.FullName));
}
_errorMessageResourceAccessor = delegate { return (string)property.GetValue(null, null); };
}
else
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
SR.ValidationAttribute_NeedBothResourceTypeAndResourceName));
}
}
#endregion
#region Protected & Public Methods
/// <summary>
/// Formats the error message to present to the user.
/// </summary>
/// <remarks>
/// The error message will be re-evaluated every time this function is called.
/// It applies the <paramref name="name" /> (for example, the name of a field) to the formated error message, resulting
/// in something like "The field 'name' has an incorrect value".
/// <para>
/// Derived classes can override this method to customize how errors are generated.
/// </para>
/// <para>
/// The base class implementation will use <see cref="ErrorMessageString" /> to obtain a localized
/// error message from properties within the current attribute. If those have not been set, a generic
/// error message will be provided.
/// </para>
/// </remarks>
/// <param name="name">The user-visible name to include in the formatted message.</param>
/// <returns>The localized string describing the validation error</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
public virtual string FormatErrorMessage(string name)
{
return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
}
/// <summary>
/// Gets the value indicating whether or not the specified <paramref name="value" /> is valid
/// with respect to the current validation attribute.
/// <para>
/// Derived classes should not override this method as it is only available for backwards compatibility.
/// Instead, implement <see cref="IsValid(object, ValidationContext)" />.
/// </para>
/// </summary>
/// <remarks>
/// The preferred public entry point for clients requesting validation is the <see cref="GetValidationResult" />
/// method.
/// </remarks>
/// <param name="value">The value to validate</param>
/// <returns><c>true</c> if the <paramref name="value" /> is acceptable, <c>false</c> if it is not acceptable</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
/// <exception cref="NotImplementedException">
/// is thrown when neither overload of IsValid has been implemented
/// by a derived class.
/// </exception>
public virtual bool IsValid(object value)
{
if (!_hasBaseIsValid)
{
// track that this method overload has not been overridden.
_hasBaseIsValid = true;
}
// call overridden method.
return IsValid(value, null) == ValidationResult.Success;
}
/// <summary>
/// Protected virtual method to override and implement validation logic.
/// <para>
/// Derived classes should override this method instead of <see cref="IsValid(object)" />, which is deprecated.
/// </para>
/// </summary>
/// <param name="value">The value to validate.</param>
/// <param name="validationContext">
/// A <see cref="ValidationContext" /> instance that provides
/// context about the validation operation, such as the object and member being validated.
/// </param>
/// <returns>
/// When validation is valid, <see cref="ValidationResult.Success" />.
/// <para>
/// When validation is invalid, an instance of <see cref="ValidationResult" />.
/// </para>
/// </returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
/// <exception cref="NotImplementedException">
/// is thrown when <see cref="IsValid(object, ValidationContext)" />
/// has not been implemented by a derived class.
/// </exception>
protected virtual ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_hasBaseIsValid)
{
// this means neither of the IsValid methods has been overridden, throw.
throw NotImplemented.ByDesignWithMessage(
SR.ValidationAttribute_IsValid_NotImplemented);
}
var result = ValidationResult.Success;
// call overridden method.
if (!IsValid(value))
{
string[] memberNames = validationContext.MemberName != null
? new string[] { validationContext.MemberName }
: null;
result = new ValidationResult(FormatErrorMessage(validationContext.DisplayName), memberNames);
}
return result;
}
/// <summary>
/// Tests whether the given <paramref name="value" /> is valid with respect to the current
/// validation attribute without throwing a <see cref="ValidationException" />
/// </summary>
/// <remarks>
/// If this method returns <see cref="ValidationResult.Success" />, then validation was successful, otherwise
/// an instance of <see cref="ValidationResult" /> will be returned with a guaranteed non-null
/// <see cref="ValidationResult.ErrorMessage" />.
/// </remarks>
/// <param name="value">The value to validate</param>
/// <param name="validationContext">
/// A <see cref="ValidationContext" /> instance that provides
/// context about the validation operation, such as the object and member being validated.
/// </param>
/// <returns>
/// When validation is valid, <see cref="ValidationResult.Success" />.
/// <para>
/// When validation is invalid, an instance of <see cref="ValidationResult" />.
/// </para>
/// </returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="NotImplementedException">
/// is thrown when <see cref="IsValid(object, ValidationContext)" />
/// has not been implemented by a derived class.
/// </exception>
public ValidationResult GetValidationResult(object value, ValidationContext validationContext)
{
if (validationContext == null)
{
throw new ArgumentNullException(nameof(validationContext));
}
var result = IsValid(value, validationContext);
// If validation fails, we want to ensure we have a ValidationResult that guarantees it has an ErrorMessage
if (result != null)
{
if (string.IsNullOrEmpty(result.ErrorMessage))
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
result = new ValidationResult(errorMessage, result.MemberNames);
}
}
return result;
}
/// <summary>
/// Validates the specified <paramref name="value" /> and throws <see cref="ValidationException" /> if it is not.
/// <para>
/// The overloaded <see cref="Validate(object, ValidationContext)" /> is the recommended entry point as it
/// can provide additional context to the <see cref="ValidationAttribute" /> being validated.
/// </para>
/// </summary>
/// <remarks>
/// This base method invokes the <see cref="IsValid(object)" /> method to determine whether or not the
/// <paramref name="value" /> is acceptable. If <see cref="IsValid(object)" /> returns <c>false</c>, this base
/// method will invoke the <see cref="FormatErrorMessage" /> to obtain a localized message describing
/// the problem, and it will throw a <see cref="ValidationException" />
/// </remarks>
/// <param name="value">The value to validate</param>
/// <param name="name">The string to be included in the validation error message if <paramref name="value" /> is not valid</param>
/// <exception cref="ValidationException">
/// is thrown if <see cref="IsValid(object)" /> returns <c>false</c>.
/// </exception>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
public void Validate(object value, string name)
{
if (!IsValid(value))
{
throw new ValidationException(FormatErrorMessage(name), this, value);
}
}
/// <summary>
/// Validates the specified <paramref name="value" /> and throws <see cref="ValidationException" /> if it is not.
/// </summary>
/// <remarks>
/// This method invokes the <see cref="IsValid(object, ValidationContext)" /> method
/// to determine whether or not the <paramref name="value" /> is acceptable given the
/// <paramref name="validationContext" />.
/// If that method doesn't return <see cref="ValidationResult.Success" />, this base method will throw
/// a <see cref="ValidationException" /> containing the <see cref="ValidationResult" /> describing the problem.
/// </remarks>
/// <param name="value">The value to validate</param>
/// <param name="validationContext">Additional context that may be used for validation. It cannot be null.</param>
/// <exception cref="ValidationException">
/// is thrown if <see cref="IsValid(object, ValidationContext)" />
/// doesn't return <see cref="ValidationResult.Success" />.
/// </exception>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
/// <exception cref="NotImplementedException">
/// is thrown when <see cref="IsValid(object, ValidationContext)" />
/// has not been implemented by a derived class.
/// </exception>
public void Validate(object value, ValidationContext validationContext)
{
if (validationContext == null)
{
throw new ArgumentNullException(nameof(validationContext));
}
ValidationResult result = GetValidationResult(value, validationContext);
if (result != null)
{
// Convenience -- if implementation did not fill in an error message,
throw new ValidationException(result, this, value);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using BTDB.Buffer;
using BTDB.Collections;
using BTDB.Encrypted;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.KVDBLayer;
using BTDB.StreamLayer;
namespace BTDB.ODBLayer;
delegate void SkipperFun(ref SpanReader reader);
delegate object? LoaderFun(ref SpanReader reader);
public class ODBIterator
{
readonly IInternalObjectDBTransaction _tr;
IODBFastVisitor _fastVisitor;
IODBVisitor? _visitor;
Dictionary<uint, string> _tableId2Name;
readonly IKeyValueDBTransaction _trkv;
Dictionary<uint, ulong> _singletons;
readonly HashSet<uint> _usedTableIds;
readonly HashSet<ulong> _visitedOids;
readonly HashSet<TableIdVersionId> _usedTableVersions;
readonly Dictionary<TableIdVersionId, TableVersionInfo> _tableVersionInfos;
readonly Dictionary<IFieldHandler, SkipperFun> _skippers;
readonly Dictionary<IFieldHandler, LoaderFun> _loaders;
//relations
Dictionary<uint, ODBIteratorRelationInfo> _relationId2Info;
public IDictionary<uint, string> TableId2Name => _tableId2Name;
public IReadOnlyDictionary<uint, ulong> TableId2SingletonOid => _singletons;
public IReadOnlyDictionary<uint, ODBIteratorRelationInfo> RelationId2Info => _relationId2Info;
public IReadOnlyDictionary<TableIdVersionId, TableVersionInfo> TableVersionInfos => _tableVersionInfos;
public bool SkipAlreadyVisitedOidChecks;
public ODBIterator(IObjectDBTransaction tr, IODBFastVisitor visitor)
{
_tr = (IInternalObjectDBTransaction)tr;
_trkv = _tr.KeyValueDBTransaction;
_fastVisitor = visitor;
_visitor = visitor as IODBVisitor;
_usedTableIds = new HashSet<uint>();
_visitedOids = new HashSet<ulong>();
_usedTableVersions = new HashSet<TableIdVersionId>();
_tableVersionInfos = new Dictionary<TableIdVersionId, TableVersionInfo>();
_skippers = new Dictionary<IFieldHandler, SkipperFun>(ReferenceEqualityComparer<IFieldHandler>.Instance);
_loaders = new Dictionary<IFieldHandler, LoaderFun>(ReferenceEqualityComparer<IFieldHandler>.Instance);
}
public void LoadGlobalInfo(bool sortTableByNameAsc = false)
{
LoadTableNamesDict();
LoadRelationInfoDict();
MarkLastDictId();
_trkv.InvalidateCurrentKey();
_singletons = new Dictionary<uint, ulong>();
while (_trkv.FindNextKey(ObjectDB.TableSingletonsPrefix))
{
_singletons.Add(
new SpanReader(_trkv.GetKey().Slice((int)ObjectDB.TableSingletonsPrefixLen)).ReadVUInt32(),
new SpanReader(_trkv.GetValue()).ReadVUInt64());
}
if (sortTableByNameAsc)
{
_singletons = _singletons.OrderBy(item => _tableId2Name.TryGetValue(item.Key, out var name) ? name : "")
.ToDictionary(item => item.Key, item => item.Value);
}
}
public void Iterate(bool sortTableByNameAsc = false)
{
LoadGlobalInfo(sortTableByNameAsc);
foreach (var singleton in _singletons)
{
if (_visitor != null &&
!_visitor.VisitSingleton(singleton.Key,
_tableId2Name.TryGetValue(singleton.Key, out var name) ? name : null, singleton.Value))
continue;
MarkTableName(singleton.Key);
if (_trkv.Find(Vuint2ByteBuffer(ObjectDB.TableSingletonsPrefix, singleton.Key), 0) == FindResult.Exact)
{
_fastVisitor.MarkCurrentKeyAsUsed(_trkv);
}
IterateOid(singleton.Value);
}
foreach (var relation in _relationId2Info)
{
if (_visitor != null && !_visitor.StartRelation(relation.Value))
continue;
MarkRelationName(relation.Key);
IterateRelation(relation.Value);
_visitor?.EndRelation();
}
}
public void IterateUnseenOid(ulong oid, IODBFastVisitor visitor)
{
var visitorBackup = _visitor;
var fastVisitorBackup = _fastVisitor;
try
{
_visitor = visitor as IODBVisitor;
_fastVisitor = visitor;
IterateOid(oid);
}
finally
{
_visitor = visitorBackup;
_fastVisitor = fastVisitorBackup;
}
}
public void IterateOid(ulong oid)
{
if (!SkipAlreadyVisitedOidChecks && !_visitedOids.Add(oid))
return;
if (!_trkv.FindExactKey(Vuint2ByteBuffer(ObjectDB.AllObjectsPrefix, oid)))
return; // Object oid was deleted
_fastVisitor.MarkCurrentKeyAsUsed(_trkv);
var reader = new SpanReader(_trkv.GetValue());
var tableId = reader.ReadVUInt32();
var version = reader.ReadVUInt32();
MarkTableIdVersionFieldInfo(tableId, version);
if (_visitor != null && !_visitor.StartObject(oid, tableId,
_tableId2Name.TryGetValue(tableId, out var tableName) ? tableName : null, version))
return;
var tvi = GetTableVersionInfo(tableId, version);
var knownInlineId = new HashSet<int>();
for (var i = 0; i < tvi.FieldCount; i++)
{
var fi = tvi[i];
if (_visitor == null || _visitor.StartField(fi.Name))
{
IterateHandler(ref reader, fi.Handler!, false, knownInlineId);
_visitor?.EndField();
}
else
{
IterateHandler(ref reader, fi.Handler!, true, knownInlineId);
}
}
_visitor?.EndObject();
}
public void IterateRelationRow(ODBIteratorRelationInfo relation, long pos)
{
var prefix = BuildRelationPrefix(relation.Id);
if (!_trkv.SetKeyIndex(prefix, pos)) return;
var prevProtectionCounter = _trkv.CursorMovedCounter;
if (_visitor == null || _visitor.StartRelationKey())
{
var keyReader = new SpanReader(_trkv.GetKey().Slice(prefix.Length));
var relationInfo = relation.VersionInfos[relation.LastPersistedVersion];
IterateFields(ref keyReader, relationInfo.PrimaryKeyFields.Span, null);
_visitor?.EndRelationKey();
}
if (_trkv.CursorMovedCounter != prevProtectionCounter)
{
if (!_trkv.SetKeyIndex(prefix, pos)) return;
}
if (_visitor == null || _visitor.StartRelationValue())
{
var valueReader = new SpanReader(_trkv.GetValue());
var version = valueReader.ReadVUInt32();
var relationInfo = relation.VersionInfos[version];
IterateFields(ref valueReader, relationInfo.Fields.Span, new HashSet<int>());
_visitor?.EndRelationValue();
}
}
public void IterateRelation(ODBIteratorRelationInfo relation)
{
IterateSecondaryIndexes(relation);
var prefix = BuildRelationPrefix(relation.Id);
long prevProtectionCounter = 0;
long pos = 0;
while (true)
{
if (pos == 0)
{
if (!_trkv.FindFirstKey(prefix)) break;
}
else
{
if (_trkv.CursorMovedCounter != prevProtectionCounter)
{
if (!_trkv.SetKeyIndex(prefix, pos)) break;
}
else
{
if (!_trkv.FindNextKey(prefix)) break;
}
}
_fastVisitor.MarkCurrentKeyAsUsed(_trkv);
prevProtectionCounter = _trkv.CursorMovedCounter;
if (_visitor == null || _visitor.StartRelationKey())
{
var keyReader = new SpanReader(_trkv.GetKey().Slice(prefix.Length));
var relationInfo = relation.VersionInfos[relation.LastPersistedVersion];
IterateFields(ref keyReader, relationInfo.PrimaryKeyFields.Span, null);
_visitor?.EndRelationKey();
}
if (_trkv.CursorMovedCounter != prevProtectionCounter)
{
if (!_trkv.SetKeyIndex(prefix, pos)) break;
}
if (_visitor == null || _visitor.StartRelationValue())
{
var valueReader = new SpanReader(_trkv.GetValue());
var version = valueReader.ReadVUInt32();
var relationInfo = relation.VersionInfos[version];
IterateFields(ref valueReader, relationInfo.Fields.Span, new HashSet<int>());
_visitor?.EndRelationValue();
}
pos++;
}
}
public List<(string, string)> IterateRelationStats(ODBIteratorRelationInfo relation)
{
var res = new List<(string, string)>();
//IterateSecondaryIndexes(relation);
var prefix = BuildRelationPrefix(relation.Id);
var stat1 = new RefDictionary<uint, uint>();
var stat2 = new RefDictionary<uint, uint>();
var stat3 = new RefDictionary<uint, uint>();
long prevProtectionCounter = 0;
long pos = 0;
while (true)
{
if (pos == 0)
{
if (!_trkv.FindFirstKey(prefix)) break;
}
else
{
if (_trkv.CursorMovedCounter != prevProtectionCounter)
{
if (!_trkv.SetKeyIndex(prefix, pos)) break;
}
else
{
if (!_trkv.FindNextKey(prefix)) break;
}
}
var ss = _trkv.GetStorageSizeOfCurrentKey();
stat2.GetOrAddValueRef(ss.Key)++;
stat3.GetOrAddValueRef(ss.Value)++;
var valueReader = new SpanReader(_trkv.GetValue());
var version = valueReader.ReadVUInt32();
stat1.GetOrAddValueRef(version)++;
pos++;
}
foreach (var p in stat1.OrderBy(p => p.Key))
{
res.Add(("Version " + p.Key + "used count", p.Value.ToString()));
}
foreach (var p in stat2.OrderBy(p => p.Key))
{
res.Add(("Key size " + p.Key + " count", p.Value.ToString()));
}
foreach (var p in stat3.OrderBy(p => p.Key))
{
res.Add(("Value size " + p.Key + " count", p.Value.ToString()));
}
return res;
}
void IterateSecondaryIndexes(ODBIteratorRelationInfo relation)
{
var version = relation.VersionInfos[relation.LastPersistedVersion];
foreach (var (secKeyName, secKeyIdx) in version.SecondaryKeysNames)
{
var secondaryKeyFields = version.GetSecondaryKeyFields(secKeyIdx);
if (_visitor == null || _visitor.StartSecondaryIndex(secKeyName))
{
var prefix = BuildRelationSecondaryKeyPrefix(relation.Id, secKeyIdx);
long prevProtectionCounter = 0;
long pos = 0;
while (true)
{
if (pos == 0)
{
if (!_trkv.FindFirstKey(prefix)) break;
}
else
{
if (_trkv.CursorMovedCounter != prevProtectionCounter)
{
if (!_trkv.SetKeyIndex(prefix, pos)) break;
}
else
{
if (!_trkv.FindNextKey(prefix)) break;
}
}
var reader = new SpanReader(_trkv.GetKey().Slice(prefix.Length));
foreach (var fi in secondaryKeyFields)
{
if (_visitor == null || !_visitor.StartField(fi.Name)) continue;
IterateHandler(ref reader, fi.Handler!, false, null);
}
_visitor?.NextSecondaryKey();
pos++;
}
_visitor?.EndSecondaryIndex();
}
}
}
static byte[] BuildRelationSecondaryKeyPrefix(uint relationIndex, uint secondaryKeyIndex)
{
var prefix =
new byte[1 + PackUnpack.LengthVUInt(relationIndex) + PackUnpack.LengthVUInt(secondaryKeyIndex)];
prefix[0] = ObjectDB.AllRelationsSKPrefixByte;
int pos = 1;
PackUnpack.PackVUInt(prefix, ref pos, relationIndex);
PackUnpack.PackVUInt(prefix, ref pos, secondaryKeyIndex);
return prefix;
}
static byte[] BuildRelationPrefix(uint relationIndex)
{
var o = ObjectDB.AllRelationsPKPrefix.Length;
var prefix = new byte[o + PackUnpack.LengthVUInt(relationIndex)];
Array.Copy(ObjectDB.AllRelationsPKPrefix, prefix, o);
PackUnpack.PackVUInt(prefix, ref o, relationIndex);
return prefix;
}
void IterateFields(ref SpanReader reader, ReadOnlySpan<TableFieldInfo> fields, HashSet<int>? knownInlineRefs)
{
foreach (var fi in fields)
{
if (_visitor == null || _visitor.StartField(fi.Name))
{
IterateHandler(ref reader, fi.Handler!, false, knownInlineRefs);
_visitor?.EndField();
}
else
{
IterateHandler(ref reader, fi.Handler!, true, knownInlineRefs);
}
}
}
uint ReadRelationVersions(uint relationIndex, string name,
Dictionary<uint, RelationVersionInfo> relationVersions)
{
uint lastPersistedVersion = 0;
var relationInfoResolver = new RelationInfoResolver((ObjectDB)_tr.Owner);
var writer = new SpanWriter();
writer.WriteByteArrayRaw(ObjectDB.RelationVersionsPrefix);
writer.WriteVUInt32(relationIndex);
var prefix = writer.GetSpan().ToArray();
if (!_trkv.FindFirstKey(prefix))
{
return lastPersistedVersion;
}
do
{
var keyReader = new SpanReader(_trkv.GetKey().Slice(prefix.Length));
var valueReader = new SpanReader(_trkv.GetValue());
lastPersistedVersion = keyReader.ReadVUInt32();
var relationVersionInfo = RelationVersionInfo.LoadUnresolved(ref valueReader, name);
relationVersionInfo.ResolveFieldHandlers(relationInfoResolver.FieldHandlerFactory);
relationVersions[lastPersistedVersion] = relationVersionInfo;
} while (_trkv.FindNextKey(prefix));
return lastPersistedVersion;
}
[SkipLocalsInit]
void IterateDict(ulong dictId, IFieldHandler keyHandler, IFieldHandler valueHandler)
{
if (_visitor != null && !_visitor.StartDictionary(dictId))
return;
var o = ObjectDB.AllDictionariesPrefix.Length;
var prefix = new byte[o + PackUnpack.LengthVUInt(dictId)];
Array.Copy(ObjectDB.AllDictionariesPrefix, prefix, o);
PackUnpack.PackVUInt(prefix, ref o, dictId);
long prevProtectionCounter = 0;
long pos = 0;
Span<byte> keyBuffer = stackalloc byte[512];
while (true)
{
if (pos == 0)
{
if (!_trkv.FindFirstKey(prefix)) break;
}
else
{
if (_trkv.CursorMovedCounter != prevProtectionCounter)
{
if (!_trkv.SetKeyIndex(prefix, pos)) break;
}
else
{
if (!_trkv.FindNextKey(prefix)) break;
}
}
_fastVisitor.MarkCurrentKeyAsUsed(_trkv);
prevProtectionCounter = _trkv.CursorMovedCounter;
if (_visitor == null || _visitor.StartDictKey())
{
var keyReader = new SpanReader(_trkv
.GetKey(ref MemoryMarshal.GetReference(keyBuffer), keyBuffer.Length).Slice(prefix.Length));
IterateHandler(ref keyReader, keyHandler, false, null);
_visitor?.EndDictKey();
}
if (_trkv.CursorMovedCounter != prevProtectionCounter)
{
if (!_trkv.SetKeyIndex(prefix, pos)) break;
}
if (_visitor == null || _visitor.StartDictValue())
{
var valueReader = new SpanReader(_trkv.GetValue());
IterateHandler(ref valueReader, valueHandler, false, null);
_visitor?.EndDictValue();
}
pos++;
}
_visitor?.EndDictionary();
}
void IterateSet(ulong dictId, IFieldHandler keyHandler)
{
if (_visitor != null && !_visitor.StartSet())
return;
var o = ObjectDB.AllDictionariesPrefix.Length;
var prefix = new byte[o + PackUnpack.LengthVUInt(dictId)];
Array.Copy(ObjectDB.AllDictionariesPrefix, prefix, o);
PackUnpack.PackVUInt(prefix, ref o, dictId);
long prevProtectionCounter = 0;
long pos = 0;
while (true)
{
if (pos == 0)
{
if (!_trkv.FindFirstKey(prefix)) break;
}
else
{
if (_trkv.CursorMovedCounter != prevProtectionCounter)
{
if (!_trkv.SetKeyIndex(prefix, pos)) break;
}
else
{
if (!_trkv.FindNextKey(prefix)) break;
}
}
_fastVisitor.MarkCurrentKeyAsUsed(_trkv);
prevProtectionCounter = _trkv.CursorMovedCounter;
if (_visitor == null || _visitor.StartSetKey())
{
var keyReader = new SpanReader(_trkv.GetKey().Slice(prefix.Length));
IterateHandler(ref keyReader, keyHandler, false, null);
_visitor?.EndSetKey();
}
pos++;
}
_visitor?.EndSet();
}
void IterateHandler(ref SpanReader reader, IFieldHandler handler, bool skipping, HashSet<int>? knownInlineRefs)
{
if (handler is ODBDictionaryFieldHandler)
{
var dictId = reader.ReadVUInt64();
if (!skipping)
{
var kvHandlers = ((IFieldHandlerWithNestedFieldHandlers)handler).EnumerateNestedFieldHandlers()
.ToArray();
IterateDict(dictId, kvHandlers[0], kvHandlers[1]);
}
}
else if (handler is ODBSetFieldHandler)
{
var dictId = reader.ReadVUInt64();
if (!skipping)
{
var keyHandler = ((IFieldHandlerWithNestedFieldHandlers)handler).EnumerateNestedFieldHandlers()
.First();
IterateSet(dictId, keyHandler);
}
}
else if (handler is DBObjectFieldHandler)
{
var oid = reader.ReadVInt64();
if (oid == 0)
{
if (!skipping) _visitor?.OidReference(0);
}
else if (oid <= int.MinValue || oid > 0)
{
if (!skipping)
{
_visitor?.OidReference((ulong)oid);
IterateOid((ulong)oid);
}
}
else
{
if (knownInlineRefs != null)
{
if (knownInlineRefs.Contains((int)oid))
{
if (!skipping) _visitor?.InlineBackRef((int)oid);
return;
}
if (!skipping) _visitor?.InlineRef((int)oid);
knownInlineRefs.Add((int)oid);
}
var tableId = reader.ReadVUInt32();
var version = reader.ReadVUInt32();
if (!skipping) MarkTableIdVersionFieldInfo(tableId, version);
var skip = skipping ||
_visitor != null && !_visitor.StartInlineObject(tableId,
_tableId2Name.TryGetValue(tableId, out var tableName) ? tableName : null, version);
var tvi = GetTableVersionInfo(tableId, version);
var knownInlineRefsNested = new HashSet<int>();
for (var i = 0; i < tvi.FieldCount; i++)
{
var fi = tvi[i];
var skipField = skip || _visitor != null && !_visitor.StartField(fi.Name);
IterateHandler(ref reader, fi.Handler!, skipField, knownInlineRefsNested);
if (!skipField) _visitor?.EndField();
}
if (!skip) _visitor?.EndInlineObject();
}
}
else if (handler is ListFieldHandler)
{
var oid = reader.ReadVInt64();
if (oid == 0)
{
if (!skipping) _visitor?.OidReference(0);
}
else if (oid <= int.MinValue || oid > 0)
{
if (!skipping)
{
_visitor?.OidReference((ulong)oid);
IterateOid((ulong)oid);
}
}
else
{
var itemHandler = ((IFieldHandlerWithNestedFieldHandlers)handler).EnumerateNestedFieldHandlers()
.First();
IterateInlineList(ref reader, itemHandler, skipping, knownInlineRefs);
}
}
else if (handler is DictionaryFieldHandler)
{
var oid = reader.ReadVInt64();
if (oid == 0)
{
if (!skipping) _visitor?.OidReference(0);
}
else if (oid <= int.MinValue || oid > 0)
{
if (!skipping)
{
_visitor?.OidReference((ulong)oid);
IterateOid((ulong)oid);
}
}
else
{
var kvHandlers = ((IFieldHandlerWithNestedFieldHandlers)handler).EnumerateNestedFieldHandlers()
.ToArray();
IterateInlineDict(ref reader, kvHandlers[0], kvHandlers[1], skipping, knownInlineRefs);
}
}
else if (handler is NullableFieldHandler)
{
var hasValue = reader.ReadBool();
if (hasValue)
{
var itemHandler = ((IFieldHandlerWithNestedFieldHandlers)handler).EnumerateNestedFieldHandlers()
.First();
IterateHandler(ref reader, itemHandler, skipping, null);
}
}
else if (handler is OrderedEncryptedStringHandler)
{
var cipher = _tr.Owner.GetSymmetricCipher();
if (cipher is InvalidSymmetricCipher)
{
var length = reader.ReadVUInt32();
_visitor?.ScalarAsText($"Encrypted[{length}]");
if (length > 0)
reader.SkipBlock(length - 1);
}
else
{
var enc = reader.ReadByteArray();
var size = cipher.CalcOrderedPlainSizeFor(enc);
var dec = new byte[size];
if (!cipher.OrderedDecrypt(enc, dec))
{
_visitor?.ScalarAsText($"Encrypted[{enc!.Length}] failed to decrypt");
}
var r = new SpanReader(dec);
_visitor?.ScalarAsText(r.ReadString()!);
}
}
else if (handler is EncryptedStringHandler)
{
var cipher = _tr.Owner.GetSymmetricCipher();
if (cipher is InvalidSymmetricCipher)
{
var length = reader.ReadVUInt32();
_visitor?.ScalarAsText($"Encrypted[{length}]");
if (length > 0)
reader.SkipBlock(length - 1);
}
else
{
var enc = reader.ReadByteArray();
var size = cipher.CalcPlainSizeFor(enc);
var dec = new byte[size];
if (!cipher.Decrypt(enc, dec))
{
_visitor?.ScalarAsText($"Encrypted[{enc!.Length}] failed to decrypt");
}
var r = new SpanReader(dec);
_visitor?.ScalarAsText(r.ReadString()!);
}
}
else if (handler is TupleFieldHandler tupleFieldHandler)
{
foreach (var fieldHandler in tupleFieldHandler.EnumerateNestedFieldHandlers())
{
var skipField = _visitor != null && !_visitor.StartItem();
IterateHandler(ref reader, fieldHandler, skipField, knownInlineRefs);
if (!skipField) _visitor?.EndItem();
}
}
else if (handler.NeedsCtx() || handler.HandledType() == null)
{
throw new BTDBException("Don't know how to iterate " + handler.Name);
}
else
{
if (skipping || _visitor == null)
{
if (!_skippers.TryGetValue(handler, out var skipper))
{
var meth =
ILBuilder.Instance.NewMethod<SkipperFun>("Skip" + handler.Name);
var il = meth.Generator;
handler.Skip(il, il2 => il2.Ldarg(0), null);
il.Ret();
skipper = meth.Create();
_skippers.Add(handler, skipper);
}
skipper(ref reader);
}
else
{
if (!_loaders.TryGetValue(handler, out var loader))
{
var meth =
ILBuilder.Instance.NewMethod<LoaderFun>("Load" + handler.Name);
var il = meth.Generator;
handler.Load(il, il2 => il2.Ldarg(0), null);
il.Box(handler.HandledType()!).Ret();
loader = meth.Create();
_loaders.Add(handler, loader);
}
var obj = loader(ref reader);
if (_visitor.NeedScalarAsObject())
{
_visitor.ScalarAsObject(obj);
}
if (_visitor.NeedScalarAsText())
{
_visitor.ScalarAsText(obj == null
? "null"
: string.Format(CultureInfo.InvariantCulture, "{0}", obj));
}
}
}
}
void IterateInlineDict(ref SpanReader reader, IFieldHandler keyHandler, IFieldHandler valueHandler,
bool skipping, HashSet<int>? knownInlineRefs)
{
var skip = skipping || _visitor != null && !_visitor.StartDictionary();
var count = reader.ReadVUInt32();
while (count-- > 0)
{
var skipKey = skip || _visitor != null && !_visitor.StartDictKey();
IterateHandler(ref reader, keyHandler, skipKey, knownInlineRefs);
if (!skipKey) _visitor?.EndDictKey();
var skipValue = skip || _visitor != null && !_visitor.StartDictValue();
IterateHandler(ref reader, valueHandler, skipValue, knownInlineRefs);
if (!skipValue) _visitor?.EndDictValue();
}
if (!skip) _visitor?.EndDictionary();
}
void IterateInlineList(ref SpanReader reader, IFieldHandler itemHandler, bool skipping,
HashSet<int>? knownInlineRefs)
{
var skip = skipping || _visitor != null && !_visitor.StartList();
var count = reader.ReadVUInt32();
while (count-- > 0)
{
var skipItem = skip || _visitor != null && !_visitor.StartItem();
IterateHandler(ref reader, itemHandler, skipItem, knownInlineRefs);
if (!skipItem) _visitor?.EndItem();
}
if (!skip) _visitor?.EndList();
}
void MarkTableIdVersionFieldInfo(uint tableId, uint version)
{
if (!_usedTableVersions.Add(new TableIdVersionId(tableId, version)))
return;
MarkTableName(tableId);
if (_trkv.Find(TwiceVuint2ByteBuffer(ObjectDB.TableVersionsPrefix, tableId, version), 0) ==
FindResult.Exact)
{
_fastVisitor.MarkCurrentKeyAsUsed(_trkv);
}
}
void MarkLastDictId()
{
if (_trkv.FindExactKey(ObjectDB.LastDictIdKey))
{
_fastVisitor.MarkCurrentKeyAsUsed(_trkv);
}
}
void MarkTableName(uint tableId)
{
if (!_usedTableIds.Add(tableId))
return;
if (_trkv.FindExactKey(Vuint2ByteBuffer(ObjectDB.TableNamesPrefix, tableId)))
{
_fastVisitor.MarkCurrentKeyAsUsed(_trkv);
}
}
void MarkRelationName(uint relationId)
{
if (_trkv.FindExactKey(Vuint2ByteBuffer(ObjectDB.RelationNamesPrefix, relationId)))
{
_fastVisitor.MarkCurrentKeyAsUsed(_trkv);
}
}
ReadOnlySpan<byte> Vuint2ByteBuffer(in ReadOnlySpan<byte> prefix, ulong value)
{
var writer = new SpanWriter();
writer.WriteBlock(prefix);
writer.WriteVUInt64(value);
return writer.GetSpan();
}
ReadOnlySpan<byte> TwiceVuint2ByteBuffer(in ReadOnlySpan<byte> prefix, uint v1, uint v2)
{
var writer = new SpanWriter();
writer.WriteBlock(prefix);
writer.WriteVUInt32(v1);
writer.WriteVUInt32(v2);
return writer.GetSpan();
}
void LoadTableNamesDict()
{
_tableId2Name = ObjectDB.LoadTablesEnum(_tr.KeyValueDBTransaction)
.ToDictionary(pair => pair.Key, pair => pair.Value);
}
void LoadRelationInfoDict()
{
_relationId2Info = ObjectDB.LoadRelationNamesEnum(_tr.KeyValueDBTransaction).ToList()
.ToDictionary(pair => pair.Key, pair => LoadRelationInfo(pair));
}
ODBIteratorRelationInfo LoadRelationInfo(KeyValuePair<uint, string> idName)
{
var res = new ODBIteratorRelationInfo
{
Id = idName.Key,
Name = idName.Value,
};
var relationVersions = new Dictionary<uint, RelationVersionInfo>();
res.LastPersistedVersion = ReadRelationVersions(res.Id, res.Name, relationVersions);
res.VersionInfos = relationVersions;
res.RowCount = _trkv.GetKeyValueCount(BuildRelationPrefix(res.Id));
return res;
}
TableVersionInfo GetTableVersionInfo(uint tableId, uint version)
{
if (_tableVersionInfos.TryGetValue(new TableIdVersionId(tableId, version), out var res))
return res;
if (_trkv.FindExactKey(TwiceVuint2ByteBuffer(ObjectDB.TableVersionsPrefix, tableId, version)))
{
var reader = new SpanReader(_trkv.GetValue());
res = TableVersionInfo.Load(ref reader, _tr.Owner.FieldHandlerFactory, _tableId2Name[tableId]);
_tableVersionInfos.Add(new TableIdVersionId(tableId, version), res);
return res;
}
throw new ArgumentException($"TableVersionInfo not found {tableId}-{version}");
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Design;
using System.ComponentModel;
using SharpGL.SceneGraph.Core;
using System.Runtime.InteropServices;
namespace SharpGL.SceneGraph.Assets
{
/// <summary>
/// A Texture object is simply an array of bytes. It has OpenGL functions, but is
/// not limited to OpenGL, so DirectX or custom library functions could be later added.
/// </summary>
[Editor(typeof(NETDesignSurface.Editors.UITextureEditor), typeof(UITypeEditor))]
[TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
[Serializable()]
public class Texture : Asset, IBindable
{
/// <summary>
/// Initializes a new instance of the <see cref="Texture"/> class.
/// </summary>
public Texture()
{
}
/// <summary>
/// Pushes this object into the provided OpenGL instance.
/// This will generally push elements of the attribute stack
/// and then set current values.
/// </summary>
/// <param name="gl">The OpenGL instance.</param>
public virtual void Push(OpenGL gl)
{
// Push texture attributes.
gl.PushAttrib(Enumerations.AttributeMask.Texture);
// Bind the texture.
Bind(gl);
}
/// <summary>
/// Pops this object from the provided OpenGL instance.
/// This will generally pop elements of the attribute stack,
/// restoring previous attribute values.
/// </summary>
/// <param name="gl">The OpenGL instance.</param>
public virtual void Pop(OpenGL gl)
{
// Pop attributes.
gl.PopAttrib();
}
/// <summary>
/// Bind to the specified OpenGL instance.
/// </summary>
/// <param name="gl">The OpenGL instance.</param>
public void Bind(OpenGL gl)
{
// Bind our texture object (make it the current texture).
gl.BindTexture(OpenGL.GL_TEXTURE_2D, TextureName);
}
/// <summary>
/// This function creates the underlying OpenGL object.
/// </summary>
/// <param name="gl"></param>
/// <returns></returns>
public virtual bool Create(OpenGL gl)
{
// If the texture currently exists in OpenGL, destroy it.
Destroy(gl);
// Generate and store a texture identifier.
gl.GenTextures(1, glTextureArray);
return true;
}
/// <summary>
/// This function creates the texture from an image.
/// </summary>
/// <param name="gl">The OpenGL object.</param>
/// <param name="image">The image.</param>
/// <returns>True if the texture was successfully loaded.</returns>
public virtual bool Create(OpenGL gl, Bitmap image)
{
// Create the underlying OpenGL object.
Create(gl);
// Get the maximum texture size supported by OpenGL.
int[] textureMaxSize = { 0 };
gl.GetInteger(OpenGL.GL_MAX_TEXTURE_SIZE, textureMaxSize);
// Find the target width and height sizes, which is just the highest
// posible power of two that'll fit into the image.
int targetWidth = textureMaxSize[0];
int targetHeight = textureMaxSize[0];
for (int size = 1; size <= textureMaxSize[0]; size *= 2)
{
if (image.Width < size)
{
targetWidth = size / 2;
break;
}
if (image.Width == size)
targetWidth = size;
}
for (int size = 1; size <= textureMaxSize[0]; size *= 2)
{
if (image.Height < size)
{
targetHeight = size / 2;
break;
}
if (image.Height == size)
targetHeight = size;
}
// If need to scale, do so now.
if (image.Width != targetWidth || image.Height != targetHeight)
{
// Resize the image.
Image newImage = image.GetThumbnailImage(targetWidth, targetHeight, null, IntPtr.Zero);
// Destory the old image, and reset.
image.Dispose();
image = (Bitmap)newImage;
}
// Lock the image bits (so that we can pass them to OGL).
BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Set the width and height.
width = image.Width;
height = image.Height;
// Bind our texture object (make it the current texture).
gl.BindTexture(OpenGL.GL_TEXTURE_2D, TextureName);
// Set the image data.
gl.TexImage2D(OpenGL.GL_TEXTURE_2D, 0, (int)OpenGL.GL_RGBA,
width, height, 0, OpenGL.GL_BGRA, OpenGL.GL_UNSIGNED_BYTE,
bitmapData.Scan0);
// Unlock the image.
image.UnlockBits(bitmapData);
// Dispose of the image file.
image.Dispose();
// Set linear filtering mode.
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, OpenGL.GL_LINEAR);
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, OpenGL.GL_LINEAR);
// We're done!
return true;
}
/// <summary>
/// This function creates the texture from an image file.
/// </summary>
/// <param name="gl">The OpenGL object.</param>
/// <param name="path">The path to the image file.</param>
/// <returns>True if the texture was successfully loaded.</returns>
public virtual bool Create(OpenGL gl, string path)
{
// Try and load the bitmap. Return false on failure.
using (Bitmap image = new Bitmap(path))
{
if (image == null)
return false;
// Call the main create function.
return Create(gl, image);
}
}
/// <summary>
/// This function destroys the OpenGL object that is a representation of this texture.
/// </summary>
public virtual void Destroy(OpenGL gl)
{
// Only destroy if we have a valid id.
if(glTextureArray[0] != 0)
{
// Delete the texture object.
gl.DeleteTextures(1, glTextureArray);
glTextureArray[0] = 0;
// Destroy the pixel data.
pixelData = null;
// Reset width and height.
width = height = 0;
}
}
/// <summary>
/// This function (attempts) to make a bitmap from the raw data. The fact that
/// the byte array is a managed type makes it slightly more complicated.
/// </summary>
/// <returns>The texture object as a Bitmap.</returns>
public virtual Bitmap ToBitmap()
{
// Check for the trivial case.
if (pixelData == null)
return null;
// Pin the pixel data.
GCHandle handle = GCHandle.Alloc(pixelData, GCHandleType.Pinned);
// Create the bitmap.
Bitmap bitmap = new Bitmap(width, height, width * 4,
PixelFormat.Format32bppRgb, handle.AddrOfPinnedObject());
// Free the data.
handle.Free();
// Return the bitmap.
return bitmap;
}
/// <summary>
/// This is an array of bytes (r, g, b, a) that represent the pixels in this
/// texture object.
/// </summary>
private byte[] pixelData = null;
/// <summary>
/// The width of the texture image.
/// </summary>
private int width = 0;
/// <summary>
/// The height of the texture image.
/// </summary>
private int height = 0;
/// <summary>
/// This is for OpenGL textures, it is the unique ID for the OpenGL texture.
/// </summary>
private uint[] glTextureArray = new uint[1] { 0 };
/// <summary>
/// Gets the name of the texture.
/// </summary>
/// <value>
/// The name of the texture.
/// </value>
[Description("The internal texture code.."), Category("Texture")]
public uint TextureName
{
get { return glTextureArray[0]; }
}
}
}
| |
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 WebApi.Server.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;
}
}
}
| |
// 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 osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Input.StateChanges;
using osu.Game.Beatmaps;
using osu.Game.Graphics.Sprites;
using osu.Game.Replays;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Tests.Visual.UserInterface;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneReplayRecording : OsuTestScene
{
private readonly TestRulesetInputManager playbackManager;
private readonly TestRulesetInputManager recordingManager;
[Cached]
private GameplayState gameplayState = new GameplayState(new Beatmap(), new OsuRuleset(), Array.Empty<Mod>());
public TestSceneReplayRecording()
{
Replay replay = new Replay();
Add(new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[]
{
recordingManager = new TestRulesetInputManager(TestSceneModSettings.CreateTestRulesetInfo(), 0, SimultaneousBindingMode.Unique)
{
Recorder = new TestReplayRecorder(new Score
{
Replay = replay,
ScoreInfo = { BeatmapInfo = gameplayState.Beatmap.BeatmapInfo }
})
{
ScreenSpaceToGamefield = pos => recordingManager?.ToLocalSpace(pos) ?? Vector2.Zero,
},
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
Colour = Color4.Brown,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Text = "Recording",
Scale = new Vector2(3),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
new TestConsumer()
}
},
}
},
new Drawable[]
{
playbackManager = new TestRulesetInputManager(TestSceneModSettings.CreateTestRulesetInfo(), 0, SimultaneousBindingMode.Unique)
{
ReplayInputHandler = new TestFramedReplayInputHandler(replay)
{
GamefieldToScreenSpace = pos => playbackManager?.ToScreenSpace(pos) ?? Vector2.Zero,
},
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
Colour = Color4.DarkBlue,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Text = "Playback",
Scale = new Vector2(3),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
new TestConsumer()
}
},
}
}
}
});
}
protected override void Update()
{
base.Update();
playbackManager.ReplayInputHandler.SetFrameFromTime(Time.Current - 500);
}
}
public class TestFramedReplayInputHandler : FramedReplayInputHandler<TestReplayFrame>
{
public TestFramedReplayInputHandler(Replay replay)
: base(replay)
{
}
public override void CollectPendingInputs(List<IInput> inputs)
{
inputs.Add(new MousePositionAbsoluteInput { Position = GamefieldToScreenSpace(CurrentFrame?.Position ?? Vector2.Zero) });
inputs.Add(new ReplayState<TestAction> { PressedActions = CurrentFrame?.Actions ?? new List<TestAction>() });
}
}
public class TestConsumer : CompositeDrawable, IKeyBindingHandler<TestAction>
{
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Parent.ReceivePositionalInputAt(screenSpacePos);
private readonly Box box;
public TestConsumer()
{
Size = new Vector2(30);
Origin = Anchor.Centre;
InternalChildren = new Drawable[]
{
box = new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
};
}
protected override bool OnMouseMove(MouseMoveEvent e)
{
Position = e.MousePosition;
return base.OnMouseMove(e);
}
public bool OnPressed(KeyBindingPressEvent<TestAction> e)
{
if (e.Repeat)
return false;
box.Colour = Color4.White;
return true;
}
public void OnReleased(KeyBindingReleaseEvent<TestAction> e)
{
box.Colour = Color4.Black;
}
}
public class TestRulesetInputManager : RulesetInputManager<TestAction>
{
public TestRulesetInputManager(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
: base(ruleset, variant, unique)
{
}
protected override KeyBindingContainer<TestAction> CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
=> new TestKeyBindingContainer();
internal class TestKeyBindingContainer : KeyBindingContainer<TestAction>
{
public override IEnumerable<IKeyBinding> DefaultKeyBindings => new[]
{
new KeyBinding(InputKey.MouseLeft, TestAction.Down),
};
}
}
public class TestReplayFrame : ReplayFrame
{
public Vector2 Position;
public List<TestAction> Actions = new List<TestAction>();
public TestReplayFrame(double time, Vector2 position, params TestAction[] actions)
: base(time)
{
Position = position;
Actions.AddRange(actions);
}
}
public enum TestAction
{
Down,
}
internal class TestReplayRecorder : ReplayRecorder<TestAction>
{
public TestReplayRecorder(Score target)
: base(target)
{
}
protected override ReplayFrame HandleFrame(Vector2 mousePosition, List<TestAction> actions, ReplayFrame previousFrame) =>
new TestReplayFrame(Time.Current, mousePosition, actions.ToArray());
}
}
| |
namespace EIDSS.Reports.Parameterized.Human.GG.Report
{
partial class MicrobiologyResearchCardReport
{
#region 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(MicrobiologyResearchCardReport));
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
this.ReportHeader1 = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.tblSampleHeader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReceivedMonthCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReceivedDayCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReceivedYearCell = new DevExpress.XtraReports.UI.XRTableCell();
this.Cell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.CollectedMonthCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell70 = new DevExpress.XtraReports.UI.XRTableCell();
this.CollectedDayCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell72 = new DevExpress.XtraReports.UI.XRTableCell();
this.CollectedYearCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.OtherCheckBox = new DevExpress.XtraReports.UI.XRCheckBox();
this.PCRCheckBox = new DevExpress.XtraReports.UI.XRCheckBox();
this.MicroscopingCheckBox = new DevExpress.XtraReports.UI.XRCheckBox();
this.VirologyCheckBox = new DevExpress.XtraReports.UI.XRCheckBox();
this.BacteriologyCheckBox = new DevExpress.XtraReports.UI.XRCheckBox();
this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell56 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell58 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.TestMonthCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.TestDayCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.TestYearCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell();
this.tblLines = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow19 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow23 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow24 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell61 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow25 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow26 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell66 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow27 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell68 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.m_Adapter = new EIDSS.Reports.Parameterized.Human.GG.DataSet.MicrobiologyResearchCardDataSetTableAdapters.MicrobiologyResearchCardAdapter();
this.m_DataSet = new EIDSS.Reports.Parameterized.Human.GG.DataSet.MicrobiologyResearchCardDataSet();
this.HeaderTable = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow28 = new DevExpress.XtraReports.UI.XRTableRow();
this.SiteNameCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow31 = new DevExpress.XtraReports.UI.XRTableRow();
this.SiteAddressCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow33 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell69 = new DevExpress.XtraReports.UI.XRTableCell();
this.LogoPicture = new DevExpress.XtraReports.UI.XRPictureBox();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tblSampleHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tblLines)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
resources.ApplyResources(this.cellLanguage, "cellLanguage");
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.Multiline = true;
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.LogoPicture,
this.HeaderTable});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
resources.ApplyResources(this.ReportHeader, "ReportHeader");
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
//
// cellBaseSite
//
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
//
// cellBaseCountry
//
resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry");
this.cellBaseCountry.StylePriority.UseFont = false;
//
// cellBaseLeftHeader
//
resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader");
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail1,
this.ReportHeader1,
this.ReportFooter});
this.DetailReport.DataAdapter = this.m_Adapter;
this.DetailReport.DataMember = "MicrobiologyResearchCard";
this.DetailReport.DataSource = this.m_DataSet;
resources.ApplyResources(this.DetailReport, "DetailReport");
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
this.DetailReport.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
//
// Detail1
//
resources.ApplyResources(this.Detail1, "Detail1");
this.Detail1.Name = "Detail1";
//
// ReportHeader1
//
this.ReportHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tblSampleHeader,
this.tblLines});
resources.ApplyResources(this.ReportHeader1, "ReportHeader1");
this.ReportHeader1.Name = "ReportHeader1";
this.ReportHeader1.StylePriority.UseFont = false;
this.ReportHeader1.StylePriority.UseTextAlignment = false;
//
// tblSampleHeader
//
resources.ApplyResources(this.tblSampleHeader, "tblSampleHeader");
this.tblSampleHeader.Name = "tblSampleHeader";
this.tblSampleHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow2,
this.xrTableRow3,
this.xrTableRow4,
this.xrTableRow5,
this.xrTableRow7,
this.xrTableRow6,
this.xrTableRow8,
this.xrTableRow9,
this.xrTableRow20,
this.xrTableRow13,
this.xrTableRow16,
this.xrTableRow17,
this.xrTableRow18,
this.xrTableRow15});
this.tblSampleHeader.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1,
this.xrTableCell15,
this.xrTableCell2});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.StylePriority.UseTextAlignment = false;
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseFont = false;
this.xrTableCell1.StylePriority.UseTextAlignment = false;
//
// xrTableCell15
//
this.xrTableCell15.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.strSampleId")});
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Name = "xrTableCell15";
this.xrTableCell15.StylePriority.UseBorders = false;
this.xrTableCell15.StylePriority.UseFont = false;
//
// xrTableCell2
//
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.Padding = new DevExpress.XtraPrinting.PaddingInfo(20, 2, 2, 2, 100F);
this.xrTableCell2.StylePriority.UsePadding = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell3,
this.ReceivedMonthCell,
this.xrTableCell4,
this.ReceivedDayCell,
this.xrTableCell30,
this.ReceivedYearCell,
this.Cell1});
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.StylePriority.UseTextAlignment = false;
//
// xrTableCell3
//
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseFont = false;
//
// ReceivedMonthCell
//
this.ReceivedMonthCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.ReceivedMonthCell, "ReceivedMonthCell");
this.ReceivedMonthCell.Name = "ReceivedMonthCell";
this.ReceivedMonthCell.StylePriority.UseBorders = false;
this.ReceivedMonthCell.StylePriority.UseFont = false;
this.ReceivedMonthCell.StylePriority.UseTextAlignment = false;
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
//
// ReceivedDayCell
//
this.ReceivedDayCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.ReceivedDayCell, "ReceivedDayCell");
this.ReceivedDayCell.Name = "ReceivedDayCell";
this.ReceivedDayCell.StylePriority.UseBorders = false;
this.ReceivedDayCell.StylePriority.UseFont = false;
this.ReceivedDayCell.StylePriority.UseTextAlignment = false;
//
// xrTableCell30
//
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Name = "xrTableCell30";
//
// ReceivedYearCell
//
this.ReceivedYearCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.ReceivedYearCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.datSampleReceived", "{0:yyyy}")});
resources.ApplyResources(this.ReceivedYearCell, "ReceivedYearCell");
this.ReceivedYearCell.Name = "ReceivedYearCell";
this.ReceivedYearCell.StylePriority.UseBorders = false;
this.ReceivedYearCell.StylePriority.UseFont = false;
this.ReceivedYearCell.StylePriority.UseTextAlignment = false;
//
// Cell1
//
resources.ApplyResources(this.Cell1, "Cell1");
this.Cell1.Name = "Cell1";
this.Cell1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.Cell1.StylePriority.UsePadding = false;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.CollectedMonthCell,
this.xrTableCell70,
this.CollectedDayCell,
this.xrTableCell72,
this.CollectedYearCell,
this.xrTableCell11,
this.xrTableCell12,
this.xrTableCell20,
this.xrTableCell21,
this.xrTableCell22,
this.xrTableCell6});
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.StylePriority.UseTextAlignment = false;
//
// xrTableCell5
//
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseFont = false;
//
// CollectedMonthCell
//
this.CollectedMonthCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.CollectedMonthCell, "CollectedMonthCell");
this.CollectedMonthCell.Name = "CollectedMonthCell";
this.CollectedMonthCell.StylePriority.UseBorders = false;
this.CollectedMonthCell.StylePriority.UseFont = false;
this.CollectedMonthCell.StylePriority.UseTextAlignment = false;
//
// xrTableCell70
//
resources.ApplyResources(this.xrTableCell70, "xrTableCell70");
this.xrTableCell70.Name = "xrTableCell70";
//
// CollectedDayCell
//
this.CollectedDayCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.CollectedDayCell, "CollectedDayCell");
this.CollectedDayCell.Name = "CollectedDayCell";
this.CollectedDayCell.StylePriority.UseBorders = false;
this.CollectedDayCell.StylePriority.UseFont = false;
this.CollectedDayCell.StylePriority.UseTextAlignment = false;
//
// xrTableCell72
//
resources.ApplyResources(this.xrTableCell72, "xrTableCell72");
this.xrTableCell72.Name = "xrTableCell72";
//
// CollectedYearCell
//
this.CollectedYearCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.CollectedYearCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.datSampleCollected", "{0:yyyy}")});
resources.ApplyResources(this.CollectedYearCell, "CollectedYearCell");
this.CollectedYearCell.Name = "CollectedYearCell";
this.CollectedYearCell.StylePriority.UseBorders = false;
this.CollectedYearCell.StylePriority.UseFont = false;
this.CollectedYearCell.StylePriority.UseTextAlignment = false;
//
// xrTableCell11
//
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
//
// xrTableCell12
//
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.Padding = new DevExpress.XtraPrinting.PaddingInfo(20, 2, 2, 2, 100F);
this.xrTableCell12.StylePriority.UseFont = false;
this.xrTableCell12.StylePriority.UsePadding = false;
//
// xrTableCell20
//
this.xrTableCell20.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseBorders = false;
this.xrTableCell20.StylePriority.UseFont = false;
//
// xrTableCell21
//
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
//
// xrTableCell22
//
this.xrTableCell22.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseBorders = false;
this.xrTableCell22.StylePriority.UseFont = false;
//
// xrTableCell6
//
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7,
this.xrTableCell16,
this.xrTableCell17,
this.xrTableCell8});
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
this.xrTableRow4.KeepTogether = false;
this.xrTableRow4.Name = "xrTableRow4";
//
// xrTableCell7
//
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseFont = false;
//
// xrTableCell16
//
this.xrTableCell16.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.strNameSurname")});
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.StylePriority.UseBorders = false;
this.xrTableCell16.StylePriority.UseFont = false;
//
// xrTableCell17
//
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.Padding = new DevExpress.XtraPrinting.PaddingInfo(20, 2, 2, 2, 100F);
this.xrTableCell17.StylePriority.UseFont = false;
this.xrTableCell17.StylePriority.UsePadding = false;
//
// xrTableCell8
//
this.xrTableCell8.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.strAge")});
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseBorders = false;
this.xrTableCell8.StylePriority.UseFont = false;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9,
this.xrTableCell18});
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
this.xrTableRow5.Name = "xrTableRow5";
//
// xrTableCell9
//
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.StylePriority.UseFont = false;
//
// xrTableCell18
//
this.xrTableCell18.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.strResearchedSample")});
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseBorders = false;
this.xrTableCell18.StylePriority.UseFont = false;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell25,
this.xrTableCell31});
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
this.xrTableRow7.Name = "xrTableRow7";
//
// xrTableCell25
//
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.StylePriority.UseFont = false;
//
// xrTableCell31
//
this.xrTableCell31.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell31.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.strResearchedDiagnosis")});
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
this.xrTableCell31.Name = "xrTableCell31";
this.xrTableCell31.StylePriority.UseBorders = false;
this.xrTableCell31.StylePriority.UseFont = false;
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell13,
this.xrTableCell19});
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
this.xrTableRow6.Name = "xrTableRow6";
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.StylePriority.UseFont = false;
//
// xrTableCell19
//
this.xrTableCell19.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.strSampleReceivedFrom")});
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseBorders = false;
this.xrTableCell19.StylePriority.UseFont = false;
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell27});
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
this.xrTableRow8.Name = "xrTableRow8";
//
// xrTableCell27
//
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Name = "xrTableCell27";
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell23,
this.xrTableCell24});
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
this.xrTableRow9.Name = "xrTableRow9";
//
// xrTableCell23
//
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseFont = false;
this.xrTableCell23.StylePriority.UseTextAlignment = false;
//
// xrTableCell24
//
this.xrTableCell24.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel1,
this.OtherCheckBox,
this.PCRCheckBox,
this.MicroscopingCheckBox,
this.VirologyCheckBox,
this.BacteriologyCheckBox});
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseBorders = false;
//
// xrLabel1
//
this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrLabel1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.strOther")});
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseBorders = false;
this.xrLabel1.StylePriority.UseFont = false;
//
// OtherCheckBox
//
resources.ApplyResources(this.OtherCheckBox, "OtherCheckBox");
this.OtherCheckBox.Name = "OtherCheckBox";
this.OtherCheckBox.StylePriority.UseFont = false;
//
// PCRCheckBox
//
resources.ApplyResources(this.PCRCheckBox, "PCRCheckBox");
this.PCRCheckBox.Name = "PCRCheckBox";
this.PCRCheckBox.StylePriority.UseFont = false;
//
// MicroscopingCheckBox
//
resources.ApplyResources(this.MicroscopingCheckBox, "MicroscopingCheckBox");
this.MicroscopingCheckBox.Name = "MicroscopingCheckBox";
this.MicroscopingCheckBox.StylePriority.UseFont = false;
//
// VirologyCheckBox
//
resources.ApplyResources(this.VirologyCheckBox, "VirologyCheckBox");
this.VirologyCheckBox.Name = "VirologyCheckBox";
this.VirologyCheckBox.StylePriority.UseFont = false;
//
// BacteriologyCheckBox
//
resources.ApplyResources(this.BacteriologyCheckBox, "BacteriologyCheckBox");
this.BacteriologyCheckBox.Name = "BacteriologyCheckBox";
this.BacteriologyCheckBox.StylePriority.UseFont = false;
//
// xrTableRow20
//
this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell26,
this.xrTableCell29});
resources.ApplyResources(this.xrTableRow20, "xrTableRow20");
this.xrTableRow20.Name = "xrTableRow20";
//
// xrTableCell26
//
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseFont = false;
this.xrTableCell26.StylePriority.UseTextAlignment = false;
//
// xrTableCell29
//
this.xrTableCell29.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.strResearchResult")});
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
this.xrTableCell29.Multiline = true;
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.StylePriority.UseBorders = false;
this.xrTableCell29.StylePriority.UseFont = false;
this.xrTableCell29.StylePriority.UseTextAlignment = false;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell40,
this.xrTableCell48,
this.xrTableCell41});
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
this.xrTableRow13.Name = "xrTableRow13";
//
// xrTableCell40
//
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
this.xrTableCell40.Name = "xrTableCell40";
this.xrTableCell40.StylePriority.UseFont = false;
//
// xrTableCell48
//
this.xrTableCell48.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell48.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.strResearchConductedBy")});
resources.ApplyResources(this.xrTableCell48, "xrTableCell48");
this.xrTableCell48.Name = "xrTableCell48";
this.xrTableCell48.StylePriority.UseBorders = false;
this.xrTableCell48.StylePriority.UseFont = false;
//
// xrTableCell41
//
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
this.xrTableCell41.Name = "xrTableCell41";
//
// xrTableRow16
//
this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell52,
this.xrTableCell53,
this.xrTableCell54});
resources.ApplyResources(this.xrTableRow16, "xrTableRow16");
this.xrTableRow16.Name = "xrTableRow16";
//
// xrTableCell52
//
resources.ApplyResources(this.xrTableCell52, "xrTableCell52");
this.xrTableCell52.Name = "xrTableCell52";
//
// xrTableCell53
//
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.StylePriority.UseFont = false;
this.xrTableCell53.StylePriority.UseTextAlignment = false;
//
// xrTableCell54
//
resources.ApplyResources(this.xrTableCell54, "xrTableCell54");
this.xrTableCell54.Name = "xrTableCell54";
//
// xrTableRow17
//
this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell55,
this.xrTableCell56,
this.xrTableCell57});
resources.ApplyResources(this.xrTableRow17, "xrTableRow17");
this.xrTableRow17.Name = "xrTableRow17";
//
// xrTableCell55
//
resources.ApplyResources(this.xrTableCell55, "xrTableCell55");
this.xrTableCell55.Name = "xrTableCell55";
this.xrTableCell55.StylePriority.UseFont = false;
//
// xrTableCell56
//
this.xrTableCell56.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell56.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.strResponsiblePerson")});
resources.ApplyResources(this.xrTableCell56, "xrTableCell56");
this.xrTableCell56.Name = "xrTableCell56";
this.xrTableCell56.StylePriority.UseBorders = false;
this.xrTableCell56.StylePriority.UseFont = false;
//
// xrTableCell57
//
resources.ApplyResources(this.xrTableCell57, "xrTableCell57");
this.xrTableCell57.Name = "xrTableCell57";
//
// xrTableRow18
//
this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell58,
this.xrTableCell59,
this.xrTableCell60});
resources.ApplyResources(this.xrTableRow18, "xrTableRow18");
this.xrTableRow18.Name = "xrTableRow18";
//
// xrTableCell58
//
resources.ApplyResources(this.xrTableCell58, "xrTableCell58");
this.xrTableCell58.Name = "xrTableCell58";
//
// xrTableCell59
//
resources.ApplyResources(this.xrTableCell59, "xrTableCell59");
this.xrTableCell59.Name = "xrTableCell59";
this.xrTableCell59.StylePriority.UseFont = false;
this.xrTableCell59.StylePriority.UseTextAlignment = false;
//
// xrTableCell60
//
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
this.xrTableCell60.Name = "xrTableCell60";
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell49,
this.TestMonthCell,
this.xrTableCell32,
this.TestDayCell,
this.xrTableCell37,
this.TestYearCell,
this.xrTableCell50,
this.xrTableCell51});
resources.ApplyResources(this.xrTableRow15, "xrTableRow15");
this.xrTableRow15.Name = "xrTableRow15";
//
// xrTableCell49
//
resources.ApplyResources(this.xrTableCell49, "xrTableCell49");
this.xrTableCell49.Name = "xrTableCell49";
this.xrTableCell49.StylePriority.UseFont = false;
this.xrTableCell49.StylePriority.UseTextAlignment = false;
//
// TestMonthCell
//
this.TestMonthCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.TestMonthCell, "TestMonthCell");
this.TestMonthCell.Name = "TestMonthCell";
this.TestMonthCell.StylePriority.UseBorders = false;
this.TestMonthCell.StylePriority.UseFont = false;
this.TestMonthCell.StylePriority.UseTextAlignment = false;
//
// xrTableCell32
//
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
this.xrTableCell32.Name = "xrTableCell32";
//
// TestDayCell
//
this.TestDayCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.TestDayCell, "TestDayCell");
this.TestDayCell.Name = "TestDayCell";
this.TestDayCell.StylePriority.UseBorders = false;
this.TestDayCell.StylePriority.UseFont = false;
this.TestDayCell.StylePriority.UseTextAlignment = false;
//
// xrTableCell37
//
resources.ApplyResources(this.xrTableCell37, "xrTableCell37");
this.xrTableCell37.Name = "xrTableCell37";
//
// TestYearCell
//
this.TestYearCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.TestYearCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "MicrobiologyResearchCard.datResultIssueDate", "{0:yyyy}")});
resources.ApplyResources(this.TestYearCell, "TestYearCell");
this.TestYearCell.Name = "TestYearCell";
this.TestYearCell.StylePriority.UseBorders = false;
this.TestYearCell.StylePriority.UseFont = false;
this.TestYearCell.StylePriority.UseTextAlignment = false;
//
// xrTableCell50
//
resources.ApplyResources(this.xrTableCell50, "xrTableCell50");
this.xrTableCell50.Name = "xrTableCell50";
//
// xrTableCell51
//
resources.ApplyResources(this.xrTableCell51, "xrTableCell51");
this.xrTableCell51.Name = "xrTableCell51";
//
// tblLines
//
this.tblLines.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.tblLines, "tblLines");
this.tblLines.Name = "tblLines";
this.tblLines.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow19,
this.xrTableRow23,
this.xrTableRow24,
this.xrTableRow25,
this.xrTableRow26,
this.xrTableRow27});
this.tblLines.StylePriority.UseBorders = false;
this.tblLines.StylePriority.UseTextAlignment = false;
//
// xrTableRow19
//
this.xrTableRow19.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell33});
resources.ApplyResources(this.xrTableRow19, "xrTableRow19");
this.xrTableRow19.Name = "xrTableRow19";
//
// xrTableCell33
//
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
this.xrTableCell33.Name = "xrTableCell33";
this.xrTableCell33.StylePriority.UseBorders = false;
//
// xrTableRow23
//
this.xrTableRow23.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell34});
resources.ApplyResources(this.xrTableRow23, "xrTableRow23");
this.xrTableRow23.Name = "xrTableRow23";
//
// xrTableCell34
//
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseBorders = false;
//
// xrTableRow24
//
this.xrTableRow24.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell61});
resources.ApplyResources(this.xrTableRow24, "xrTableRow24");
this.xrTableRow24.Name = "xrTableRow24";
//
// xrTableCell61
//
resources.ApplyResources(this.xrTableCell61, "xrTableCell61");
this.xrTableCell61.Name = "xrTableCell61";
this.xrTableCell61.StylePriority.UseBorders = false;
//
// xrTableRow25
//
this.xrTableRow25.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell64});
resources.ApplyResources(this.xrTableRow25, "xrTableRow25");
this.xrTableRow25.Name = "xrTableRow25";
//
// xrTableCell64
//
resources.ApplyResources(this.xrTableCell64, "xrTableCell64");
this.xrTableCell64.Name = "xrTableCell64";
this.xrTableCell64.StylePriority.UseBorders = false;
//
// xrTableRow26
//
this.xrTableRow26.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell66});
resources.ApplyResources(this.xrTableRow26, "xrTableRow26");
this.xrTableRow26.Name = "xrTableRow26";
//
// xrTableCell66
//
resources.ApplyResources(this.xrTableCell66, "xrTableCell66");
this.xrTableCell66.Name = "xrTableCell66";
//
// xrTableRow27
//
this.xrTableRow27.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell68});
resources.ApplyResources(this.xrTableRow27, "xrTableRow27");
this.xrTableRow27.Name = "xrTableRow27";
//
// xrTableCell68
//
resources.ApplyResources(this.xrTableCell68, "xrTableCell68");
this.xrTableCell68.Name = "xrTableCell68";
//
// ReportFooter
//
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
this.ReportFooter.StylePriority.UseTextAlignment = false;
//
// m_Adapter
//
this.m_Adapter.ClearBeforeFill = true;
//
// m_DataSet
//
this.m_DataSet.DataSetName = "MicrobiologyResearchCardDataSet";
this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// HeaderTable
//
resources.ApplyResources(this.HeaderTable, "HeaderTable");
this.HeaderTable.Name = "HeaderTable";
this.HeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow28,
this.xrTableRow31,
this.xrTableRow33});
this.HeaderTable.StylePriority.UseTextAlignment = false;
//
// xrTableRow28
//
this.xrTableRow28.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.SiteNameCell});
resources.ApplyResources(this.xrTableRow28, "xrTableRow28");
this.xrTableRow28.Name = "xrTableRow28";
this.xrTableRow28.StylePriority.UseTextAlignment = false;
//
// SiteNameCell
//
this.SiteNameCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_DataSet, "MicrobiologyResearchCard.strSiteName")});
resources.ApplyResources(this.SiteNameCell, "SiteNameCell");
this.SiteNameCell.Name = "SiteNameCell";
this.SiteNameCell.StylePriority.UseFont = false;
//
// xrTableRow31
//
this.xrTableRow31.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.SiteAddressCell});
resources.ApplyResources(this.xrTableRow31, "xrTableRow31");
this.xrTableRow31.Name = "xrTableRow31";
//
// SiteAddressCell
//
this.SiteAddressCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", this.m_DataSet, "MicrobiologyResearchCard.strSiteAddress")});
resources.ApplyResources(this.SiteAddressCell, "SiteAddressCell");
this.SiteAddressCell.Name = "SiteAddressCell";
this.SiteAddressCell.StylePriority.UseFont = false;
this.SiteAddressCell.StylePriority.UseTextAlignment = false;
//
// xrTableRow33
//
this.xrTableRow33.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell69});
resources.ApplyResources(this.xrTableRow33, "xrTableRow33");
this.xrTableRow33.Name = "xrTableRow33";
//
// xrTableCell69
//
resources.ApplyResources(this.xrTableCell69, "xrTableCell69");
this.xrTableCell69.Name = "xrTableCell69";
this.xrTableCell69.StylePriority.UseFont = false;
//
// LogoPicture
//
resources.ApplyResources(this.LogoPicture, "LogoPicture");
this.LogoPicture.Image = ((System.Drawing.Image)(resources.GetObject("LogoPicture.Image")));
this.LogoPicture.Name = "LogoPicture";
this.LogoPicture.Sizing = DevExpress.XtraPrinting.ImageSizeMode.StretchImage;
//
// MicrobiologyResearchCardReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReport});
resources.ApplyResources(this, "$this");
this.Version = "14.1";
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tblSampleHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tblLines)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand Detail1;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader1;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
private DevExpress.XtraReports.UI.XRTable tblSampleHeader;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell Cell1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell40;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell52;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell54;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell55;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell56;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell57;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell58;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell59;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell60;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell50;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell51;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private EIDSS.Reports.Parameterized.Human.GG.DataSet.MicrobiologyResearchCardDataSet m_DataSet;
private EIDSS.Reports.Parameterized.Human.GG.DataSet.MicrobiologyResearchCardDataSetTableAdapters.MicrobiologyResearchCardAdapter m_Adapter;
private DevExpress.XtraReports.UI.XRTable tblLines;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell61;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell64;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow26;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell66;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow27;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell68;
private DevExpress.XtraReports.UI.XRPictureBox LogoPicture;
private DevExpress.XtraReports.UI.XRTable HeaderTable;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow28;
private DevExpress.XtraReports.UI.XRTableCell SiteNameCell;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow31;
private DevExpress.XtraReports.UI.XRTableCell SiteAddressCell;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow33;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell69;
private DevExpress.XtraReports.UI.XRTableCell ReceivedMonthCell;
private DevExpress.XtraReports.UI.XRTableCell ReceivedDayCell;
private DevExpress.XtraReports.UI.XRTableCell ReceivedYearCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableCell CollectedMonthCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell70;
private DevExpress.XtraReports.UI.XRTableCell CollectedDayCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell72;
private DevExpress.XtraReports.UI.XRTableCell CollectedYearCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRCheckBox OtherCheckBox;
private DevExpress.XtraReports.UI.XRCheckBox PCRCheckBox;
private DevExpress.XtraReports.UI.XRCheckBox MicroscopingCheckBox;
private DevExpress.XtraReports.UI.XRCheckBox VirologyCheckBox;
private DevExpress.XtraReports.UI.XRCheckBox BacteriologyCheckBox;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.XRTableCell TestMonthCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell TestDayCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell37;
private DevExpress.XtraReports.UI.XRTableCell TestYearCell;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Security.Policy;
using System.Collections.Generic;
using System.Runtime.Versioning;
namespace System.Xml
{
internal sealed partial class XmlValidatingReaderImpl : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
{
//
// Private helper types
//
// ParsingFunction = what should the reader do when the next Read() is called
private enum ParsingFunction
{
Read = 0,
Init,
ParseDtdFromContext,
ResolveEntityInternally,
InReadBinaryContent,
ReaderClosed,
Error,
None,
}
internal class ValidationEventHandling : IValidationEventHandling
{
// Fields
private XmlValidatingReaderImpl _reader;
private ValidationEventHandler _eventHandler;
// Constructor
internal ValidationEventHandling(XmlValidatingReaderImpl reader)
{
_reader = reader;
}
// IValidationEventHandling interface
#region IValidationEventHandling interface
object IValidationEventHandling.EventHandler
{
get { return _eventHandler; }
}
void IValidationEventHandling.SendEvent(Exception /*XmlSchemaException*/ exception, XmlSeverityType severity)
{
if (_eventHandler != null)
{
_eventHandler(_reader, new ValidationEventArgs((XmlSchemaException)exception, severity));
}
else if (_reader.ValidationType != ValidationType.None && severity == XmlSeverityType.Error)
{
throw exception;
}
}
#endregion
// XmlValidatingReaderImpl helper methods
internal void AddHandler(ValidationEventHandler handler)
{
_eventHandler += handler;
}
internal void RemoveHandler(ValidationEventHandler handler)
{
_eventHandler -= handler;
}
}
//
// Fields
//
// core text reader
private XmlReader _coreReader;
private XmlTextReaderImpl _coreReaderImpl;
private IXmlNamespaceResolver _coreReaderNSResolver;
// validation
private ValidationType _validationType;
private BaseValidator _validator;
#pragma warning disable 618
private XmlSchemaCollection _schemaCollection;
#pragma warning restore 618
private bool _processIdentityConstraints;
// parsing function (state)
private ParsingFunction _parsingFunction = ParsingFunction.Init;
// event handling
private ValidationEventHandling _eventHandling;
// misc
private XmlParserContext _parserContext;
// helper for Read[Element]ContentAs{Base64,BinHex} methods
private ReadContentAsBinaryHelper _readBinaryHelper;
// Outer XmlReader exposed to the user - either XmlValidatingReader or XmlValidatingReaderImpl (when created via XmlReader.Create).
// Virtual methods called from within XmlValidatingReaderImpl must be called on the outer reader so in case the user overrides
// some of the XmlValidatingReader methods we will call the overriden version.
private XmlReader _outerReader;
//
// Constructors
//
// Initializes a new instance of XmlValidatingReaderImpl class with the specified XmlReader.
// This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader
internal XmlValidatingReaderImpl(XmlReader reader)
{
XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader;
if (asyncCheckReader != null)
{
reader = asyncCheckReader.CoreReader;
}
_outerReader = this;
_coreReader = reader;
_coreReaderNSResolver = reader as IXmlNamespaceResolver;
_coreReaderImpl = reader as XmlTextReaderImpl;
if (_coreReaderImpl == null)
{
XmlTextReader tr = reader as XmlTextReader;
if (tr != null)
{
_coreReaderImpl = tr.Impl;
}
}
if (_coreReaderImpl == null)
{
throw new ArgumentException(SR.Arg_ExpectingXmlTextReader, "reader");
}
_coreReaderImpl.EntityHandling = EntityHandling.ExpandEntities;
_coreReaderImpl.XmlValidatingReaderCompatibilityMode = true;
_processIdentityConstraints = true;
#pragma warning disable 618
_schemaCollection = new XmlSchemaCollection(_coreReader.NameTable);
_schemaCollection.XmlResolver = GetResolver();
_eventHandling = new ValidationEventHandling(this);
_coreReaderImpl.ValidationEventHandling = _eventHandling;
_coreReaderImpl.OnDefaultAttributeUse = new XmlTextReaderImpl.OnDefaultAttributeUseDelegate(ValidateDefaultAttributeOnUse);
_validationType = ValidationType.Auto;
SetupValidation(ValidationType.Auto);
#pragma warning restore 618
}
// Initializes a new instance of XmlValidatingReaderImpl class for parsing fragments with the specified string, fragment type and parser context
// This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader
// SxS: This method resolves an Uri but does not expose it to the caller. It's OK to suppress the SxS warning.
internal XmlValidatingReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext context)
: this(new XmlTextReader(xmlFragment, fragType, context))
{
if (_coreReader.BaseURI.Length > 0)
{
_validator.BaseUri = GetResolver().ResolveUri(null, _coreReader.BaseURI);
}
if (context != null)
{
_parsingFunction = ParsingFunction.ParseDtdFromContext;
_parserContext = context;
}
}
// Initializes a new instance of XmlValidatingReaderImpl class for parsing fragments with the specified stream, fragment type and parser context
// This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader
// SxS: This method resolves an Uri but does not expose it to the caller. It's OK to suppress the SxS warning.
internal XmlValidatingReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)
: this(new XmlTextReader(xmlFragment, fragType, context))
{
if (_coreReader.BaseURI.Length > 0)
{
_validator.BaseUri = GetResolver().ResolveUri(null, _coreReader.BaseURI);
}
if (context != null)
{
_parsingFunction = ParsingFunction.ParseDtdFromContext;
_parserContext = context;
}
}
// Initializes a new instance of XmlValidatingReaderImpl class with the specified arguments.
// This constructor is used when creating XmlValidatingReaderImpl reader via "XmlReader.Create(..)"
internal XmlValidatingReaderImpl(XmlReader reader, ValidationEventHandler settingsEventHandler, bool processIdentityConstraints)
{
XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader;
if (asyncCheckReader != null)
{
reader = asyncCheckReader.CoreReader;
}
_outerReader = this;
_coreReader = reader;
_coreReaderImpl = reader as XmlTextReaderImpl;
if (_coreReaderImpl == null)
{
XmlTextReader tr = reader as XmlTextReader;
if (tr != null)
{
_coreReaderImpl = tr.Impl;
}
}
if (_coreReaderImpl == null)
{
throw new ArgumentException(SR.Arg_ExpectingXmlTextReader, "reader");
}
_coreReaderImpl.XmlValidatingReaderCompatibilityMode = true;
_coreReaderNSResolver = reader as IXmlNamespaceResolver;
_processIdentityConstraints = processIdentityConstraints;
#pragma warning disable 618
_schemaCollection = new XmlSchemaCollection(_coreReader.NameTable);
#pragma warning restore 618
_schemaCollection.XmlResolver = GetResolver();
_eventHandling = new ValidationEventHandling(this);
if (settingsEventHandler != null)
{
_eventHandling.AddHandler(settingsEventHandler);
}
_coreReaderImpl.ValidationEventHandling = _eventHandling;
_coreReaderImpl.OnDefaultAttributeUse = new XmlTextReaderImpl.OnDefaultAttributeUseDelegate(ValidateDefaultAttributeOnUse);
_validationType = ValidationType.DTD;
SetupValidation(ValidationType.DTD);
}
//
// XmlReader members
//
// Returns the current settings of the reader
public override XmlReaderSettings Settings
{
get
{
XmlReaderSettings settings;
if (_coreReaderImpl.V1Compat)
{
settings = null;
}
else
{
settings = _coreReader.Settings;
}
if (settings != null)
{
settings = settings.Clone();
}
else
{
settings = new XmlReaderSettings();
}
settings.ValidationType = ValidationType.DTD;
if (!_processIdentityConstraints)
{
settings.ValidationFlags &= ~XmlSchemaValidationFlags.ProcessIdentityConstraints;
}
settings.ReadOnly = true;
return settings;
}
}
// Returns the type of the current node.
public override XmlNodeType NodeType
{
get
{
return _coreReader.NodeType;
}
}
// Returns the name of the current node, including prefix.
public override string Name
{
get
{
return _coreReader.Name;
}
}
// Returns local name of the current node (without prefix)
public override string LocalName
{
get
{
return _coreReader.LocalName;
}
}
// Returns namespace name of the current node.
public override string NamespaceURI
{
get
{
return _coreReader.NamespaceURI;
}
}
// Returns prefix associated with the current node.
public override string Prefix
{
get
{
return _coreReader.Prefix;
}
}
// Returns true if the current node can have Value property != string.Empty.
public override bool HasValue
{
get
{
return _coreReader.HasValue;
}
}
// Returns the text value of the current node.
public override string Value
{
get
{
return _coreReader.Value;
}
}
// Returns the depth of the current node in the XML element stack
public override int Depth
{
get
{
return _coreReader.Depth;
}
}
// Returns the base URI of the current node.
public override string BaseURI
{
get
{
return _coreReader.BaseURI;
}
}
// Returns true if the current node is an empty element (for example, <MyElement/>).
public override bool IsEmptyElement
{
get
{
return _coreReader.IsEmptyElement;
}
}
// Returns true of the current node is a default attribute declared in DTD.
public override bool IsDefault
{
get
{
return _coreReader.IsDefault;
}
}
// Returns the quote character used in the current attribute declaration
public override char QuoteChar
{
get
{
return _coreReader.QuoteChar;
}
}
// Returns the current xml:space scope.
public override XmlSpace XmlSpace
{
get
{
return _coreReader.XmlSpace;
}
}
// Returns the current xml:lang scope.</para>
public override string XmlLang
{
get
{
return _coreReader.XmlLang;
}
}
// Returns the current read state of the reader
public override ReadState ReadState
{
get
{
return (_parsingFunction == ParsingFunction.Init) ? ReadState.Initial : _coreReader.ReadState;
}
}
// Returns true if the reader reached end of the input data
public override bool EOF
{
get
{
return _coreReader.EOF;
}
}
// Returns the XmlNameTable associated with this XmlReader
public override XmlNameTable NameTable
{
get
{
return _coreReader.NameTable;
}
}
// Returns encoding of the XML document
internal Encoding Encoding
{
get
{
return _coreReaderImpl.Encoding;
}
}
// Returns the number of attributes on the current node.
public override int AttributeCount
{
get
{
return _coreReader.AttributeCount;
}
}
// Returns value of an attribute with the specified Name
public override string GetAttribute(string name)
{
return _coreReader.GetAttribute(name);
}
// Returns value of an attribute with the specified LocalName and NamespaceURI
public override string GetAttribute(string localName, string namespaceURI)
{
return _coreReader.GetAttribute(localName, namespaceURI);
}
// Returns value of an attribute at the specified index (position)
public override string GetAttribute(int i)
{
return _coreReader.GetAttribute(i);
}
// Moves to an attribute with the specified Name
public override bool MoveToAttribute(string name)
{
if (!_coreReader.MoveToAttribute(name))
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Moves to an attribute with the specified LocalName and NamespceURI
public override bool MoveToAttribute(string localName, string namespaceURI)
{
if (!_coreReader.MoveToAttribute(localName, namespaceURI))
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Moves to an attribute at the specified index (position)
public override void MoveToAttribute(int i)
{
_coreReader.MoveToAttribute(i);
_parsingFunction = ParsingFunction.Read;
}
// Moves to the first attribute of the current node
public override bool MoveToFirstAttribute()
{
if (!_coreReader.MoveToFirstAttribute())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Moves to the next attribute of the current node
public override bool MoveToNextAttribute()
{
if (!_coreReader.MoveToNextAttribute())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// If on attribute, moves to the element that contains the attribute node
public override bool MoveToElement()
{
if (!_coreReader.MoveToElement())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Reads and validated next node from the input data
public override bool Read()
{
switch (_parsingFunction)
{
case ParsingFunction.Read:
if (_coreReader.Read())
{
ProcessCoreReaderEvent();
return true;
}
else
{
_validator.CompleteValidation();
return false;
}
case ParsingFunction.ParseDtdFromContext:
_parsingFunction = ParsingFunction.Read;
ParseDtdFromParserContext();
goto case ParsingFunction.Read;
case ParsingFunction.Error:
case ParsingFunction.ReaderClosed:
return false;
case ParsingFunction.Init:
_parsingFunction = ParsingFunction.Read; // this changes the value returned by ReadState
if (_coreReader.ReadState == ReadState.Interactive)
{
ProcessCoreReaderEvent();
return true;
}
else
{
goto case ParsingFunction.Read;
}
case ParsingFunction.ResolveEntityInternally:
_parsingFunction = ParsingFunction.Read;
ResolveEntityInternally();
goto case ParsingFunction.Read;
case ParsingFunction.InReadBinaryContent:
_parsingFunction = ParsingFunction.Read;
_readBinaryHelper.Finish();
goto case ParsingFunction.Read;
default:
Debug.Assert(false);
return false;
}
}
// Closes the input stream ot TextReader, changes the ReadState to Closed and sets all properties to zero/string.Empty
public override void Close()
{
_coreReader.Close();
_parsingFunction = ParsingFunction.ReaderClosed;
}
// Returns NamespaceURI associated with the specified prefix in the current namespace scope.
public override String LookupNamespace(String prefix)
{
return _coreReaderImpl.LookupNamespace(prefix);
}
// Iterates through the current attribute value's text and entity references chunks.
public override bool ReadAttributeValue()
{
if (_parsingFunction == ParsingFunction.InReadBinaryContent)
{
_parsingFunction = ParsingFunction.Read;
_readBinaryHelper.Finish();
}
if (!_coreReader.ReadAttributeValue())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
public override bool CanReadBinaryContent
{
get
{
return true;
}
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper if called the first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = _readBinaryHelper.ReadContentAsBase64(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper when called first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = _readBinaryHelper.ReadContentAsBinHex(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper if called the first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = _readBinaryHelper.ReadElementContentAsBase64(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper when called first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = _readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
// Returns true if the XmlReader knows how to resolve general entities
public override bool CanResolveEntity
{
get
{
return true;
}
}
// Resolves the current entity reference node
public override void ResolveEntity()
{
if (_parsingFunction == ParsingFunction.ResolveEntityInternally)
{
_parsingFunction = ParsingFunction.Read;
}
_coreReader.ResolveEntity();
}
internal XmlReader OuterReader
{
get
{
return _outerReader;
}
set
{
#pragma warning disable 618
Debug.Assert(value is XmlValidatingReader);
#pragma warning restore 618
_outerReader = value;
}
}
internal void MoveOffEntityReference()
{
if (_outerReader.NodeType == XmlNodeType.EntityReference && _parsingFunction != ParsingFunction.ResolveEntityInternally)
{
if (!_outerReader.Read())
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
}
}
public override string ReadString()
{
MoveOffEntityReference();
return base.ReadString();
}
//
// IXmlLineInfo members
//
public bool HasLineInfo()
{
return true;
}
// Returns the line number of the current node
public int LineNumber
{
get
{
return ((IXmlLineInfo)_coreReader).LineNumber;
}
}
// Returns the line number of the current node
public int LinePosition
{
get
{
return ((IXmlLineInfo)_coreReader).LinePosition;
}
}
//
// IXmlNamespaceResolver members
//
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return this.GetNamespacesInScope(scope);
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return this.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return this.LookupPrefix(namespaceName);
}
// Internal IXmlNamespaceResolver methods
internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
return _coreReaderNSResolver.GetNamespacesInScope(scope);
}
internal string LookupPrefix(string namespaceName)
{
return _coreReaderNSResolver.LookupPrefix(namespaceName);
}
//
// XmlValidatingReader members
//
// Specufies the validation event handler that wil get warnings and errors related to validation
internal event ValidationEventHandler ValidationEventHandler
{
add
{
_eventHandling.AddHandler(value);
}
remove
{
_eventHandling.RemoveHandler(value); ;
}
}
// returns the schema type of the current node
internal object SchemaType
{
get
{
if (_validationType != ValidationType.None)
{
XmlSchemaType schemaTypeObj = _coreReaderImpl.InternalSchemaType as XmlSchemaType;
if (schemaTypeObj != null && schemaTypeObj.QualifiedName.Namespace == XmlReservedNs.NsXs)
{
return schemaTypeObj.Datatype;
}
return _coreReaderImpl.InternalSchemaType;
}
else
return null;
}
}
// returns the underlying XmlTextReader or XmlTextReaderImpl
internal XmlReader Reader
{
get
{
return (XmlReader)_coreReader;
}
}
// returns the underlying XmlTextReaderImpl
internal XmlTextReaderImpl ReaderImpl
{
get
{
return _coreReaderImpl;
}
}
// specifies the validation type (None, DDT, XSD, XDR, Auto)
internal ValidationType ValidationType
{
get
{
return _validationType;
}
set
{
if (ReadState != ReadState.Initial)
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
_validationType = value;
SetupValidation(value);
}
}
// current schema collection used for validationg
#pragma warning disable 618
internal XmlSchemaCollection Schemas
{
get
{
return _schemaCollection;
}
}
#pragma warning restore 618
// Spefifies whether general entities should be automatically expanded or not
internal EntityHandling EntityHandling
{
get
{
return _coreReaderImpl.EntityHandling;
}
set
{
_coreReaderImpl.EntityHandling = value;
}
}
// Specifies XmlResolver used for opening the XML document and other external references
internal XmlResolver XmlResolver
{
set
{
_coreReaderImpl.XmlResolver = value;
_validator.XmlResolver = value;
_schemaCollection.XmlResolver = value;
}
}
// Disables or enables support of W3C XML 1.0 Namespaces
internal bool Namespaces
{
get
{
return _coreReaderImpl.Namespaces;
}
set
{
_coreReaderImpl.Namespaces = value;
}
}
// Returns typed value of the current node (based on the type specified by schema)
public object ReadTypedValue()
{
if (_validationType == ValidationType.None)
{
return null;
}
switch (_outerReader.NodeType)
{
case XmlNodeType.Attribute:
return _coreReaderImpl.InternalTypedValue;
case XmlNodeType.Element:
if (SchemaType == null)
{
return null;
}
XmlSchemaDatatype dtype = (SchemaType is XmlSchemaDatatype) ? (XmlSchemaDatatype)SchemaType : ((XmlSchemaType)SchemaType).Datatype;
if (dtype != null)
{
if (!_outerReader.IsEmptyElement)
{
for (;;)
{
if (!_outerReader.Read())
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
XmlNodeType type = _outerReader.NodeType;
if (type != XmlNodeType.CDATA && type != XmlNodeType.Text &&
type != XmlNodeType.Whitespace && type != XmlNodeType.SignificantWhitespace &&
type != XmlNodeType.Comment && type != XmlNodeType.ProcessingInstruction)
{
break;
}
}
if (_outerReader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_InvalidNodeType, _outerReader.NodeType.ToString());
}
}
return _coreReaderImpl.InternalTypedValue;
}
return null;
case XmlNodeType.EndElement:
return null;
default:
if (_coreReaderImpl.V1Compat)
{ //If v1 XmlValidatingReader return null
return null;
}
else
{
return Value;
}
}
}
//
// Private implementation methods
//
private void ParseDtdFromParserContext()
{
Debug.Assert(_parserContext != null);
Debug.Assert(_coreReaderImpl.DtdInfo == null);
if (_parserContext.DocTypeName == null || _parserContext.DocTypeName.Length == 0)
{
return;
}
IDtdParser dtdParser = DtdParser.Create();
XmlTextReaderImpl.DtdParserProxy proxy = new XmlTextReaderImpl.DtdParserProxy(_coreReaderImpl);
IDtdInfo dtdInfo = dtdParser.ParseFreeFloatingDtd(_parserContext.BaseURI, _parserContext.DocTypeName, _parserContext.PublicId,
_parserContext.SystemId, _parserContext.InternalSubset, proxy);
_coreReaderImpl.SetDtdInfo(dtdInfo);
ValidateDtd();
}
private void ValidateDtd()
{
IDtdInfo dtdInfo = _coreReaderImpl.DtdInfo;
if (dtdInfo != null)
{
switch (_validationType)
{
#pragma warning disable 618
case ValidationType.Auto:
SetupValidation(ValidationType.DTD);
goto case ValidationType.DTD;
#pragma warning restore 618
case ValidationType.DTD:
case ValidationType.None:
_validator.DtdInfo = dtdInfo;
break;
}
}
}
private void ResolveEntityInternally()
{
Debug.Assert(_coreReader.NodeType == XmlNodeType.EntityReference);
int initialDepth = _coreReader.Depth;
_outerReader.ResolveEntity();
while (_outerReader.Read() && _coreReader.Depth > initialDepth) ;
}
// SxS: This method resolves an Uri but does not expose it to caller. It's OK to suppress the SxS warning.
private void SetupValidation(ValidationType valType)
{
_validator = BaseValidator.CreateInstance(valType, this, _schemaCollection, _eventHandling, _processIdentityConstraints);
XmlResolver resolver = GetResolver();
_validator.XmlResolver = resolver;
if (_outerReader.BaseURI.Length > 0)
{
_validator.BaseUri = (resolver == null) ? new Uri(_outerReader.BaseURI, UriKind.RelativeOrAbsolute) : resolver.ResolveUri(null, _outerReader.BaseURI);
}
_coreReaderImpl.ValidationEventHandling = (_validationType == ValidationType.None) ? null : _eventHandling;
}
private static XmlResolver s_tempResolver;
// This is needed because we can't have the setter for XmlResolver public and with internal getter.
private XmlResolver GetResolver()
{
XmlResolver tempResolver = _coreReaderImpl.GetResolver();
if (tempResolver == null && !_coreReaderImpl.IsResolverSet &&
!System.Xml.XmlReaderSettings.EnableLegacyXmlSettings())
{
// it is safe to return valid resolver as it'll be used in the schema validation
if (s_tempResolver == null)
s_tempResolver = new XmlUrlResolver();
return s_tempResolver;
}
return tempResolver;
}
//
// Internal methods for validators, DOM, XPathDocument etc.
//
private void ProcessCoreReaderEvent()
{
switch (_coreReader.NodeType)
{
case XmlNodeType.Whitespace:
if (_coreReader.Depth > 0 || _coreReaderImpl.FragmentType != XmlNodeType.Document)
{
if (_validator.PreserveWhitespace)
{
_coreReaderImpl.ChangeCurrentNodeType(XmlNodeType.SignificantWhitespace);
}
}
goto default;
case XmlNodeType.DocumentType:
ValidateDtd();
break;
case XmlNodeType.EntityReference:
_parsingFunction = ParsingFunction.ResolveEntityInternally;
goto default;
default:
_coreReaderImpl.InternalSchemaType = null;
_coreReaderImpl.InternalTypedValue = null;
_validator.Validate();
break;
}
}
internal void Close(bool closeStream)
{
_coreReaderImpl.Close(closeStream);
_parsingFunction = ParsingFunction.ReaderClosed;
}
internal BaseValidator Validator
{
get
{
return _validator;
}
set
{
_validator = value;
}
}
internal override XmlNamespaceManager NamespaceManager
{
get
{
return _coreReaderImpl.NamespaceManager;
}
}
internal bool StandAlone
{
get
{
return _coreReaderImpl.StandAlone;
}
}
internal object SchemaTypeObject
{
set
{
_coreReaderImpl.InternalSchemaType = value;
}
}
internal object TypedValueObject
{
get
{
return _coreReaderImpl.InternalTypedValue;
}
set
{
_coreReaderImpl.InternalTypedValue = value;
}
}
internal bool Normalization
{
get
{
return _coreReaderImpl.Normalization;
}
}
internal bool AddDefaultAttribute(SchemaAttDef attdef)
{
return _coreReaderImpl.AddDefaultAttributeNonDtd(attdef);
}
internal override IDtdInfo DtdInfo
{
get { return _coreReaderImpl.DtdInfo; }
}
internal void ValidateDefaultAttributeOnUse(IDtdDefaultAttributeInfo defaultAttribute, XmlTextReaderImpl coreReader)
{
SchemaAttDef attdef = defaultAttribute as SchemaAttDef;
if (attdef == null)
{
return;
}
if (!attdef.DefaultValueChecked)
{
SchemaInfo schemaInfo = coreReader.DtdInfo as SchemaInfo;
if (schemaInfo == null)
{
return;
}
DtdValidator.CheckDefaultValue(attdef, schemaInfo, _eventHandling, coreReader.BaseURI);
}
}
}
}
| |
/*
*
* (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.MessagingSystem
{
public enum MessageAction
{
None = -1,
#region Login
LoginSuccess = 1000,
LoginSuccessViaSocialAccount = 1001,
LoginSuccessViaSms = 1007,
LoginSuccessViaApi = 1010,
LoginSuccessViaSocialApp = 1011,
LoginSuccessViaApiSms = 1012,
LoginSuccessViaApiTfa = 1024,
LoginSuccessViaApiSocialAccount = 1019,
LoginSuccessViaSSO = 1015,
LoginSuccesViaTfaApp = 1021,
LoginFailViaSSO = 1018,
LoginFailInvalidCombination = 1002,
LoginFailSocialAccountNotFound = 1003,
LoginFailDisabledProfile = 1004,
LoginFail = 1005,
LoginFailViaSms = 1008,
LoginFailViaApi = 1013,
LoginFailViaApiSms = 1014,
LoginFailViaApiTfa = 1025,
LoginFailViaApiSocialAccount = 1020,
LoginFailViaTfaApp = 1022,
LoginFailIpSecurity = 1009,
LoginFailBruteForce = 1023,
LoginFailRecaptcha = 1026, // last login
Logout = 1006,
SessionStarted = 1016,
SessionCompleted = 1017,
#endregion
#region Projects
ProjectCreated = 2000,
ProjectCreatedFromTemplate = 2001,
ProjectUpdated = 2002,
ProjectUpdatedStatus = 2003,
ProjectFollowed = 2004,
ProjectUnfollowed = 2005,
ProjectDeleted = 2006,
ProjectDeletedMember = 2007,
ProjectUpdatedTeam = 2008,
ProjectUpdatedMemberRights = 2009,
ProjectLinkedCompany = 2010,
ProjectUnlinkedCompany = 2011,
ProjectLinkedPerson = 2012,
ProjectUnlinkedPerson = 2013,
ProjectLinkedContacts = 2014,
MilestoneCreated = 2015,
MilestoneUpdated = 2016,
MilestoneUpdatedStatus = 2017,
MilestoneDeleted = 2018,
TaskCreated = 2019,
TaskCreatedFromDiscussion = 2020,
TaskUpdated = 2021,
TaskUpdatedStatus = 2022,
TaskMovedToMilestone = 2023,
TaskUnlinkedMilestone = 2024,
TaskUpdatedFollowing = 2025,
TaskAttachedFiles = 2026,
TaskDetachedFile = 2027,
TasksLinked = 2028,
TasksUnlinked = 2029,
TaskDeleted = 2030,
TaskCommentCreated = 2031,
TaskCommentUpdated = 2032,
TaskCommentDeleted = 2033,
SubtaskCreated = 2034,
SubtaskUpdated = 2035,
SubtaskUpdatedStatus = 2036,
SubtaskDeleted = 2037,
DiscussionCreated = 2038,
DiscussionUpdated = 2039,
DiscussionUpdatedFollowing = 2040,
DiscussionAttachedFiles = 2041,
DiscussionDetachedFile = 2042,
DiscussionDeleted = 2043,
DiscussionCommentCreated = 2044,
DiscussionCommentUpdated = 2045,
DiscussionCommentDeleted = 2046,
TaskTimeCreated = 2047,
TaskTimeUpdated = 2048,
TaskTimesUpdatedStatus = 2049,
TaskTimesDeleted = 2050,
ReportTemplateCreated = 2051,
ReportTemplateUpdated = 2052,
ReportTemplateDeleted = 2053,
ProjectTemplateCreated = 2054,
ProjectTemplateUpdated = 2055,
ProjectTemplateDeleted = 2056,
ProjectsImportedFromBasecamp = 2057,
#endregion
#region CRM
CompanyCreated = 3000,
CompanyCreatedWithWebForm = 3157,
CompanyUpdated = 3001,
CompanyUpdatedPrincipalInfo = 3002,
CompanyUpdatedPhoto = 3003,
CompanyUpdatedTemperatureLevel = 3004,
CompanyUpdatedPersonsTemperatureLevel = 3005,
CompanyCreatedTag = 3006,
CompanyCreatedPersonsTag = 3007,
CompanyDeletedTag = 3008,
CompanyCreatedHistoryEvent = 3009,
CompanyDeletedHistoryEvent = 3010,
CompanyLinkedPerson = 3011,
CompanyUnlinkedPerson = 3012,
CompanyLinkedProject = 3013,
CompanyUnlinkedProject = 3014,
CompanyAttachedFiles = 3015,
CompanyDetachedFile = 3159,
CompaniesMerged = 3016,
CompanyDeleted = 3017,
PersonCreated = 3018,
PersonCreatedWithWebForm = 3158,
PersonsCreated = 3019,
PersonUpdated = 3020,
PersonUpdatedPrincipalInfo = 3021,
PersonUpdatedPhoto = 3022,
PersonUpdatedTemperatureLevel = 3023,
PersonUpdatedCompanyTemperatureLevel = 3024,
PersonCreatedTag = 3025,
PersonCreatedCompanyTag = 3026,
PersonDeletedTag = 3027,
PersonCreatedHistoryEvent = 3028,
PersonDeletedHistoryEvent = 3029,
PersonLinkedProject = 3030,
PersonUnlinkedProject = 3031,
PersonAttachedFiles = 3032,
PersonDetachedFile = 3160,
PersonsMerged = 3033,
PersonDeleted = 3034,
ContactsDeleted = 3035,
CrmTaskCreated = 3036,
ContactsCreatedCrmTasks = 3037,
CrmTaskUpdated = 3038,
CrmTaskOpened = 3039,
CrmTaskClosed = 3040,
CrmTaskDeleted = 3041,
OpportunityCreated = 3042,
OpportunityUpdated = 3043,
OpportunityUpdatedStage = 3044,
OpportunityCreatedTag = 3045,
OpportunityDeletedTag = 3046,
OpportunityCreatedHistoryEvent = 3047,
OpportunityDeletedHistoryEvent = 3048,
OpportunityLinkedCompany = 3049,
OpportunityUnlinkedCompany = 3050,
OpportunityLinkedPerson = 3051,
OpportunityUnlinkedPerson = 3052,
OpportunityAttachedFiles = 3053,
OpportunityDetachedFile = 3161,
OpportunityOpenedAccess = 3054,
OpportunityRestrictedAccess = 3055,
OpportunityDeleted = 3056,
OpportunitiesDeleted = 3057,
InvoiceCreated = 3058,
InvoiceUpdated = 3059,
InvoicesUpdatedStatus = 3060,
InvoiceDeleted = 3061,
InvoicesDeleted = 3062,
CaseCreated = 3063,
CaseUpdated = 3064,
CaseOpened = 3065,
CaseClosed = 3066,
CaseCreatedTag = 3067,
CaseDeletedTag = 3068,
CaseCreatedHistoryEvent = 3069,
CaseDeletedHistoryEvent = 3070,
CaseLinkedCompany = 3071,
CaseUnlinkedCompany = 3072,
CaseLinkedPerson = 3073,
CaseUnlinkedPerson = 3074,
CaseAttachedFiles = 3075,
CaseDetachedFile = 3162,
CaseOpenedAccess = 3076,
CaseRestrictedAccess = 3077,
CaseDeleted = 3078,
CasesDeleted = 3079,
CrmSmtpSettingsUpdated = 3080,
CrmTestMailSent = 3081,
CrmDefaultCurrencyUpdated = 3082,
CrmAllDataExported = 3083,
ContactTemperatureLevelCreated = 3084,
ContactTemperatureLevelUpdated = 3085,
ContactTemperatureLevelUpdatedColor = 3086,
ContactTemperatureLevelsUpdatedOrder = 3087,
ContactTemperatureLevelDeleted = 3088,
ContactTemperatureLevelSettingsUpdated = 3089,
ContactTypeCreated = 3090,
ContactTypeUpdated = 3091,
ContactTypesUpdatedOrder = 3092,
ContactTypeDeleted = 3093,
InvoiceItemCreated = 3094,
InvoiceItemUpdated = 3095,
InvoiceItemDeleted = 3096,
InvoiceItemsDeleted = 3097,
InvoiceTaxCreated = 3098,
InvoiceTaxUpdated = 3099,
InvoiceTaxDeleted = 3100,
CurrencyRateUpdated = 3163,
InvoiceDefaultTermsUpdated = 3164,
InvoiceDownloaded = 3165,
CrmSmtpMailSent = 3166,
OrganizationProfileUpdatedCompanyName = 3101,
OrganizationProfileUpdatedInvoiceLogo = 3102,
OrganizationProfileUpdatedAddress = 3103,
InvoiceNumberFormatUpdated = 3104,
ContactUserFieldCreated = 3105,
ContactUserFieldUpdated = 3106,
ContactUserFieldsUpdatedOrder = 3107,
ContactUserFieldDeleted = 3108,
CompanyUserFieldCreated = 3109,
CompanyUserFieldUpdated = 3110,
CompanyUserFieldsUpdatedOrder = 3111,
CompanyUserFieldDeleted = 3112,
PersonUserFieldCreated = 3113,
PersonUserFieldUpdated = 3114,
PersonUserFieldsUpdatedOrder = 3115,
PersonUserFieldDeleted = 3116,
OpportunityUserFieldCreated = 3117,
OpportunityUserFieldUpdated = 3118,
OpportunityUserFieldsUpdatedOrder = 3119,
OpportunityUserFieldDeleted = 3120,
CaseUserFieldCreated = 3121,
CaseUserFieldUpdated = 3122,
CaseUserFieldsUpdatedOrder = 3123,
CaseUserFieldDeleted = 3124,
HistoryEventCategoryCreated = 3125,
HistoryEventCategoryUpdated = 3126,
HistoryEventCategoryUpdatedIcon = 3127,
HistoryEventCategoriesUpdatedOrder = 3128,
HistoryEventCategoryDeleted = 3129,
CrmTaskCategoryCreated = 3130,
CrmTaskCategoryUpdated = 3131,
CrmTaskCategoryUpdatedIcon = 3132,
CrmTaskCategoriesUpdatedOrder = 3133,
CrmTaskCategoryDeleted = 3134,
OpportunityStageCreated = 3135,
OpportunityStageUpdated = 3136,
OpportunityStageUpdatedColor = 3137,
OpportunityStagesUpdatedOrder = 3138,
OpportunityStageDeleted = 3139,
ContactsCreatedTag = 3140,
ContactsDeletedTag = 3141,
OpportunitiesCreatedTag = 3142,
OpportunitiesDeletedTag = 3143,
CasesCreatedTag = 3144,
CasesDeletedTag = 3145,
ContactsTagSettingsUpdated = 3146,
WebsiteContactFormUpdatedKey = 3147,
ContactsImportedFromCSV = 3148,
CrmTasksImportedFromCSV = 3149,
OpportunitiesImportedFromCSV = 3150,
CasesImportedFromCSV = 3151,
ContactsExportedToCsv = 3152,
CrmTasksExportedToCsv = 3153,
OpportunitiesExportedToCsv = 3154,
CasesExportedToCsv = 3155,
#endregion
#region People
UserCreated = 4000,
GuestCreated = 4001,
UserCreatedViaInvite = 4002,
GuestCreatedViaInvite = 4003,
UserActivated = 4004,
GuestActivated = 4005,
UserUpdated = 4006,
UserUpdatedMobileNumber = 4029,
UserUpdatedLanguage = 4007,
UserAddedAvatar = 4008,
UserDeletedAvatar = 4009,
UserUpdatedAvatarThumbnails = 4010,
UserLinkedSocialAccount = 4011,
UserUnlinkedSocialAccount = 4012,
UserConnectedTfaApp = 4032,
UserDisconnectedTfaApp = 4033,
UserSentActivationInstructions = 4013,
UserSentEmailChangeInstructions = 4014,
UserSentPasswordChangeInstructions = 4015,
UserSentDeleteInstructions = 4016,
UserUpdatedEmail = 5047,
UserUpdatedPassword = 4017,
UserDeleted = 4018,
UsersUpdatedType = 4019,
UsersUpdatedStatus = 4020,
UsersSentActivationInstructions = 4021,
UsersDeleted = 4022,
SentInviteInstructions = 4023,
UserImported = 4024,
GuestImported = 4025,
GroupCreated = 4026,
GroupUpdated = 4027,
GroupDeleted = 4028,
UserDataReassigns = 4030,
UserDataRemoving = 4031,
#endregion
#region Documents
FileCreated = 5000,
FileRenamed = 5001,
FileUpdated = 5002,
UserFileUpdated = 5034,
FileCreatedVersion = 5003,
FileDeletedVersion = 5004,
FileRestoreVersion = 5044,
FileUpdatedRevisionComment = 5005,
FileLocked = 5006,
FileUnlocked = 5007,
FileUpdatedAccess = 5008,
FileSendAccessLink = 5036, // not used
FileDownloaded = 5009,
FileDownloadedAs = 5010,
FileUploaded = 5011,
FileImported = 5012,
FileCopied = 5013,
FileCopiedWithOverwriting = 5014,
FileMoved = 5015,
FileMovedWithOverwriting = 5016,
FileMovedToTrash = 5017,
FileDeleted = 5018, // not used
FolderCreated = 5019,
FolderRenamed = 5020,
FolderUpdatedAccess = 5021,
FolderCopied = 5022,
FolderCopiedWithOverwriting = 5023,
FolderMoved = 5024,
FolderMovedWithOverwriting = 5025,
FolderMovedToTrash = 5026,
FolderDeleted = 5027, // not used
ThirdPartyCreated = 5028,
ThirdPartyUpdated = 5029,
ThirdPartyDeleted = 5030,
DocumentsThirdPartySettingsUpdated = 5031,
DocumentsOverwritingSettingsUpdated = 5032,
DocumentsForcesave = 5049,
DocumentsStoreForcesave = 5048,
DocumentsUploadingFormatsSettingsUpdated = 5033,
FileConverted = 5035,
FileChangeOwner = 5043,
DocumentSignComplete = 5046,
DocumentSendToSign = 5045,
#endregion
#region Settings
LanguageSettingsUpdated = 6000,
TimeZoneSettingsUpdated = 6001,
DnsSettingsUpdated = 6002,
TrustedMailDomainSettingsUpdated = 6003,
PasswordStrengthSettingsUpdated = 6004,
TwoFactorAuthenticationSettingsUpdated = 6005, // deprecated - use 6036-6038 instead
AdministratorMessageSettingsUpdated = 6006,
DefaultStartPageSettingsUpdated = 6007,
ProductsListUpdated = 6008,
AdministratorAdded = 6009,
AdministratorOpenedFullAccess = 6010,
AdministratorDeleted = 6011,
UsersOpenedProductAccess = 6012,
GroupsOpenedProductAccess = 6013,
ProductAccessOpened = 6014,
ProductAccessRestricted = 6015, // not used
ProductAddedAdministrator = 6016,
ProductDeletedAdministrator = 6017,
GreetingSettingsUpdated = 6018,
TeamTemplateChanged = 6019,
ColorThemeChanged = 6020,
OwnerSentChangeOwnerInstructions = 6021,
OwnerUpdated = 6022,
OwnerSentPortalDeactivationInstructions = 6023,
OwnerSentPortalDeleteInstructions = 6024,
PortalDeactivated = 6025,
PortalDeleted = 6026,
LoginHistoryReportDownloaded = 6027,
AuditTrailReportDownloaded = 6028,
SSOEnabled = 6029,
SSODisabled = 6030,
PortalAccessSettingsUpdated = 6031,
CookieSettingsUpdated = 6032,
MailServiceSettingsUpdated = 6033,
CustomNavigationSettingsUpdated = 6034,
AuditSettingsUpdated = 6035,
TwoFactorAuthenticationDisabled = 6036,
TwoFactorAuthenticationEnabledBySms = 6037,
TwoFactorAuthenticationEnabledByTfaApp = 6038,
DocumentServiceLocationSetting = 5037,
AuthorizationKeysSetting = 5038,
FullTextSearchSetting = 5039,
StartTransferSetting = 5040,
StartBackupSetting = 5041,
LicenseKeyUploaded = 5042,
StartStorageEncryption = 5050,
PrivacyRoomEnable = 5051,
PrivacyRoomDisable = 5052,
StartStorageDecryption = 5053, // last
#endregion
#region others
ContactAdminMailSent = 7000,
#endregion
#region Partners
AcceptRequest = 8000,
RejectRequest = 8001,
BlockPartner = 8002,
UnblockPartner = 8003,
DeletePartner = 8004,
ChangePartner = 8005,
ConfirmPortal = 8006,
MarkInvoicePaid = 8007,
MarkInvoiceUnpaid = 8008,
AddHostedPartner = 8009,
RemoveHostedPartner = 8010,
MarkPartnerAuthorized = 8011,
MarkPartnerNotAuthorized = 8012,
ChangePartnerLevel = 8013,
ChangeHostedPartnerQuotas = 8014,
ChangeHostedPartner = 8015,
BillLumpSumInvoice = 8016,
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.GoToDefinition;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices
{
[Export(typeof(VisualStudioWorkspace))]
[Export(typeof(VisualStudioWorkspaceImpl))]
internal class RoslynVisualStudioWorkspace : VisualStudioWorkspaceImpl
{
private readonly IEnumerable<Lazy<IStreamingFindUsagesPresenter>> _streamingPresenters;
private readonly IEnumerable<Lazy<IDefinitionsAndReferencesPresenter>> _referencedSymbolsPresenters;
[ImportingConstructor]
private RoslynVisualStudioWorkspace(
ExportProvider exportProvider,
[ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters,
[ImportMany] IEnumerable<Lazy<IDefinitionsAndReferencesPresenter>> referencedSymbolsPresenters,
[ImportMany] IEnumerable<IDocumentOptionsProviderFactory> documentOptionsProviderFactories)
: base(exportProvider.AsExportProvider())
{
_streamingPresenters = streamingPresenters;
_referencedSymbolsPresenters = referencedSymbolsPresenters;
foreach (var providerFactory in documentOptionsProviderFactories)
{
Services.GetRequiredService<IOptionService>().RegisterDocumentOptionsProvider(providerFactory.Create(this));
}
}
public override EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (DeferredState == null)
{
// We haven't gotten any projects added yet, so we don't know where this came from
throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
}
var project = DeferredState.ProjectTracker.GetProject(documentId.ProjectId);
if (project == null)
{
throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
}
var document = project.GetDocumentOrAdditionalDocument(documentId);
if (document == null)
{
throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
}
var provider = project as IProjectCodeModelProvider;
if (provider != null)
{
var projectCodeModel = provider.ProjectCodeModel;
if (projectCodeModel.CanCreateFileCodeModelThroughProject(document.FilePath))
{
return (EnvDTE.FileCodeModel)projectCodeModel.CreateFileCodeModelThroughProject(document.FilePath);
}
}
return null;
}
internal override bool RenameFileCodeModelInstance(DocumentId documentId, string newFilePath)
{
if (documentId == null)
{
return false;
}
var project = DeferredState.ProjectTracker.GetProject(documentId.ProjectId);
if (project == null)
{
return false;
}
var document = project.GetDocumentOrAdditionalDocument(documentId);
if (document == null)
{
return false;
}
var codeModelProvider = project as IProjectCodeModelProvider;
if (codeModelProvider == null)
{
return false;
}
var codeModelCache = codeModelProvider.ProjectCodeModel.GetCodeModelCache();
if (codeModelCache == null)
{
return false;
}
codeModelCache.OnSourceFileRenaming(document.FilePath, newFilePath);
return true;
}
internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId)
{
var hostDocument = GetHostDocument(documentId);
return OpenInvisibleEditor(hostDocument);
}
internal override IInvisibleEditor OpenInvisibleEditor(IVisualStudioHostDocument hostDocument)
{
var globalUndoService = this.Services.GetService<IGlobalUndoService>();
var needsUndoDisabled = false;
// Do not save the file if is open and there is not a global undo transaction.
var needsSave = globalUndoService.IsGlobalTransactionOpen(this) || !hostDocument.IsOpen;
if (needsSave)
{
if (this.CurrentSolution.ContainsDocument(hostDocument.Id))
{
// Disable undo on generated documents
needsUndoDisabled = this.CurrentSolution.GetDocument(hostDocument.Id).IsGeneratedCode(CancellationToken.None);
}
else
{
// Enable undo on "additional documents" or if no document can be found.
needsUndoDisabled = false;
}
}
return new InvisibleEditor(DeferredState.ServiceProvider, hostDocument.FilePath, needsSave, needsUndoDisabled);
}
private static bool TryResolveSymbol(ISymbol symbol, Project project, CancellationToken cancellationToken, out ISymbol resolvedSymbol, out Project resolvedProject)
{
resolvedSymbol = null;
resolvedProject = null;
var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id);
if (currentProject == null)
{
return false;
}
var originalCompilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolId = SymbolKey.Create(symbol, cancellationToken);
var currentCompilation = currentProject.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken);
if (symbolInfo.Symbol == null)
{
return false;
}
resolvedSymbol = symbolInfo.Symbol;
resolvedProject = currentProject;
return true;
}
public override bool TryGoToDefinition(
ISymbol symbol, Project project, CancellationToken cancellationToken)
{
if (!_streamingPresenters.Any())
{
return false;
}
if (!TryResolveSymbol(symbol, project, cancellationToken,
out var searchSymbol, out var searchProject))
{
return false;
}
return GoToDefinitionHelpers.TryGoToDefinition(
searchSymbol, searchProject,
_streamingPresenters, cancellationToken);
}
public override bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken)
{
if (!_referencedSymbolsPresenters.Any())
{
return false;
}
if (!TryResolveSymbol(symbol, project, cancellationToken, out var searchSymbol, out var searchProject))
{
return false;
}
var searchSolution = searchProject.Solution;
var result = SymbolFinder
.FindReferencesAsync(searchSymbol, searchSolution, cancellationToken)
.WaitAndGetResult(cancellationToken).ToList();
if (result != null)
{
DisplayReferencedSymbols(searchSolution, result);
return true;
}
return false;
}
public override void DisplayReferencedSymbols(
Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols)
{
var service = this.Services.GetService<IDefinitionsAndReferencesFactory>();
var definitionsAndReferences = service.CreateDefinitionsAndReferences(
solution, referencedSymbols,
includeHiddenLocations: false, cancellationToken: CancellationToken.None);
foreach (var presenter in _referencedSymbolsPresenters)
{
presenter.Value.DisplayResult(definitionsAndReferences);
return;
}
}
internal override object GetBrowseObject(SymbolListItem symbolListItem)
{
var compilation = symbolListItem.GetCompilation(this);
if (compilation == null)
{
return null;
}
var symbol = symbolListItem.ResolveSymbol(compilation);
var sourceLocation = symbol.Locations.Where(l => l.IsInSource).FirstOrDefault();
if (sourceLocation == null)
{
return null;
}
var projectId = symbolListItem.ProjectId;
if (projectId == null)
{
return null;
}
var project = this.CurrentSolution.GetProject(projectId);
if (project == null)
{
return null;
}
var codeModelService = project.LanguageServices.GetService<ICodeModelService>();
if (codeModelService == null)
{
return null;
}
var tree = sourceLocation.SourceTree;
var document = project.GetDocument(tree);
var vsFileCodeModel = this.GetFileCodeModel(document.Id);
var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(vsFileCodeModel);
if (fileCodeModel != null)
{
var syntaxNode = tree.GetRoot().FindNode(sourceLocation.SourceSpan);
while (syntaxNode != null)
{
if (!codeModelService.TryGetNodeKey(syntaxNode).IsEmpty)
{
break;
}
syntaxNode = syntaxNode.Parent;
}
if (syntaxNode != null)
{
var codeElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(syntaxNode);
if (codeElement != null)
{
return codeElement;
}
}
}
return null;
}
}
}
| |
using UnityEngine;
using System.Collections;
public enum LensflareStyle34 {
Ghosting = 0,
Anamorphic = 1,
Combined = 2,
}
public enum TweakMode34 {
Basic = 0,
Complex = 1,
}
public enum HDRBloomMode {
Auto = 0,
On = 1,
Off = 2,
}
public enum BloomScreenBlendMode {
Screen = 0,
Add = 1,
}
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
[AddComponentMenu ("Image Effects/Bloom and Glow/BloomAndFlares (3.5f, Deprecated)")]
public class BloomAndFlares : PostEffectsBase {
public TweakMode34 tweakMode = 0;
public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add;
public HDRBloomMode hdr = HDRBloomMode.Auto;
private bool doHdr = false;
public float sepBlurSpread = 1.5f;
public float useSrcAlphaAsMask = 0.5f;
public float bloomIntensity = 1.0f;
public float bloomThreshhold = 0.5f;
public int bloomBlurIterations = 2;
public bool lensflares = false;
public int hollywoodFlareBlurIterations = 2;
public LensflareStyle34 lensflareMode = (LensflareStyle34) 1;
public float hollyStretchWidth = 3.5f;
public float lensflareIntensity = 1.0f;
public float lensflareThreshhold = 0.3f;
public Color flareColorA = new Color (0.4f, 0.4f, 0.8f, 0.75f);
public Color flareColorB = new Color (0.4f, 0.8f, 0.8f, 0.75f);
public Color flareColorC = new Color (0.8f, 0.4f, 0.8f, 0.75f);
public Color flareColorD = new Color (0.8f, 0.4f, 0.0f, 0.75f);
public float blurWidth = 1.0f;
public Texture2D lensFlareVignetteMask;
public Shader lensFlareShader;
private Material lensFlareMaterial;
public Shader vignetteShader;
private Material vignetteMaterial;
public Shader separableBlurShader;
private Material separableBlurMaterial;
public Shader addBrightStuffOneOneShader;
private Material addBrightStuffBlendOneOneMaterial;
public Shader screenBlendShader;
private Material screenBlend;
public Shader hollywoodFlaresShader;
private Material hollywoodFlaresMaterial;
public Shader brightPassFilterShader;
private Material brightPassFilterMaterial;
public override bool CheckResources (){
CheckSupport (false);
screenBlend = CheckShaderAndCreateMaterial (screenBlendShader, screenBlend);
lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader,lensFlareMaterial);
vignetteMaterial = CheckShaderAndCreateMaterial(vignetteShader,vignetteMaterial);
separableBlurMaterial = CheckShaderAndCreateMaterial(separableBlurShader,separableBlurMaterial);
addBrightStuffBlendOneOneMaterial = CheckShaderAndCreateMaterial(addBrightStuffOneOneShader,addBrightStuffBlendOneOneMaterial);
hollywoodFlaresMaterial = CheckShaderAndCreateMaterial (hollywoodFlaresShader, hollywoodFlaresMaterial);
brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial);
if(!isSupported)
ReportAutoDisable ();
return isSupported;
}
void OnRenderImage ( RenderTexture source , RenderTexture destination ){
if(CheckResources()==false) {
Graphics.Blit (source, destination);
return;
}
// screen blend is not supported when HDR is enabled (will cap values)
doHdr = false;
if(hdr == HDRBloomMode.Auto)
doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr;
else {
doHdr = hdr == HDRBloomMode.On;
}
doHdr = doHdr && supportHDRTextures;
BloomScreenBlendMode realBlendMode = screenBlendMode;
if(doHdr)
realBlendMode = BloomScreenBlendMode.Add;
var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
RenderTexture halfRezColor = RenderTexture.GetTemporary (source.width / 2, source.height / 2, 0, rtFormat);
RenderTexture quarterRezColor = RenderTexture.GetTemporary (source.width / 4, source.height / 4, 0, rtFormat);
RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (source.width / 4, source.height / 4, 0, rtFormat);
RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary (source.width / 4, source.height / 4, 0, rtFormat);
float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
float oneOverBaseSize = 1.0f / 512.0f;
// downsample
Graphics.Blit (source, halfRezColor, screenBlend, 2); // <- 2 is stable downsample
Graphics.Blit (halfRezColor, quarterRezColor, screenBlend, 2); // <- 2 is stable downsample
RenderTexture.ReleaseTemporary (halfRezColor);
// cut colors (threshholding)
BrightFilter (bloomThreshhold, useSrcAlphaAsMask, quarterRezColor, secondQuarterRezColor);
quarterRezColor.DiscardContents();
// blurring
if (bloomBlurIterations < 1) bloomBlurIterations = 1;
for (int iter = 0; iter < bloomBlurIterations; iter++ ) {
float spreadForPass = (1.0f + (iter * 0.5f)) * sepBlurSpread;
separableBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f));
RenderTexture src = iter == 0 ? secondQuarterRezColor : quarterRezColor;
Graphics.Blit (src, thirdQuarterRezColor, separableBlurMaterial);
src.DiscardContents();
separableBlurMaterial.SetVector ("offsets", new Vector4 ((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit (thirdQuarterRezColor, quarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
// lens flares: ghosting, anamorphic or a combination
if (lensflares) {
if (lensflareMode == 0) {
BrightFilter (lensflareThreshhold, 0.0f, quarterRezColor, thirdQuarterRezColor);
quarterRezColor.DiscardContents();
// smooth a little, this needs to be resolution dependent
/*
separableBlurMaterial.SetVector ("offsets", Vector4 (0.0ff, (2.0ff) / (1.0ff * quarterRezColor.height), 0.0ff, 0.0ff));
Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
separableBlurMaterial.SetVector ("offsets", Vector4 ((2.0ff) / (1.0ff * quarterRezColor.width), 0.0ff, 0.0ff, 0.0ff));
Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
*/
// no ugly edges!
Vignette (0.975f, thirdQuarterRezColor, secondQuarterRezColor);
thirdQuarterRezColor.DiscardContents();
BlendFlares (secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
// (b) hollywood/anamorphic flares?
else {
// thirdQuarter has the brightcut unblurred colors
// quarterRezColor is the blurred, brightcut buffer that will end up as bloom
hollywoodFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshhold, 1.0f / (1.0f - lensflareThreshhold), 0.0f, 0.0f));
hollywoodFlaresMaterial.SetVector ("tintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 2);
thirdQuarterRezColor.DiscardContents();
Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 3);
secondQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetVector ("offsets", new Vector4 ((sepBlurSpread * 1.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
hollywoodFlaresMaterial.SetFloat ("stretchWidth", hollyStretchWidth);
Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
thirdQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetFloat ("stretchWidth", hollyStretchWidth * 2.0f);
Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 1);
secondQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetFloat ("stretchWidth", hollyStretchWidth * 4.0f);
Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
thirdQuarterRezColor.DiscardContents();
if (lensflareMode == (LensflareStyle34) 1) {
for (int itera = 0; itera < hollywoodFlareBlurIterations; itera++ ) {
separableBlurMaterial.SetVector ("offsets", new Vector4 ((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
secondQuarterRezColor.DiscardContents();
separableBlurMaterial.SetVector ("offsets", new Vector4 ((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
AddTo (1.0f, secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
else {
// (c) combined
for (int ix = 0; ix < hollywoodFlareBlurIterations; ix++ ) {
separableBlurMaterial.SetVector ("offsets", new Vector4 ((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
secondQuarterRezColor.DiscardContents();
separableBlurMaterial.SetVector ("offsets", new Vector4 ((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
Vignette (1.0f, secondQuarterRezColor, thirdQuarterRezColor);
secondQuarterRezColor.DiscardContents();
BlendFlares (thirdQuarterRezColor, secondQuarterRezColor);
thirdQuarterRezColor.DiscardContents();
AddTo (1.0f, secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
}
}
// screen blend bloom results to color buffer
screenBlend.SetFloat ("_Intensity", bloomIntensity);
screenBlend.SetTexture ("_ColorBuffer", source);
Graphics.Blit (quarterRezColor, destination, screenBlend, (int) realBlendMode);
RenderTexture.ReleaseTemporary (quarterRezColor);
RenderTexture.ReleaseTemporary (secondQuarterRezColor);
RenderTexture.ReleaseTemporary (thirdQuarterRezColor);
}
private void AddTo ( float intensity_ , RenderTexture from , RenderTexture to ){
addBrightStuffBlendOneOneMaterial.SetFloat ("_Intensity", intensity_);
Graphics.Blit (from, to, addBrightStuffBlendOneOneMaterial);
}
private void BlendFlares ( RenderTexture from , RenderTexture to ){
lensFlareMaterial.SetVector ("colorA",new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorB",new Vector4 (flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorC",new Vector4 (flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity);
lensFlareMaterial.SetVector ("colorD",new Vector4 (flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity);
Graphics.Blit (from, to, lensFlareMaterial);
}
private void BrightFilter ( float thresh , float useAlphaAsMask , RenderTexture from , RenderTexture to ){
if(doHdr)
brightPassFilterMaterial.SetVector ("threshhold", new Vector4 (thresh, 1.0f, 0.0f, 0.0f));
else
brightPassFilterMaterial.SetVector ("threshhold", new Vector4 (thresh, 1.0f / (1.0f-thresh), 0.0f, 0.0f));
brightPassFilterMaterial.SetFloat ("useSrcAlphaAsMask", useAlphaAsMask);
Graphics.Blit (from, to, brightPassFilterMaterial);
}
private void Vignette ( float amount , RenderTexture from , RenderTexture to ){
if(lensFlareVignetteMask) {
screenBlend.SetTexture ("_ColorBuffer", lensFlareVignetteMask);
Graphics.Blit (from, to, screenBlend, 3);
}
else {
vignetteMaterial.SetFloat ("vignetteIntensity", amount);
Graphics.Blit (from, to, vignetteMaterial);
}
}
}
| |
/*
* A base class for all List memory data structures.
*
* Prototype and logging information that would be considered "standard" will start
* here.
*
* This should allow us to reuse comparators for multiple data structures.
*
* TODO: Consider putting saving and loading crap into this
*/
using System;
using MasterLogFile;
namespace MasterDataStructureBase
{
public class DataStructureBase : PassThroughLoggedClass
{
//This is so we can override the current node business
protected DataNode _CurrentNode;
//The overridable property
public virtual DataNode CurrentNode
{
get { return this._CurrentNode; }
set { } //Nothing now, but we want to be able to override it.
}
public long CurrentNodeIndex
{
get
{
if (this._NodeCount > 0)
return this.CurrentNode.Index;
else
return 0;
}
}
// The number of items in the data structure
protected long _NodeCount;
//Default statistics for a data structure
protected long _SearchCount; //Number of searches
protected long _SearchMatchCount; //Number of matches resulting from searches
protected long _NavigationCount; //Number of navigation calls made (movefirst, etc)
//Extended statistics
protected long _AddCount; //Number of inserts
protected long _DeleteCount; //Number of deletes
//Logging options
protected bool _LogSearch; //Time and log each search
protected bool _LogNavigation; //Log each navigation function (WAY HUGE log files)
//Extended logging options
protected bool _LogAdd; //Log each add (can make log files HUGE)
protected bool _LogDelete; //Log each delete operation
// The Auto Incriment key
protected long _LastGivenIndex;
public DataStructureBase ()
{
//Initialize the list count
this._NodeCount = 0;
//Reset the statistics
this._SearchCount = 0;
this._SearchMatchCount = 0;
this._NavigationCount = 0;
this._AddCount = 0;
this._DeleteCount = 0;
this._LogSearch = false;
this._LogNavigation = false;
this._LogAdd = false;
this._LogDelete = false;
//The list is empty. Zero everything out!
this._LastGivenIndex = 0;
}
#region Data Access Functions
/// <summary>
/// The list count
/// </summary>
public long Count
{
get { return this._NodeCount; }
}
public long StatisticSearchCount
{
get { return this._SearchCount; }
}
public long StatisticSearchMatchCount
{
get { return this._SearchMatchCount; }
}
public long StatisticNavigationCount
{
get { return this._NavigationCount; }
}
public long StatisticAddCount
{
get { return this._AddCount; }
}
public long StatisticDeleteCount
{
get { return this._DeleteCount; }
}
public bool LogAllSearches
{
get { return this._LogSearch; }
set { this._LogSearch = value; }
}
public bool LogAllNavigation
{
get { return this._LogNavigation; }
set { this._LogNavigation = value; }
}
public bool LogAllAdds
{
get { return this._LogAdd; }
set { this._LogAdd = value; }
}
public bool LogAllDeletes
{
get { return this._LogDelete; }
set { this._LogDelete = value; }
}
#endregion
}
public class DataNode
{
//The primary key
private long _NodeIndex;
//The data gram
private object _NodeData;
//The constructor
public DataNode ( object pNodeData )
{
this._NodeData = pNodeData;
}
#region Data Access Functions
/// <summary>
/// The primary key for the list node.
/// </summary>
public long Index
{
get { return this._NodeIndex; }
set { this._NodeIndex = value; }
}
public object NodeData
{
get { return this._NodeData; }
set { this._NodeData = value; }
}
#endregion
}
public class NodeMatch
{
//The key to match
private long _NodeIndex;
public NodeMatch ()
{
//Do nothing
this._NodeIndex = 0;
}
public NodeMatch ( long pNodeIndexToFind )
{
this._NodeIndex = pNodeIndexToFind;
}
/// <summary>
/// Compare two nodes.
/// Return -1 for Left < Right
/// Return 0 for Left = Right
/// Return 1 for Left > Right
/// </summary>
/// <param name="Left_Node_Value">Left Comparator</param>
/// <param name="Right_Node_Value">Right Comparator</param>
/// <returns>-1 for L less than R, 0 for L equal to R, 1 for L greater than R</returns>
public virtual int Compare ( DataNode pLeftNodeValue, DataNode pRightNodeValue )
{
if ( pLeftNodeValue.Index < pRightNodeValue.Index )
return -1;
else if ( pLeftNodeValue.Index == pRightNodeValue.Index )
return 0;
else
return 1;
}
public virtual bool Match ( DataNode pNodeToVerify )
{
//See if it matches. This is extremely straightforward.
if ( pNodeToVerify.Index == this._NodeIndex )
return true;
else
return false;
}
}
}
| |
//------------------------------------------------------------------------
//
// Microsoft Windows Client Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows.Markup;
using System.Globalization;
namespace System.Windows.Markup.Primitives
{
/// <summary>
/// Utility class use as a base class for classes wrap another
/// instance by delegating MarkupItem implementation to that
/// instance.
/// </summary>
internal class MarkupObjectWrapper : MarkupObject
{
MarkupObject _baseObject;
public MarkupObjectWrapper(MarkupObject baseObject)
{
_baseObject = baseObject;
}
public override void AssignRootContext(IValueSerializerContext context)
{
_baseObject.AssignRootContext(context);
}
public override AttributeCollection Attributes
{
get { return _baseObject.Attributes; }
}
public override Type ObjectType
{
get { return _baseObject.ObjectType; }
}
public override object Instance
{
get { return _baseObject.Instance; }
}
internal override IEnumerable<MarkupProperty> GetProperties(bool mapToConstructorArgs)
{
return _baseObject.GetProperties(mapToConstructorArgs);
}
}
/// <summary>
/// Utility class use as a base class for classes wrap another
/// instance by delegating MarkupProperty implementation to that
/// instance.
/// </summary>
internal class MarkupPropertyWrapper : MarkupProperty
{
MarkupProperty _baseProperty;
/*
protected MarkupProperty BaseProperty
{
get { return _baseProperty; }
}
*/
public MarkupPropertyWrapper(MarkupProperty baseProperty)
{
_baseProperty = baseProperty;
}
public override AttributeCollection Attributes
{
get { return _baseProperty.Attributes; }
}
public override IEnumerable<MarkupObject> Items
{
get { return _baseProperty.Items; }
}
public override string Name
{
get { return _baseProperty.Name; }
}
public override Type PropertyType
{
get { return _baseProperty.PropertyType; }
}
public override string StringValue
{
get { return _baseProperty.StringValue; }
}
public override IEnumerable<Type> TypeReferences
{
get { return _baseProperty.TypeReferences; }
}
public override object Value
{
get { return _baseProperty.Value; }
}
public override DependencyProperty DependencyProperty
{
get { return _baseProperty.DependencyProperty; }
}
public override bool IsAttached
{
get { return _baseProperty.IsAttached; }
}
public override bool IsComposite
{
get { return _baseProperty.IsComposite; }
}
public override bool IsConstructorArgument
{
get { return _baseProperty.IsConstructorArgument; }
}
public override bool IsKey
{
get { return _baseProperty.IsKey; }
}
public override bool IsValueAsString
{
get { return _baseProperty.IsValueAsString; }
}
public override bool IsContent
{
get { return _baseProperty.IsContent; }
}
public override PropertyDescriptor PropertyDescriptor
{
get { return _baseProperty.PropertyDescriptor; }
}
/// <summary>
/// Checks to see that each markup object is of a public type. Used in serialization.
///
/// This implementation just checks the base property.
/// </summary>
internal override void VerifyOnlySerializableTypes()
{
_baseProperty.VerifyOnlySerializableTypes();
}
}
/// <summary>
/// A MarkupItem wrapper that creates an ExtensionSimplifierProperty wrapper
/// for every property returned. All other implementation is delegated to
/// the wrapped item.
/// </summary>
internal class ExtensionSimplifierMarkupObject : MarkupObjectWrapper
{
IValueSerializerContext _context;
public ExtensionSimplifierMarkupObject(MarkupObject baseObject, IValueSerializerContext context)
: base(baseObject)
{
_context = context;
}
/// This is placed in its own method to avoid accessing base.Properties from the
/// iterator class generated by the code below because C# produces unverifiable
/// code for the expression.
private IEnumerable<MarkupProperty> GetBaseProperties(bool mapToConstructorArgs) {
return base.GetProperties(mapToConstructorArgs);
}
internal override IEnumerable<MarkupProperty> GetProperties(bool mapToConstructorArgs)
{
foreach (MarkupProperty property in GetBaseProperties(mapToConstructorArgs))
{
yield return new ExtensionSimplifierProperty(property, _context);
}
}
public override void AssignRootContext(IValueSerializerContext context)
{
_context = context;
base.AssignRootContext(context);
}
}
/// <summary>
/// A MarkupProperty wrapper that creates simplifies items for objects
/// of type MarkupExtension to a string if all its properties can be
/// simplified into a string. This is recursive in that a markup extension
/// can contain references to other markup extensions which are themselves
/// simplified.
/// </summary>
internal class ExtensionSimplifierProperty : MarkupPropertyWrapper
{
IValueSerializerContext _context;
public ExtensionSimplifierProperty(MarkupProperty baseProperty, IValueSerializerContext context) : base(baseProperty)
{
_context = context;
}
public override bool IsComposite
{
get
{
// See if we can convert an extension into a string.
if (!base.IsComposite)
{
// If it is already a string then we can.
return false;
}
// If the property is a collection, this property is a composite.
if (IsCollectionProperty)
{
return true;
}
bool first = true;
foreach (MarkupObject item in Items)
{
// If there is more than one MarkupExtension, we can't.
// If it is not a markup extension we can't.
if (!first ||
!typeof(MarkupExtension).IsAssignableFrom(item.ObjectType))
{
return true;
}
first = false;
// If any of the properties are composite we can't. This is recursive to this
// routine because of the wrapping below.
item.AssignRootContext(_context);
foreach (MarkupProperty property in item.Properties)
{
if (property.IsComposite)
{
return true;
}
}
}
// We can turn this into a string if we have seen at least one item
return first;
}
}
/// This is placed in its own method to avoid accessing base.Items from the
/// iterator class generated by the code below because C# produces unverifiable
/// code for the expression.
private IEnumerable<MarkupObject> GetBaseItems()
{
return base.Items;
}
public override IEnumerable<MarkupObject> Items
{
get
{
// Wrap all of the items from the property we are wrapping.
foreach (MarkupObject baseItem in GetBaseItems())
{
ExtensionSimplifierMarkupObject item = new ExtensionSimplifierMarkupObject(baseItem, _context);
item.AssignRootContext(_context);
yield return item;
}
}
}
private const int EXTENSIONLENGTH = 9; // the number of characters in the string "Extension"
public override string StringValue
{
get
{
string result = null;
if (!base.IsComposite)
{
// Escape the text as necessary to avoid being mistaken for a MarkupExtension.
result = MarkupExtensionParser.AddEscapeToLiteralString(base.StringValue);
}
else
{
// Convert the markup extension into a string
foreach (MarkupObject item in Items)
{
result = ConvertMarkupItemToString(item);
break;
}
if (result == null)
{
Debug.Fail("No items where found and IsComposite return true");
result = "";
}
}
return result;
}
}
private string ConvertMarkupItemToString(MarkupObject item)
{
ValueSerializer typeSerializer = _context.GetValueSerializerFor(typeof(Type));
Debug.Assert(typeSerializer != null, "Could not retrieve typeSerializer for Type");
// Serialize the markup extension into a string
StringBuilder resultBuilder = new StringBuilder();
resultBuilder.Append('{');
string typeName = typeSerializer.ConvertToString(item.ObjectType, _context);
if (typeName.EndsWith("Extension", StringComparison.Ordinal))
{
// The "Extension" suffix is optional, much like the Attribute suffix of an Attribute.
// The normalized version is without the suffix.
resultBuilder.Append(typeName, 0, typeName.Length - EXTENSIONLENGTH);
}
else
{
resultBuilder.Append(typeName);
}
bool first = true;
bool propertyWritten = false;
foreach (MarkupProperty property in item.Properties)
{
resultBuilder.Append(first ? " " : ", ");
first = false;
if (!property.IsConstructorArgument)
{
resultBuilder.Append(property.Name);
resultBuilder.Append('=');
propertyWritten = true;
}
else
{
Debug.Assert(!propertyWritten, "An argument was returned after a property was set. All arguments must be returned first and in order");
}
string value = property.StringValue;
if (value != null && value.Length > 0)
{
if (value[0] == '{')
{
if (value.Length > 1 && value[1] == '}')
{
// It is a literal quote, remove the literals and write the text with escapes.
value = value.Substring(2);
}
else
{
// It is a nested markup-extension, just insert the text literally.
resultBuilder.Append(value);
continue;
}
}
// Escape the string
for (int i = 0; i < value.Length; i++)
{
char ch = value[i];
switch (ch)
{
case '{':
resultBuilder.Append(@"\{");
break;
case '}':
resultBuilder.Append(@"\}");
break;
case ',':
resultBuilder.Append(@"\,");
break;
default:
resultBuilder.Append(ch);
break;
}
}
}
}
resultBuilder.Append('}');
return resultBuilder.ToString();
}
/// <summary>
/// Checks to see that each markup object is of a public type. Used in serialization.
///
/// This implementation checks the base property, checks the item's type, and recursively checks each of
/// the item's properties.
/// </summary>
internal override void VerifyOnlySerializableTypes()
{
base.VerifyOnlySerializableTypes();
if(base.IsComposite)
{
foreach (MarkupObject item in Items)
{
MarkupWriter.VerifyTypeIsSerializable(item.ObjectType);
foreach (MarkupProperty property in item.Properties)
{
property.VerifyOnlySerializableTypes();
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using Raksha.Security;
using Raksha.Asn1;
using Raksha.Asn1.CryptoPro;
using Raksha.Asn1.Nist;
using Raksha.Asn1.Pkcs;
using Raksha.Asn1.TeleTrust;
using Raksha.Asn1.X509;
using Raksha.Asn1.X9;
using Raksha.Crypto;
using Raksha.Crypto.Digests;
using Raksha.Crypto.Engines;
using Raksha.Crypto.Signers;
using Raksha.Utilities;
namespace Raksha.Security
{
/// <summary>
/// Signer Utility class contains methods that can not be specifically grouped into other classes.
/// </summary>
public sealed class SignerUtilities
{
private SignerUtilities()
{
}
internal static readonly IDictionary algorithms = Platform.CreateHashtable();
internal static readonly IDictionary oids = Platform.CreateHashtable();
static SignerUtilities()
{
algorithms["MD2WITHRSA"] = "MD2withRSA";
algorithms["MD2WITHRSAENCRYPTION"] = "MD2withRSA";
algorithms[PkcsObjectIdentifiers.MD2WithRsaEncryption.Id] = "MD2withRSA";
algorithms["MD4WITHRSA"] = "MD4withRSA";
algorithms["MD4WITHRSAENCRYPTION"] = "MD4withRSA";
algorithms[PkcsObjectIdentifiers.MD4WithRsaEncryption.Id] = "MD4withRSA";
algorithms["MD5WITHRSA"] = "MD5withRSA";
algorithms["MD5WITHRSAENCRYPTION"] = "MD5withRSA";
algorithms[PkcsObjectIdentifiers.MD5WithRsaEncryption.Id] = "MD5withRSA";
algorithms["SHA1WITHRSA"] = "SHA-1withRSA";
algorithms["SHA1WITHRSAENCRYPTION"] = "SHA-1withRSA";
algorithms[PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id] = "SHA-1withRSA";
algorithms["SHA-1WITHRSA"] = "SHA-1withRSA";
algorithms["SHA224WITHRSA"] = "SHA-224withRSA";
algorithms["SHA224WITHRSAENCRYPTION"] = "SHA-224withRSA";
algorithms[PkcsObjectIdentifiers.Sha224WithRsaEncryption.Id] = "SHA-224withRSA";
algorithms["SHA-224WITHRSA"] = "SHA-224withRSA";
algorithms["SHA256WITHRSA"] = "SHA-256withRSA";
algorithms["SHA256WITHRSAENCRYPTION"] = "SHA-256withRSA";
algorithms[PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id] = "SHA-256withRSA";
algorithms["SHA-256WITHRSA"] = "SHA-256withRSA";
algorithms["SHA384WITHRSA"] = "SHA-384withRSA";
algorithms["SHA384WITHRSAENCRYPTION"] = "SHA-384withRSA";
algorithms[PkcsObjectIdentifiers.Sha384WithRsaEncryption.Id] = "SHA-384withRSA";
algorithms["SHA-384WITHRSA"] = "SHA-384withRSA";
algorithms["SHA512WITHRSA"] = "SHA-512withRSA";
algorithms["SHA512WITHRSAENCRYPTION"] = "SHA-512withRSA";
algorithms[PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id] = "SHA-512withRSA";
algorithms["SHA-512WITHRSA"] = "SHA-512withRSA";
algorithms["PSSWITHRSA"] = "PSSwithRSA";
algorithms["RSASSA-PSS"] = "PSSwithRSA";
algorithms[PkcsObjectIdentifiers.IdRsassaPss.Id] = "PSSwithRSA";
algorithms["RSAPSS"] = "PSSwithRSA";
algorithms["SHA1WITHRSAANDMGF1"] = "SHA-1withRSAandMGF1";
algorithms["SHA-1WITHRSAANDMGF1"] = "SHA-1withRSAandMGF1";
algorithms["SHA1WITHRSA/PSS"] = "SHA-1withRSAandMGF1";
algorithms["SHA-1WITHRSA/PSS"] = "SHA-1withRSAandMGF1";
algorithms["SHA224WITHRSAANDMGF1"] = "SHA-224withRSAandMGF1";
algorithms["SHA-224WITHRSAANDMGF1"] = "SHA-224withRSAandMGF1";
algorithms["SHA224WITHRSA/PSS"] = "SHA-224withRSAandMGF1";
algorithms["SHA-224WITHRSA/PSS"] = "SHA-224withRSAandMGF1";
algorithms["SHA256WITHRSAANDMGF1"] = "SHA-256withRSAandMGF1";
algorithms["SHA-256WITHRSAANDMGF1"] = "SHA-256withRSAandMGF1";
algorithms["SHA256WITHRSA/PSS"] = "SHA-256withRSAandMGF1";
algorithms["SHA-256WITHRSA/PSS"] = "SHA-256withRSAandMGF1";
algorithms["SHA384WITHRSAANDMGF1"] = "SHA-384withRSAandMGF1";
algorithms["SHA-384WITHRSAANDMGF1"] = "SHA-384withRSAandMGF1";
algorithms["SHA384WITHRSA/PSS"] = "SHA-384withRSAandMGF1";
algorithms["SHA-384WITHRSA/PSS"] = "SHA-384withRSAandMGF1";
algorithms["SHA512WITHRSAANDMGF1"] = "SHA-512withRSAandMGF1";
algorithms["SHA-512WITHRSAANDMGF1"] = "SHA-512withRSAandMGF1";
algorithms["SHA512WITHRSA/PSS"] = "SHA-512withRSAandMGF1";
algorithms["SHA-512WITHRSA/PSS"] = "SHA-512withRSAandMGF1";
algorithms["RIPEMD128WITHRSA"] = "RIPEMD128withRSA";
algorithms["RIPEMD128WITHRSAENCRYPTION"] = "RIPEMD128withRSA";
algorithms[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128.Id] = "RIPEMD128withRSA";
algorithms["RIPEMD160WITHRSA"] = "RIPEMD160withRSA";
algorithms["RIPEMD160WITHRSAENCRYPTION"] = "RIPEMD160withRSA";
algorithms[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160.Id] = "RIPEMD160withRSA";
algorithms["RIPEMD256WITHRSA"] = "RIPEMD256withRSA";
algorithms["RIPEMD256WITHRSAENCRYPTION"] = "RIPEMD256withRSA";
algorithms[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256.Id] = "RIPEMD256withRSA";
algorithms["NONEWITHRSA"] = "RSA";
algorithms["RSAWITHNONE"] = "RSA";
algorithms["RAWRSA"] = "RSA";
algorithms["RAWRSAPSS"] = "RAWRSASSA-PSS";
algorithms["NONEWITHRSAPSS"] = "RAWRSASSA-PSS";
algorithms["NONEWITHRSASSA-PSS"] = "RAWRSASSA-PSS";
algorithms["NONEWITHDSA"] = "NONEwithDSA";
algorithms["DSAWITHNONE"] = "NONEwithDSA";
algorithms["RAWDSA"] = "NONEwithDSA";
algorithms["DSA"] = "SHA-1withDSA";
algorithms["DSAWITHSHA1"] = "SHA-1withDSA";
algorithms["DSAWITHSHA-1"] = "SHA-1withDSA";
algorithms["SHA/DSA"] = "SHA-1withDSA";
algorithms["SHA1/DSA"] = "SHA-1withDSA";
algorithms["SHA-1/DSA"] = "SHA-1withDSA";
algorithms["SHA1WITHDSA"] = "SHA-1withDSA";
algorithms["SHA-1WITHDSA"] = "SHA-1withDSA";
algorithms[X9ObjectIdentifiers.IdDsaWithSha1.Id] = "SHA-1withDSA";
algorithms["DSAWITHSHA224"] = "SHA-224withDSA";
algorithms["DSAWITHSHA-224"] = "SHA-224withDSA";
algorithms["SHA224/DSA"] = "SHA-224withDSA";
algorithms["SHA-224/DSA"] = "SHA-224withDSA";
algorithms["SHA224WITHDSA"] = "SHA-224withDSA";
algorithms["SHA-224WITHDSA"] = "SHA-224withDSA";
algorithms[NistObjectIdentifiers.DsaWithSha224.Id] = "SHA-224withDSA";
algorithms["DSAWITHSHA256"] = "SHA-256withDSA";
algorithms["DSAWITHSHA-256"] = "SHA-256withDSA";
algorithms["SHA256/DSA"] = "SHA-256withDSA";
algorithms["SHA-256/DSA"] = "SHA-256withDSA";
algorithms["SHA256WITHDSA"] = "SHA-256withDSA";
algorithms["SHA-256WITHDSA"] = "SHA-256withDSA";
algorithms[NistObjectIdentifiers.DsaWithSha256.Id] = "SHA-256withDSA";
algorithms["DSAWITHSHA384"] = "SHA-384withDSA";
algorithms["DSAWITHSHA-384"] = "SHA-384withDSA";
algorithms["SHA384/DSA"] = "SHA-384withDSA";
algorithms["SHA-384/DSA"] = "SHA-384withDSA";
algorithms["SHA384WITHDSA"] = "SHA-384withDSA";
algorithms["SHA-384WITHDSA"] = "SHA-384withDSA";
algorithms[NistObjectIdentifiers.DsaWithSha384.Id] = "SHA-384withDSA";
algorithms["DSAWITHSHA512"] = "SHA-512withDSA";
algorithms["DSAWITHSHA-512"] = "SHA-512withDSA";
algorithms["SHA512/DSA"] = "SHA-512withDSA";
algorithms["SHA-512/DSA"] = "SHA-512withDSA";
algorithms["SHA512WITHDSA"] = "SHA-512withDSA";
algorithms["SHA-512WITHDSA"] = "SHA-512withDSA";
algorithms[NistObjectIdentifiers.DsaWithSha512.Id] = "SHA-512withDSA";
algorithms["NONEWITHECDSA"] = "NONEwithECDSA";
algorithms["ECDSAWITHNONE"] = "NONEwithECDSA";
algorithms["ECDSA"] = "SHA-1withECDSA";
algorithms["SHA1/ECDSA"] = "SHA-1withECDSA";
algorithms["SHA-1/ECDSA"] = "SHA-1withECDSA";
algorithms["ECDSAWITHSHA1"] = "SHA-1withECDSA";
algorithms["ECDSAWITHSHA-1"] = "SHA-1withECDSA";
algorithms["SHA1WITHECDSA"] = "SHA-1withECDSA";
algorithms["SHA-1WITHECDSA"] = "SHA-1withECDSA";
algorithms[X9ObjectIdentifiers.ECDsaWithSha1.Id] = "SHA-1withECDSA";
algorithms[TeleTrusTObjectIdentifiers.ECSignWithSha1.Id] = "SHA-1withECDSA";
algorithms["SHA224/ECDSA"] = "SHA-224withECDSA";
algorithms["SHA-224/ECDSA"] = "SHA-224withECDSA";
algorithms["ECDSAWITHSHA224"] = "SHA-224withECDSA";
algorithms["ECDSAWITHSHA-224"] = "SHA-224withECDSA";
algorithms["SHA224WITHECDSA"] = "SHA-224withECDSA";
algorithms["SHA-224WITHECDSA"] = "SHA-224withECDSA";
algorithms[X9ObjectIdentifiers.ECDsaWithSha224.Id] = "SHA-224withECDSA";
algorithms["SHA256/ECDSA"] = "SHA-256withECDSA";
algorithms["SHA-256/ECDSA"] = "SHA-256withECDSA";
algorithms["ECDSAWITHSHA256"] = "SHA-256withECDSA";
algorithms["ECDSAWITHSHA-256"] = "SHA-256withECDSA";
algorithms["SHA256WITHECDSA"] = "SHA-256withECDSA";
algorithms["SHA-256WITHECDSA"] = "SHA-256withECDSA";
algorithms[X9ObjectIdentifiers.ECDsaWithSha256.Id] = "SHA-256withECDSA";
algorithms["SHA384/ECDSA"] = "SHA-384withECDSA";
algorithms["SHA-384/ECDSA"] = "SHA-384withECDSA";
algorithms["ECDSAWITHSHA384"] = "SHA-384withECDSA";
algorithms["ECDSAWITHSHA-384"] = "SHA-384withECDSA";
algorithms["SHA384WITHECDSA"] = "SHA-384withECDSA";
algorithms["SHA-384WITHECDSA"] = "SHA-384withECDSA";
algorithms[X9ObjectIdentifiers.ECDsaWithSha384.Id] = "SHA-384withECDSA";
algorithms["SHA512/ECDSA"] = "SHA-512withECDSA";
algorithms["SHA-512/ECDSA"] = "SHA-512withECDSA";
algorithms["ECDSAWITHSHA512"] = "SHA-512withECDSA";
algorithms["ECDSAWITHSHA-512"] = "SHA-512withECDSA";
algorithms["SHA512WITHECDSA"] = "SHA-512withECDSA";
algorithms["SHA-512WITHECDSA"] = "SHA-512withECDSA";
algorithms[X9ObjectIdentifiers.ECDsaWithSha512.Id] = "SHA-512withECDSA";
algorithms["RIPEMD160/ECDSA"] = "RIPEMD160withECDSA";
algorithms["SHA-512/ECDSA"] = "RIPEMD160withECDSA";
algorithms["ECDSAWITHRIPEMD160"] = "RIPEMD160withECDSA";
algorithms["ECDSAWITHRIPEMD160"] = "RIPEMD160withECDSA";
algorithms["RIPEMD160WITHECDSA"] = "RIPEMD160withECDSA";
algorithms["RIPEMD160WITHECDSA"] = "RIPEMD160withECDSA";
algorithms[TeleTrusTObjectIdentifiers.ECSignWithRipeMD160.Id] = "RIPEMD160withECDSA";
algorithms["GOST-3410"] = "GOST3410";
algorithms["GOST-3410-94"] = "GOST3410";
algorithms["GOST3411WITHGOST3410"] = "GOST3410";
algorithms[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94.Id] = "GOST3410";
algorithms["ECGOST-3410"] = "ECGOST3410";
algorithms["ECGOST-3410-2001"] = "ECGOST3410";
algorithms["GOST3411WITHECGOST3410"] = "ECGOST3410";
algorithms[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001.Id] = "ECGOST3410";
oids["MD2withRSA"] = PkcsObjectIdentifiers.MD2WithRsaEncryption;
oids["MD4withRSA"] = PkcsObjectIdentifiers.MD4WithRsaEncryption;
oids["MD5withRSA"] = PkcsObjectIdentifiers.MD5WithRsaEncryption;
oids["SHA-1withRSA"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption;
oids["SHA-224withRSA"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption;
oids["SHA-256withRSA"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption;
oids["SHA-384withRSA"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption;
oids["SHA-512withRSA"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption;
oids["PSSwithRSA"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["SHA-1withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["SHA-224withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["SHA-256withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["SHA-384withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["SHA-512withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
oids["RIPEMD128withRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128;
oids["RIPEMD160withRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160;
oids["RIPEMD256withRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256;
oids["SHA-1withDSA"] = X9ObjectIdentifiers.IdDsaWithSha1;
oids["SHA-1withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha1;
oids["SHA-224withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha224;
oids["SHA-256withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha256;
oids["SHA-384withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha384;
oids["SHA-512withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha512;
oids["GOST3410"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94;
oids["ECGOST3410"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001;
}
/// <summary>
/// Returns a ObjectIdentifier for a give encoding.
/// </summary>
/// <param name="mechanism">A string representation of the encoding.</param>
/// <returns>A DerObjectIdentifier, null if the Oid is not available.</returns>
// TODO Don't really want to support this
public static DerObjectIdentifier GetObjectIdentifier(
string mechanism)
{
if (mechanism == null)
throw new ArgumentNullException("mechanism");
mechanism = mechanism.ToUpperInvariant();
string aliased = (string) algorithms[mechanism];
if (aliased != null)
mechanism = aliased;
return (DerObjectIdentifier) oids[mechanism];
}
public static ICollection Algorithms
{
get { return oids.Keys; }
}
public static Asn1Encodable GetDefaultX509Parameters(
DerObjectIdentifier id)
{
return GetDefaultX509Parameters(id.Id);
}
public static Asn1Encodable GetDefaultX509Parameters(
string algorithm)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
algorithm = algorithm.ToUpperInvariant();
string mechanism = (string) algorithms[algorithm];
if (mechanism == null)
mechanism = algorithm;
if (mechanism == "PSSwithRSA")
{
// TODO The Sha1Digest here is a default. In JCE version, the actual digest
// to be used can be overridden by subsequent parameter settings.
return GetPssX509Parameters("SHA-1");
}
if (mechanism.EndsWith("withRSAandMGF1"))
{
string digestName = mechanism.Substring(0, mechanism.Length - "withRSAandMGF1".Length);
return GetPssX509Parameters(digestName);
}
return DerNull.Instance;
}
private static Asn1Encodable GetPssX509Parameters(
string digestName)
{
AlgorithmIdentifier hashAlgorithm = new AlgorithmIdentifier(
DigestUtilities.GetObjectIdentifier(digestName), DerNull.Instance);
// TODO Is it possible for the MGF hash alg to be different from the PSS one?
AlgorithmIdentifier maskGenAlgorithm = new AlgorithmIdentifier(
PkcsObjectIdentifiers.IdMgf1, hashAlgorithm);
int saltLen = DigestUtilities.GetDigest(digestName).GetDigestSize();
return new RsassaPssParameters(hashAlgorithm, maskGenAlgorithm,
new DerInteger(saltLen), new DerInteger(1));
}
public static ISigner GetSigner(
DerObjectIdentifier id)
{
return GetSigner(id.Id);
}
public static ISigner GetSigner(
string algorithm)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
algorithm = algorithm.ToUpperInvariant();
string mechanism = (string) algorithms[algorithm];
if (mechanism == null)
mechanism = algorithm;
if (mechanism.Equals("RSA"))
{
return (new RsaDigestSigner(new NullDigest()));
}
if (mechanism.Equals("MD2withRSA"))
{
return (new RsaDigestSigner(new MD2Digest()));
}
if (mechanism.Equals("MD4withRSA"))
{
return (new RsaDigestSigner(new MD4Digest()));
}
if (mechanism.Equals("MD5withRSA"))
{
return (new RsaDigestSigner(new MD5Digest()));
}
if (mechanism.Equals("SHA-1withRSA"))
{
return (new RsaDigestSigner(new Sha1Digest()));
}
if (mechanism.Equals("SHA-224withRSA"))
{
return (new RsaDigestSigner(new Sha224Digest()));
}
if (mechanism.Equals("SHA-256withRSA"))
{
return (new RsaDigestSigner(new Sha256Digest()));
}
if (mechanism.Equals("SHA-384withRSA"))
{
return (new RsaDigestSigner(new Sha384Digest()));
}
if (mechanism.Equals("SHA-512withRSA"))
{
return (new RsaDigestSigner(new Sha512Digest()));
}
if (mechanism.Equals("RIPEMD128withRSA"))
{
return (new RsaDigestSigner(new RipeMD128Digest()));
}
if (mechanism.Equals("RIPEMD160withRSA"))
{
return (new RsaDigestSigner(new RipeMD160Digest()));
}
if (mechanism.Equals("RIPEMD256withRSA"))
{
return (new RsaDigestSigner(new RipeMD256Digest()));
}
if (mechanism.Equals("RAWRSASSA-PSS"))
{
// TODO Add support for other parameter settings
return PssSigner.CreateRawSigner(new RsaBlindedEngine(), new Sha1Digest());
}
if (mechanism.Equals("PSSwithRSA"))
{
// TODO The Sha1Digest here is a default. In JCE version, the actual digest
// to be used can be overridden by subsequent parameter settings.
return (new PssSigner(new RsaBlindedEngine(), new Sha1Digest()));
}
if (mechanism.Equals("SHA-1withRSAandMGF1"))
{
return (new PssSigner(new RsaBlindedEngine(), new Sha1Digest()));
}
if (mechanism.Equals("SHA-224withRSAandMGF1"))
{
return (new PssSigner(new RsaBlindedEngine(), new Sha224Digest()));
}
if (mechanism.Equals("SHA-256withRSAandMGF1"))
{
return (new PssSigner(new RsaBlindedEngine(), new Sha256Digest()));
}
if (mechanism.Equals("SHA-384withRSAandMGF1"))
{
return (new PssSigner(new RsaBlindedEngine(), new Sha384Digest()));
}
if (mechanism.Equals("SHA-512withRSAandMGF1"))
{
return (new PssSigner(new RsaBlindedEngine(), new Sha512Digest()));
}
if (mechanism.Equals("NONEwithDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new NullDigest()));
}
if (mechanism.Equals("SHA-1withDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new Sha1Digest()));
}
if (mechanism.Equals("SHA-224withDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new Sha224Digest()));
}
if (mechanism.Equals("SHA-256withDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new Sha256Digest()));
}
if (mechanism.Equals("SHA-384withDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new Sha384Digest()));
}
if (mechanism.Equals("SHA-512withDSA"))
{
return (new DsaDigestSigner(new DsaSigner(), new Sha512Digest()));
}
if (mechanism.Equals("NONEwithECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new NullDigest()));
}
if (mechanism.Equals("SHA-1withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new Sha1Digest()));
}
if (mechanism.Equals("SHA-224withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new Sha224Digest()));
}
if (mechanism.Equals("SHA-256withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new Sha256Digest()));
}
if (mechanism.Equals("SHA-384withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new Sha384Digest()));
}
if (mechanism.Equals("SHA-512withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new Sha512Digest()));
}
if (mechanism.Equals("RIPEMD160withECDSA"))
{
return (new DsaDigestSigner(new ECDsaSigner(), new RipeMD160Digest()));
}
if (mechanism.Equals("SHA1WITHECNR"))
{
return (new DsaDigestSigner(new ECNRSigner(), new Sha1Digest()));
}
if (mechanism.Equals("SHA224WITHECNR"))
{
return (new DsaDigestSigner(new ECNRSigner(), new Sha224Digest()));
}
if (mechanism.Equals("SHA256WITHECNR"))
{
return (new DsaDigestSigner(new ECNRSigner(), new Sha256Digest()));
}
if (mechanism.Equals("SHA384WITHECNR"))
{
return (new DsaDigestSigner(new ECNRSigner(), new Sha384Digest()));
}
if (mechanism.Equals("SHA512WITHECNR"))
{
return (new DsaDigestSigner(new ECNRSigner(), new Sha512Digest()));
}
if (mechanism.Equals("GOST3410"))
{
return new Gost3410DigestSigner(new Gost3410Signer(), new Gost3411Digest());
}
if (mechanism.Equals("ECGOST3410"))
{
return new Gost3410DigestSigner(new ECGost3410Signer(), new Gost3411Digest());
}
if (mechanism.Equals("SHA1WITHRSA/ISO9796-2"))
{
return new Iso9796d2Signer(new RsaBlindedEngine(), new Sha1Digest(), true);
}
if (mechanism.Equals("MD5WITHRSA/ISO9796-2"))
{
return new Iso9796d2Signer(new RsaBlindedEngine(), new MD5Digest(), true);
}
if (mechanism.Equals("RIPEMD160WITHRSA/ISO9796-2"))
{
return new Iso9796d2Signer(new RsaBlindedEngine(), new RipeMD160Digest(), true);
}
throw new SecurityUtilityException("Signer " + algorithm + " not recognised.");
}
public static string GetEncodingName(
DerObjectIdentifier oid)
{
return (string) algorithms[oid.Id];
}
}
}
| |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* 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
namespace RedBadger.Xpf
{
using System;
using System.Diagnostics;
/// <summary>
/// A struct representing a Vector with <see cref = "X">X</see> and <see cref = "Y">Y</see> components.
/// </summary>
[DebuggerDisplay("{X} x {Y}")]
public struct Vector : IEquatable<Vector>
{
/// <summary>
/// The X component of the <see cref = "Vector">Vector</see>.
/// </summary>
public double X;
/// <summary>
/// The Y component of the <see cref = "Vector">Vector</see>.
/// </summary>
public double Y;
private const double RadiansToDegrees = 57.295779513082323;
/// <summary>
/// Initializes a new <see cref = "Vector">Vector</see> structure.
/// </summary>
/// <param name = "x"> The <see cref = "X">X</see> component of the <see cref = "Vector">Vector</see>.</param>
/// <param name = "y"> The <see cref = "Y">Y</see> component of the <see cref = "Vector">Vector</see>.</param>
public Vector(double x, double y)
{
this.X = x;
this.Y = y;
}
/// <summary>
/// Gets a <see cref = "Vector">Vector</see> with <see cref = "X">X</see> and <see cref = "Y">Y</see> of zero.
/// </summary>
public static Vector Zero
{
get
{
return new Vector();
}
}
/// <summary>
/// Gets the length of the <see cref = "Vector">Vector</see>.
/// </summary>
public double Length
{
get
{
return Math.Sqrt(this.LengthSquared);
}
}
/// <summary>
/// Gets the square of the <see cref = "Length">Length</see> of the <see cref = "Vector">Vector</see>.
/// </summary>
public double LengthSquared
{
get
{
return (this.X * this.X) + (this.Y * this.Y);
}
}
/// <summary>
/// Adds a <see cref = "Vector">Vector</see> to another Vector.
/// </summary>
/// <param name = "vector1">The first <see cref = "Vector">Vector</see>.</param>
/// <param name = "vector2">The second <see cref = "Vector">Vector</see>.</param>
/// <returns>The sum of the two <see cref = "Vector">Vector</see>s.</returns>
public static Vector operator +(Vector vector1, Vector vector2)
{
return new Vector(vector1.X + vector2.X, vector1.Y + vector2.Y);
}
/// <summary>
/// Divides a <see cref = "Vector">Vector</see> by the specified <see cref = "scalar">scalar</see>.
/// </summary>
/// <param name = "vector">The <see cref = "Vector">Vector</see> to divide.</param>
/// <param name = "scalar">The scalar by which to divide the <see cref = "Vector">Vector</see>.</param>
/// <returns>A new <see cref = "Vector">Vector</see> whose <see cref = "X">X</see> and <see cref = "Y">Y</see> values have been divided by the specified <see cref = "scalar">scalar</see>.</returns>
public static Vector operator /(Vector vector, double scalar)
{
return vector * (1d / scalar);
}
/// <summary>
/// Compares two <see cref = "Vector">Vector</see> structs for equality in their <see cref = "X">X</see> and <see cref = "Y">Y</see> components.
/// </summary>
/// <param name = "left">The first <see cref = "Vector">Vector</see> to compare.</param>
/// <param name = "right">The second <see cref = "Vector">Vector</see> to compare.</param>
/// <returns>Returns true if the two <see cref = "Vector">Vector</see> instances are equal.</returns>
public static bool operator ==(Vector left, Vector right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two <see cref = "Vector">Vector</see> structs for inequality in their <see cref = "X">X</see> and <see cref = "Y">Y</see> components.
/// </summary>
/// <param name = "left">The first <see cref = "Vector">Vector</see> to compare.</param>
/// <param name = "right">The second <see cref = "Vector">Vector</see> to compare.</param>
/// <returns>Returns true if the two <see cref = "Vector">Vector</see> instances are not equal.</returns>
public static bool operator !=(Vector left, Vector right)
{
return !left.Equals(right);
}
/// <summary>
/// Multiplies a <see cref = "Vector">Vector</see> by the specified <see cref = "scalar">scalar</see>.
/// </summary>
/// <param name = "vector">The <see cref = "Vector">Vector</see> to multiply.</param>
/// <param name = "scalar">The scalar by which to multiply the <see cref = "Vector">Vector</see>.</param>
/// <returns>A new <see cref = "Vector">Vector</see> whose <see cref = "X">X</see> and <see cref = "Y">Y</see> values have been multiplied by the specified <see cref = "scalar">scalar</see>.</returns>
public static Vector operator *(Vector vector, double scalar)
{
return new Vector(vector.X * scalar, vector.Y * scalar);
}
/// <summary>
/// Calculates the angle in degrees between two <see cref = "Vector">Vector</see>s.
/// </summary>
/// <param name = "vector1">The first <see cref = "Vector">Vector</see>.</param>
/// <param name = "vector2">The second <see cref = "Vector">Vector</see>.</param>
/// <returns>The angle between the two specified <see cref = "Vector">Vector</see>s.</returns>
public static double AngleBetween(Vector vector1, Vector vector2)
{
return Math.Atan2(CrossProduct(vector1, vector2), DotProduct(vector1, vector2)) * RadiansToDegrees;
}
/// <summary>
/// Calculates the Cross Product of two <see cref = "Vector">Vector</see>s.
/// </summary>
/// <param name = "vector1">The first <see cref = "Vector">Vector</see>.</param>
/// <param name = "vector2">The second <see cref = "Vector">Vector</see>.</param>
/// <returns>The Cross Product of the two <see cref = "Vector">Vector</see>s.</returns>
public static double CrossProduct(Vector vector1, Vector vector2)
{
return (vector1.X * vector2.Y) - (vector1.Y * vector2.X);
}
/// <summary>
/// Calculates the Dot Product of two <see cref = "Vector">Vector</see>s.
/// </summary>
/// <param name = "vector1">The first <see cref = "Vector">Vector</see>.</param>
/// <param name = "vector2">The second <see cref = "Vector">Vector</see>.</param>
/// <returns>The Dot Product of the two <see cref = "Vector">Vector</see>s.</returns>
public static double DotProduct(Vector vector1, Vector vector2)
{
return (vector1.X * vector2.X) + (vector1.Y * vector2.Y);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (obj.GetType() != typeof(Vector))
{
return false;
}
return this.Equals((Vector)obj);
}
public override int GetHashCode()
{
unchecked
{
return (this.X.GetHashCode() * 397) ^ this.Y.GetHashCode();
}
}
/// <summary>
/// Normalizes the <see cref = "Vector">Vector</see> so that it is parallel but with unit length.
/// </summary>
public void Normalize()
{
this = this / Math.Max(Math.Abs(this.X), Math.Abs(this.Y));
this = this / this.Length;
}
public override string ToString()
{
return string.Format("X: {0}, Y: {1}", this.X, this.Y);
}
public bool Equals(Vector other)
{
return other.X.Equals(this.X) && other.Y.Equals(this.Y);
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Unicode;
using Internal.Runtime.CompilerServices;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Utf8Span.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
#pragma warning disable SA1121 // explicitly using type aliases instead of built-in types
#if BIT64
using nint = System.Int64;
using nuint = System.UInt64;
#else
using nint = System.Int32;
using nuint = System.UInt32;
#endif
namespace System.Text
{
[StructLayout(LayoutKind.Auto)]
public readonly ref partial struct Utf8Span
{
/// <summary>
/// Creates a <see cref="Utf8Span"/> from an existing <see cref="Utf8String"/> instance.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Utf8Span(Utf8String? value)
{
Bytes = Utf8Extensions.AsBytes(value);
}
/// <summary>
/// Ctor for internal use only. Caller _must_ validate both invariants hold:
/// (a) the buffer represents well-formed UTF-8 data, and
/// (b) the buffer is immutable.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Utf8Span(ReadOnlySpan<byte> rawData)
{
// In debug builds, we want to ensure that the callers really did validate
// the buffer for well-formedness. The entire line below is removed when
// compiling release builds.
Debug.Assert(Utf8Utility.GetIndexOfFirstInvalidUtf8Sequence(rawData, out _) == -1);
Bytes = rawData;
}
public ReadOnlySpan<byte> Bytes { get; }
public static Utf8Span Empty => default;
public bool IsEmpty => Bytes.IsEmpty;
/// <summary>
/// Returns the length (in UTF-8 code units, or <see cref="byte"/>s) of this instance.
/// </summary>
public int Length => Bytes.Length;
public Utf8Span this[Range range]
{
get
{
(int offset, int length) = range.GetOffsetAndLength(Length);
// Check for a split across a multi-byte subsequence on the way out.
// Reminder: Unlike Utf8String, we can't safely dereference past the end of the span.
ref byte newRef = ref DangerousGetMutableReference(offset);
if (length > 0 && Utf8Utility.IsUtf8ContinuationByte(newRef))
{
Utf8String.ThrowImproperStringSplit();
}
int endIdx = offset + length;
if (endIdx < Length && Utf8Utility.IsUtf8ContinuationByte(DangerousGetMutableReference(endIdx)))
{
Utf8String.ThrowImproperStringSplit();
}
return UnsafeCreateWithoutValidation(new ReadOnlySpan<byte>(ref newRef, length));
}
}
/// <summary>
/// Returns a <em>mutable</em> reference to the first byte of this <see cref="Utf8Span"/>
/// (or, if this <see cref="Utf8Span"/> is empty, to where the first byte would be).
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ref byte DangerousGetMutableReference() => ref MemoryMarshal.GetReference(Bytes);
/// <summary>
/// Returns a <em>mutable</em> reference to the element at index <paramref name="index"/>
/// of this <see cref="Utf8Span"/> instance. The index is not bounds-checked.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ref byte DangerousGetMutableReference(int index)
{
Debug.Assert(index >= 0, "Caller should've performed bounds checking.");
return ref DangerousGetMutableReference((uint)index);
}
/// <summary>
/// Returns a <em>mutable</em> reference to the element at index <paramref name="index"/>
/// of this <see cref="Utf8Span"/> instance. The index is not bounds-checked.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ref byte DangerousGetMutableReference(nuint index)
{
// Allow retrieving references to just past the end of the span (but shouldn't dereference this).
Debug.Assert(index <= (uint)Length, "Caller should've performed bounds checking.");
return ref Unsafe.AddByteOffset(ref DangerousGetMutableReference(), index);
}
public bool IsEmptyOrWhiteSpace() => (Utf8Utility.GetIndexOfFirstNonWhiteSpaceChar(Bytes) == Length);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals(object) on Utf8Span will always throw an exception. Use Equals(Utf8Span) or operator == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj)
{
throw new NotSupportedException(SR.Utf8Span_CannotCallEqualsObject);
}
public bool Equals(Utf8Span other) => Equals(this, other);
public bool Equals(Utf8Span other, StringComparison comparison) => Equals(this, other, comparison);
public static bool Equals(Utf8Span left, Utf8Span right) => left.Bytes.SequenceEqual(right.Bytes);
public static bool Equals(Utf8Span left, Utf8Span right, StringComparison comparison)
{
// TODO_UTF8STRING: This perf can be improved, including removing
// the virtual dispatch by putting the switch directly in this method.
return Utf8StringComparer.FromComparison(comparison).Equals(left, right);
}
public override int GetHashCode()
{
// TODO_UTF8STRING: Consider whether this should use a different seed than String.GetHashCode.
// This method should only be called to calculate the hash code over spans that represent
// UTF-8 textual data, not over arbitrary binary sequences.
ulong seed = Marvin.DefaultSeed;
return Marvin.ComputeHash32(ref MemoryMarshal.GetReference(Bytes), (uint)Length /* in bytes */, (uint)seed, (uint)(seed >> 32));
}
public int GetHashCode(StringComparison comparison)
{
// TODO_UTF8STRING: This perf can be improved, including removing
// the virtual dispatch by putting the switch directly in this method.
return Utf8StringComparer.FromComparison(comparison).GetHashCode(this);
}
/// <summary>
/// Returns <see langword="true"/> if this UTF-8 text consists of all-ASCII data,
/// <see langword="false"/> if there is any non-ASCII data within this UTF-8 text.
/// </summary>
/// <remarks>
/// ASCII text is defined as text consisting only of scalar values in the range [ U+0000..U+007F ].
/// Empty spans are considered to be all-ASCII. The runtime of this method is O(n).
/// </remarks>
public bool IsAscii()
{
// TODO_UTF8STRING: Use an API that takes 'ref byte' instead of a 'byte*' as a parameter.
unsafe
{
fixed (byte* pData = &MemoryMarshal.GetReference(Bytes))
{
return (ASCIIUtility.GetIndexOfFirstNonAsciiByte(pData, (uint)Length) == (uint)Length);
}
}
}
/// <summary>
/// Returns a value stating whether this <see cref="Utf8Span"/> instance is normalized
/// using the specified Unicode normalization form.
/// </summary>
/// <param name="normalizationForm">The <see cref="NormalizationForm"/> to check.</param>
/// <returns><see langword="true"/> if this <see cref="Utf8Span"/> instance represents text
/// normalized under <paramref name="normalizationForm"/>, otherwise <see langword="false"/>.</returns>
public bool IsNormalized(NormalizationForm normalizationForm = NormalizationForm.FormC)
{
// TODO_UTF8STRING: Avoid allocations in this code path.
return ToString().IsNormalized(normalizationForm);
}
/// <summary>
/// Gets an immutable reference that can be used in a <see langword="fixed"/> statement. Unlike
/// <see cref="Utf8String"/>, the resulting reference is not guaranteed to be null-terminated.
/// </summary>
/// <remarks>
/// If this <see cref="Utf8Span"/> instance is empty, returns <see langword="null"/>. Dereferencing
/// such a reference will result in a <see cref="NullReferenceException"/> being generated.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public ref readonly byte GetPinnableReference()
{
// This returns null if the underlying span is empty. The reason for this is that unlike
// Utf8String, these buffers are not guaranteed to be null-terminated, so it's not always
// safe or meaningful to dereference the element just past the end of the buffer.
return ref Bytes.GetPinnableReference();
}
public override string ToString()
{
// TODO_UTF8STRING: Since we know the underlying data is immutable, well-formed UTF-8,
// we can perform transcoding using an optimized code path that skips all safety checks.
return Encoding.UTF8.GetString(Bytes);
}
/// <summary>
/// Converts this <see cref="Utf8Span"/> instance to a <see cref="string"/>.
/// </summary>
/// <remarks>
/// This routine throws <see cref="InvalidOperationException"/> if the underlying instance
/// contains invalid UTF-8 data.
/// </remarks>
internal unsafe string ToStringNoReplacement()
{
// TODO_UTF8STRING: Optimize the call below, potentially by avoiding the two-pass.
fixed (byte* pData = &MemoryMarshal.GetReference(Bytes))
{
byte* pFirstInvalidByte = Utf8Utility.GetPointerToFirstInvalidByte(pData, Length, out int utf16CodeUnitCountAdjustment, out _);
if (pFirstInvalidByte != pData + (uint)Length)
{
// Saw bad UTF-8 data.
// TODO_UTF8STRING: Throw a better exception below?
ThrowHelper.ThrowInvalidOperationException();
}
int utf16CharCount = Length + utf16CodeUnitCountAdjustment;
Debug.Assert(utf16CharCount <= Length && utf16CharCount >= 0);
// TODO_UTF8STRING: Can we call string.FastAllocate directly?
return string.Create(utf16CharCount, (pbData: (IntPtr)pData, cbData: Length), (chars, state) =>
{
OperationStatus status = Utf8.ToUtf16(new ReadOnlySpan<byte>((byte*)state.pbData, state.cbData), chars, out _, out _, replaceInvalidSequences: false);
Debug.Assert(status == OperationStatus.Done, "Did somebody mutate this Utf8String instance unexpectedly?");
});
}
}
public Utf8String ToUtf8String()
{
// TODO_UTF8STRING: Since we know the underlying data is immutable, well-formed UTF-8,
// we can perform transcoding using an optimized code path that skips all safety checks.
return Utf8String.UnsafeCreateWithoutValidation(Bytes);
}
/// <summary>
/// Wraps a <see cref="Utf8Span"/> instance around the provided <paramref name="buffer"/>,
/// skipping validation of the input data.
/// </summary>
/// <remarks>
/// Callers must uphold the following two invariants:
///
/// (a) <paramref name="buffer"/> consists only of well-formed UTF-8 data and does
/// not contain invalid or incomplete UTF-8 subsequences; and
/// (b) the contents of <paramref name="buffer"/> will not change for the duration
/// of the returned <see cref="Utf8Span"/>'s existence.
///
/// If these invariants are not maintained, the runtime may exhibit undefined behavior.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Utf8Span UnsafeCreateWithoutValidation(ReadOnlySpan<byte> buffer)
{
return new Utf8Span(buffer);
}
}
}
| |
// 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.RecoveryServices.Backup
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// JobCancellationsOperations operations.
/// </summary>
internal partial class JobCancellationsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IJobCancellationsOperations
{
/// <summary>
/// Initializes a new instance of the JobCancellationsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal JobCancellationsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Cancels a job. This is an asynchronous operation. To know the status of
/// the cancellation, call GetCancelOperationResult API.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='jobName'>
/// Name of the job to cancel.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> TriggerWithHttpMessagesAsync(string vaultName, string resourceGroupName, string jobName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (jobName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "jobName");
}
string apiVersion = "2016-06-01";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Trigger", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs/{jobName}/cancel").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Zlib.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2011 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-August-03 19:52:28>
//
// ------------------------------------------------------------------
//
// This module defines classes for ZLIB compression and
// decompression. This code is derived from the jzlib implementation of
// zlib, but significantly modified. The object model is not the same,
// and many of the behaviors are new or different. Nonetheless, in
// keeping with the license for jzlib, the copyright to that code is
// included below.
//
// ------------------------------------------------------------------
//
// The following notice applies to jzlib:
//
// Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
//
// 3. The names of the authors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
// INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
//
// -----------------------------------------------------------------------
//
// jzlib is based on zlib-1.1.3.
//
// The following notice applies to zlib:
//
// -----------------------------------------------------------------------
//
// Copyright (C) 1995-2004 Jean-loup Gailly and Mark Adler
//
// The ZLIB software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Jean-loup Gailly jloup@gzip.org
// Mark Adler madler@alumni.caltech.edu
//
// -----------------------------------------------------------------------
using System;
using Interop=System.Runtime.InteropServices;
namespace Ionic.Zlib
{
/// <summary>
/// Describes how to flush the current deflate operation.
/// </summary>
/// <remarks>
/// The different FlushType values are useful when using a Deflate in a streaming application.
/// </remarks>
public enum FlushType
{
/// <summary>No flush at all.</summary>
None = 0,
/// <summary>Closes the current block, but doesn't flush it to
/// the output. Used internally only in hypothetical
/// scenarios. This was supposed to be removed by Zlib, but it is
/// still in use in some edge cases.
/// </summary>
Partial,
/// <summary>
/// Use this during compression to specify that all pending output should be
/// flushed to the output buffer and the output should be aligned on a byte
/// boundary. You might use this in a streaming communication scenario, so that
/// the decompressor can get all input data available so far. When using this
/// with a ZlibCodec, <c>AvailableBytesIn</c> will be zero after the call if
/// enough output space has been provided before the call. Flushing will
/// degrade compression and so it should be used only when necessary.
/// </summary>
Sync,
/// <summary>
/// Use this during compression to specify that all output should be flushed, as
/// with <c>FlushType.Sync</c>, but also, the compression state should be reset
/// so that decompression can restart from this point if previous compressed
/// data has been damaged or if random access is desired. Using
/// <c>FlushType.Full</c> too often can significantly degrade the compression.
/// </summary>
Full,
/// <summary>Signals the end of the compression/decompression stream.</summary>
Finish,
}
/// <summary>
/// The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress.
/// </summary>
public enum CompressionLevel
{
/// <summary>
/// None means that the data will be simply stored, with no change at all.
/// If you are producing ZIPs for use on Mac OSX, be aware that archives produced with CompressionLevel.None
/// cannot be opened with the default zip reader. Use a different CompressionLevel.
/// </summary>
None= 0,
/// <summary>
/// Same as None.
/// </summary>
Level0 = 0,
/// <summary>
/// The fastest but least effective compression.
/// </summary>
BestSpeed = 1,
/// <summary>
/// A synonym for BestSpeed.
/// </summary>
Level1 = 1,
/// <summary>
/// A little slower, but better, than level 1.
/// </summary>
Level2 = 2,
/// <summary>
/// A little slower, but better, than level 2.
/// </summary>
Level3 = 3,
/// <summary>
/// A little slower, but better, than level 3.
/// </summary>
Level4 = 4,
/// <summary>
/// A little slower than level 4, but with better compression.
/// </summary>
Level5 = 5,
/// <summary>
/// The default compression level, with a good balance of speed and compression efficiency.
/// </summary>
Default = 6,
/// <summary>
/// A synonym for Default.
/// </summary>
Level6 = 6,
/// <summary>
/// Pretty good compression!
/// </summary>
Level7 = 7,
/// <summary>
/// Better compression than Level7!
/// </summary>
Level8 = 8,
/// <summary>
/// The "best" compression, where best means greatest reduction in size of the input data stream.
/// This is also the slowest compression.
/// </summary>
BestCompression = 9,
/// <summary>
/// A synonym for BestCompression.
/// </summary>
Level9 = 9,
}
/// <summary>
/// Describes options for how the compression algorithm is executed. Different strategies
/// work better on different sorts of data. The strategy parameter can affect the compression
/// ratio and the speed of compression but not the correctness of the compresssion.
/// </summary>
public enum CompressionStrategy
{
/// <summary>
/// The default strategy is probably the best for normal data.
/// </summary>
Default = 0,
/// <summary>
/// The <c>Filtered</c> strategy is intended to be used most effectively with data produced by a
/// filter or predictor. By this definition, filtered data consists mostly of small
/// values with a somewhat random distribution. In this case, the compression algorithm
/// is tuned to compress them better. The effect of <c>Filtered</c> is to force more Huffman
/// coding and less string matching; it is a half-step between <c>Default</c> and <c>HuffmanOnly</c>.
/// </summary>
Filtered = 1,
/// <summary>
/// Using <c>HuffmanOnly</c> will force the compressor to do Huffman encoding only, with no
/// string matching.
/// </summary>
HuffmanOnly = 2,
}
/// <summary>
/// An enum to specify the direction of transcoding - whether to compress or decompress.
/// </summary>
public enum CompressionMode
{
/// <summary>
/// Used to specify that the stream should compress the data.
/// </summary>
Compress= 0,
/// <summary>
/// Used to specify that the stream should decompress the data.
/// </summary>
Decompress = 1,
}
/// <summary>
/// A general purpose exception class for exceptions in the Zlib library.
/// </summary>
#if !PCL
[Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000E")]
#endif
public class ZlibException : System.Exception
{
/// <summary>
/// The ZlibException class captures exception information generated
/// by the Zlib library.
/// </summary>
public ZlibException()
: base()
{
}
/// <summary>
/// This ctor collects a message attached to the exception.
/// </summary>
/// <param name="s">the message for the exception.</param>
public ZlibException(System.String s)
: base(s)
{
}
}
internal class SharedUtils
{
/// <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);
}
#if NOT
/// <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) ((UInt64)number >> bits);
}
#endif
/// <summary>
/// Reads a number of characters from the current source TextReader and writes
/// the data to the target array at the specified index.
/// </summary>
///
/// <param name="sourceTextReader">The source TextReader to read from</param>
/// <param name="target">Contains the array of characteres read from the source TextReader.</param>
/// <param name="start">The starting index of the target array.</param>
/// <param name="count">The maximum number of characters to read from the source TextReader.</param>
///
/// <returns>
/// The number of characters read. The number will be less than or equal to
/// count depending on the data available in the source TextReader. Returns -1
/// if the end of the stream is reached.
/// </returns>
public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count)
{
// Returns 0 bytes if not enough space in target
if (target.Length == 0) return 0;
char[] charArray = new char[target.Length];
int bytesRead = sourceTextReader.Read(charArray, start, count);
// Returns -1 if EOF
if (bytesRead == 0) return -1;
for (int index = start; index < start + bytesRead; index++)
target[index] = (byte)charArray[index];
return bytesRead;
}
internal static byte[] ToByteArray(System.String sourceString)
{
return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString);
}
internal static char[] ToCharArray(byte[] byteArray)
{
return System.Text.UTF8Encoding.UTF8.GetChars(byteArray);
}
}
internal static class InternalConstants
{
internal static readonly int MAX_BITS = 15;
internal static readonly int BL_CODES = 19;
internal static readonly int D_CODES = 30;
internal static readonly int LITERALS = 256;
internal static readonly int LENGTH_CODES = 29;
internal static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES);
// Bit length codes must not exceed MAX_BL_BITS bits
internal static readonly int MAX_BL_BITS = 7;
// repeat previous bit length 3-6 times (2 bits of repeat count)
internal static readonly int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
internal static readonly int REPZ_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
internal static readonly int REPZ_11_138 = 18;
}
internal sealed class StaticTree
{
internal static readonly short[] lengthAndLiteralsTreeCodes = new short[] {
12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8,
28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8,
2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8,
18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8,
10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8,
26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8,
6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8,
22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8,
14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8,
30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8,
1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8,
17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8,
9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8,
25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8,
5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8,
21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8,
13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8,
29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8,
19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9,
51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9,
11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9,
43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9,
27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9,
59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9,
7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9,
39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9,
23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9,
55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9,
15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9,
47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9,
31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9,
63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9,
0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7,
8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7,
4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7,
3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8
};
internal static readonly short[] distTreeCodes = new short[] {
0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5,
2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5,
1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5,
3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 };
internal static readonly StaticTree Literals;
internal static readonly StaticTree Distances;
internal static readonly StaticTree BitLengths;
internal short[] treeCodes; // static tree or null
internal int[] extraBits; // extra bits for each code or null
internal int extraBase; // base index for extra_bits
internal int elems; // max number of elements in the tree
internal int maxLength; // max bit length for the codes
private StaticTree(short[] treeCodes, int[] extraBits, int extraBase, int elems, int maxLength)
{
this.treeCodes = treeCodes;
this.extraBits = extraBits;
this.extraBase = extraBase;
this.elems = elems;
this.maxLength = maxLength;
}
static StaticTree()
{
Literals = new StaticTree(lengthAndLiteralsTreeCodes, Tree.ExtraLengthBits, InternalConstants.LITERALS + 1, InternalConstants.L_CODES, InternalConstants.MAX_BITS);
Distances = new StaticTree(distTreeCodes, Tree.ExtraDistanceBits, 0, InternalConstants.D_CODES, InternalConstants.MAX_BITS);
BitLengths = new StaticTree(null, Tree.extra_blbits, 0, InternalConstants.BL_CODES, InternalConstants.MAX_BL_BITS);
}
}
/// <summary>
/// Computes an Adler-32 checksum.
/// </summary>
/// <remarks>
/// The Adler checksum is similar to a CRC checksum, but faster to compute, though less
/// reliable. It is used in producing RFC1950 compressed streams. The Adler checksum
/// is a required part of the "ZLIB" standard. Applications will almost never need to
/// use this class directly.
/// </remarks>
///
/// <exclude/>
public sealed class Adler
{
// largest prime smaller than 65536
private static readonly uint BASE = 65521;
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
private static readonly int NMAX = 5552;
#pragma warning disable 3001
#pragma warning disable 3002
/// <summary>
/// Calculates the Adler32 checksum.
/// </summary>
/// <remarks>
/// <para>
/// This is used within ZLIB. You probably don't need to use this directly.
/// </para>
/// </remarks>
/// <example>
/// To compute an Adler32 checksum on a byte array:
/// <code>
/// var adler = Adler.Adler32(0, null, 0, 0);
/// adler = Adler.Adler32(adler, buffer, index, length);
/// </code>
/// </example>
public static uint Adler32(uint adler, byte[] buf, int index, int len)
{
if (buf == null)
return 1;
uint s1 = (uint) (adler & 0xffff);
uint s2 = (uint) ((adler >> 16) & 0xffff);
while (len > 0)
{
int k = len < NMAX ? len : NMAX;
len -= k;
while (k >= 16)
{
//s1 += (buf[index++] & 0xff); s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
s1 += buf[index++]; s2 += s1;
k -= 16;
}
if (k != 0)
{
do
{
s1 += buf[index++];
s2 += s1;
}
while (--k != 0);
}
s1 %= BASE;
s2 %= BASE;
}
return (uint)((s2 << 16) | s1);
}
#pragma warning restore 3001
#pragma warning restore 3002
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void TestAllZerosInt64()
{
var test = new BooleanBinaryOpTest__TestAllZerosInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestAllZerosInt64
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int64);
private const int Op2ElementCount = VectorSize / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector128<Int64> _clsVar1;
private static Vector128<Int64> _clsVar2;
private Vector128<Int64> _fld1;
private Vector128<Int64> _fld2;
private BooleanBinaryOpTest__DataTable<Int64, Int64> _dataTable;
static BooleanBinaryOpTest__TestAllZerosInt64()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
}
public BooleanBinaryOpTest__TestAllZerosInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new BooleanBinaryOpTest__DataTable<Int64, Int64>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestAllZeros(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestAllZeros(
Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestAllZeros(
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestAllZeros), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestAllZeros), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestAllZeros), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestAllZeros(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr);
var result = Sse41.TestAllZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr));
var result = Sse41.TestAllZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr));
var result = Sse41.TestAllZeros(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanBinaryOpTest__TestAllZerosInt64();
var result = Sse41.TestAllZeros(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestAllZeros(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int64> left, Vector128<Int64> right, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((left[i] & right[i]) == 0);
}
if (expectedResult != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestAllZeros)}<Int64>(Vector128<Int64>, Vector128<Int64>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ValueExpressions.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Common.CommandTrees
{
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Common.CommandTrees.Internal;
using System.Data.Metadata.Edm;
using System.Diagnostics;
/// <summary>
/// Represents a constant value.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbConstantExpression : DbExpression
{
private readonly bool _shouldCloneValue;
private readonly object _value;
internal DbConstantExpression(TypeUsage resultType, object value)
: base(DbExpressionKind.Constant, resultType)
{
Debug.Assert(value != null, "DbConstantExpression value cannot be null");
Debug.Assert(TypeSemantics.IsScalarType(resultType), "DbConstantExpression must have a primitive or enum value");
Debug.Assert(!value.GetType().IsEnum || TypeSemantics.IsEnumerationType(resultType), "value is an enum while the result type is not of enum type.");
Debug.Assert(Helper.AsPrimitive(resultType.EdmType).ClrEquivalentType == (value.GetType().IsEnum ? value.GetType().GetEnumUnderlyingType() : value.GetType()),
"the type of the value has to match the result type (for enum types only underlying types are compared).");
// binary values should be cloned before use
PrimitiveType primitiveType;
this._shouldCloneValue = TypeHelpers.TryGetEdmType<PrimitiveType>(resultType, out primitiveType)
&& primitiveType.PrimitiveTypeKind == PrimitiveTypeKind.Binary;
if (this._shouldCloneValue)
{
// DevDiv#480416: DbConstantExpression with a binary value is not fully immutable
//
this._value = ((byte[])value).Clone();
}
else
{
this._value = value;
}
}
/// <summary>
/// Provides direct access to the constant value, even for byte[] constants.
/// </summary>
/// <returns>The object value contained by this constant expression, not a copy.</returns>
internal object GetValue()
{
return this._value;
}
/// <summary>
/// Gets the constant value.
/// </summary>
public object Value
{
get
{
// DevDiv#480416: DbConstantExpression with a binary value is not fully immutable
//
if (this._shouldCloneValue)
{
return ((byte[])_value).Clone();
}
else
{
return _value;
}
}
}
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
/// <summary>
/// Represents null.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbNullExpression : DbExpression
{
internal DbNullExpression(TypeUsage type)
: base(DbExpressionKind.Null, type)
{
}
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
/// <summary>
/// Represents a reference to a variable that is currently in scope.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbVariableReferenceExpression : DbExpression
{
private readonly string _name;
internal DbVariableReferenceExpression(TypeUsage type, string name)
: base(DbExpressionKind.VariableReference, type)
{
Debug.Assert(name != null, "DbVariableReferenceExpression Name cannot be null");
this._name = name;
}
/// <summary>
/// Gets the name of the referenced variable.
/// </summary>
public string VariableName { get { return _name; } }
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
/// <summary>
/// Represents a reference to a parameter declared on the command tree that contains this expression.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbParameterReferenceExpression : DbExpression
{
private readonly string _name;
internal DbParameterReferenceExpression(TypeUsage type, string name)
: base(DbExpressionKind.ParameterReference, type)
{
Debug.Assert(DbCommandTree.IsValidParameterName(name), "DbParameterReferenceExpression name should be valid");
this._name = name;
}
/// <summary>
/// Gets the name of the referenced parameter.
/// </summary>
public string ParameterName { get { return _name; } }
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
/// <summary>
/// Represents the retrieval of a static or instance property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbPropertyExpression : DbExpression
{
private readonly EdmMember _property;
private readonly DbExpression _instance;
internal DbPropertyExpression(TypeUsage resultType, EdmMember property, DbExpression instance)
: base(DbExpressionKind.Property, resultType)
{
Debug.Assert(property != null, "DbPropertyExpression property cannot be null");
Debug.Assert(instance != null, "DbPropertyExpression instance cannot be null");
Debug.Assert(Helper.IsEdmProperty(property) ||
Helper.IsRelationshipEndMember(property) ||
Helper.IsNavigationProperty(property), "DbExpression property must be a property, navigation property, or relationship end");
this._property = property;
this._instance = instance;
}
/// <summary>
/// Gets the property metadata for the property to retrieve.
/// </summary>
public EdmMember Property { get { return _property; } }
/// <summary>
/// Gets the <see cref="DbExpression"/> that defines the instance from which the property should be retrieved.
/// </summary>
public DbExpression Instance { get { return _instance; } }
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// Creates a new KeyValuePair<string, DbExpression> based on this property expression.
/// The string key will be the name of the referenced property, while the DbExpression value will be the property expression itself.
/// </summary>
/// <returns>A new KeyValuePair<string, DbExpression> with key and value derived from the DbPropertyExpression</returns>
public KeyValuePair<string, DbExpression> ToKeyValuePair()
{
return new KeyValuePair<string, DbExpression>(this.Property.Name, this);
}
public static implicit operator KeyValuePair<string, DbExpression>(DbPropertyExpression value)
{
EntityUtil.CheckArgumentNull(value, "value");
return value.ToKeyValuePair();
}
}
/// <summary>
/// Represents the invocation of a function.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbFunctionExpression : DbExpression
{
private readonly EdmFunction _functionInfo;
private readonly DbExpressionList _arguments;
internal DbFunctionExpression(TypeUsage resultType, EdmFunction function, DbExpressionList arguments)
: base(DbExpressionKind.Function, resultType)
{
Debug.Assert(function != null, "DbFunctionExpression function cannot be null");
Debug.Assert(arguments != null, "DbFunctionExpression arguments cannot be null");
Debug.Assert(object.ReferenceEquals(resultType, function.ReturnParameter.TypeUsage), "DbFunctionExpression result type must be function return type");
this._functionInfo = function;
this._arguments = arguments;
}
/// <summary>
/// Gets the metadata for the function to invoke.
/// </summary>
public EdmFunction Function { get { return _functionInfo; } }
/// <summary>
/// Gets an <see cref="DbExpression"/> list that provides the arguments to the function.
/// </summary>
public IList<DbExpression> Arguments { get { return this._arguments; } }
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
/// <summary>
/// Represents the application of a Lambda function.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbLambdaExpression : DbExpression
{
private readonly DbLambda _lambda;
private readonly DbExpressionList _arguments;
internal DbLambdaExpression(TypeUsage resultType, DbLambda lambda, DbExpressionList args)
: base(DbExpressionKind.Lambda, resultType)
{
Debug.Assert(lambda != null, "DbLambdaExpression lambda cannot be null");
Debug.Assert(args != null, "DbLambdaExpression arguments cannot be null");
Debug.Assert(object.ReferenceEquals(resultType, lambda.Body.ResultType), "DbLambdaExpression result type must be Lambda body result type");
Debug.Assert(lambda.Variables.Count == args.Count, "DbLambdaExpression argument count does not match Lambda parameter count");
this._lambda = lambda;
this._arguments = args;
}
/// <summary>
/// Gets the <see cref="DbLambda"/> representing the Lambda function applied by this expression.
/// </summary>
public DbLambda Lambda { get { return _lambda; } }
/// <summary>
/// Gets a <see cref="DbExpression"/> list that provides the arguments to which the Lambda function should be applied.
/// </summary>
public IList<DbExpression> Arguments { get { return this._arguments; } }
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
#if METHOD_EXPRESSION
/// <summary>
/// Represents the invocation of a method.
/// </summary>
public sealed class MethodExpression : Expression
{
MethodMetadata m_methodInfo;
IList<Expression> m_args;
ExpressionLink m_inst;
internal MethodExpression(CommandTree cmdTree, MethodMetadata methodInfo, IList<Expression> args, Expression instance)
: base(cmdTree, ExpressionKind.Method)
{
//
// Ensure that the property metadata is non-null and from the same metadata workspace and dataspace as the command tree.
//
CommandTreeTypeHelper.CheckMember(methodInfo, "method", "methodInfo");
//
// Methods that return void are not allowed
//
if (cmdTree.TypeHelper.IsNullOrNullType(methodInfo.Type))
{
throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Method_VoidResultInvalid, "methodInfo");
}
if (null == args)
{
throw EntityUtil.ArgumentNull("args");
}
this.m_inst = new ExpressionLink("Instance", cmdTree);
//
// Validate the instance
//
if (methodInfo.IsStatic)
{
if (instance != null)
{
throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Method_InstanceInvalidForStatic, "instance");
}
}
else
{
if (null == instance)
{
throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_Method_InstanceRequiredForInstance, "instance");
}
this.m_inst.SetExpectedType(methodInfo.DefiningType);
this.m_inst.InitializeValue(instance);
}
//
// Validate the arguments
//
m_args = new ExpressionList("Arguments", cmdTree, methodInfo.Parameters, args);
m_methodInfo = methodInfo;
this.ResultType = methodInfo.Type;
}
/// <summary>
/// Gets the metadata for the method to invoke.
/// </summary>
public MethodMetadata Method { get { return m_methodInfo; } }
/// <summary>
/// Gets the expressions that provide the arguments to the method.
/// </summary>
public IList<Expression> Arguments { get { return m_args; } }
/// <summary>
/// Gets or sets an <see cref="Expression"/> that defines the instance on which the method should be invoked. Must be null for instance methods.
/// For static properties, <code>Instance</code> will always be null, and attempting to set a new value will result
/// in <see cref="NotSupportedException"/>.
/// </summary>
/// <exception cref="ArgumentNullException">The expression is null</exception>
/// <exception cref="NotSupportedException">The method is static</exception>
/// <exception cref="ArgumentException">
/// The expression is not associated with the MethodExpression's command tree,
/// or its result type is not equal or promotable to the type that defines the method
/// </exception>
public Expression Instance
{
get { return m_inst.Expression; }
/*CQT_PUBLIC_API(*/internal/*)*/ set
{
if (this.m_methodInfo.IsStatic)
{
throw EntityUtil.NotSupported(System.Data.Entity.Strings.Cqt_Method_InstanceInvalidForStatic);
}
this.m_inst.Expression = value;
}
}
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of ExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(ExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed ExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
#endif
/// <summary>
/// Represents the navigation of a (composition or association) relationship given the 'from' role, the 'to' role and an instance of the from role
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbRelationshipNavigationExpression : DbExpression
{
private readonly RelationshipType _relation;
private readonly RelationshipEndMember _fromRole;
private readonly RelationshipEndMember _toRole;
private readonly DbExpression _from;
internal DbRelationshipNavigationExpression(
TypeUsage resultType,
RelationshipType relType,
RelationshipEndMember fromEnd,
RelationshipEndMember toEnd,
DbExpression navigateFrom)
: base(DbExpressionKind.RelationshipNavigation, resultType)
{
Debug.Assert(relType != null, "DbRelationshipNavigationExpression relationship type cannot be null");
Debug.Assert(fromEnd != null, "DbRelationshipNavigationExpression 'from' end cannot be null");
Debug.Assert(toEnd != null, "DbRelationshipNavigationExpression 'to' end cannot be null");
Debug.Assert(navigateFrom != null, "DbRelationshipNavigationExpression navigation source cannot be null");
this._relation = relType;
this._fromRole = fromEnd;
this._toRole = toEnd;
this._from = navigateFrom;
}
/// <summary>
/// Gets the metadata for the relationship over which navigation occurs
/// </summary>
public RelationshipType Relationship { get { return _relation; } }
/// <summary>
/// Gets the metadata for the relationship end to navigate from
/// </summary>
public RelationshipEndMember NavigateFrom { get { return _fromRole; } }
/// <summary>
/// Gets the metadata for the relationship end to navigate to
/// </summary>
public RelationshipEndMember NavigateTo { get { return _toRole; } }
/// <summary>
/// Gets the <see cref="DbExpression"/> that specifies the instance of the 'from' relationship end from which navigation should occur.
/// </summary>
public DbExpression NavigationSource { get { return _from; } }
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
/// <summary>
/// Encapsulates the result (represented as a Ref to the resulting Entity) of navigating from
/// the specified source end of a relationship to the specified target end. This class is intended
/// for use only with <see cref="DbNewInstanceExpression"/>, where an 'owning' instance of that class
/// represents the source Entity involved in the relationship navigation.
/// Instances of DbRelatedEntityRef may be specified when creating a <see cref="DbNewInstanceExpression"/> that
/// constructs an Entity, allowing information about Entities that are related to the newly constructed Entity to be captured.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
internal sealed class DbRelatedEntityRef
{
private readonly RelationshipEndMember _sourceEnd;
private readonly RelationshipEndMember _targetEnd;
private readonly DbExpression _targetEntityRef;
internal DbRelatedEntityRef(RelationshipEndMember sourceEnd, RelationshipEndMember targetEnd, DbExpression targetEntityRef)
{
// Validate that the specified relationship ends are:
// 1. Non-null
// 2. From the same metadata workspace as that used by the command tree
EntityUtil.CheckArgumentNull(sourceEnd, "sourceEnd");
EntityUtil.CheckArgumentNull(targetEnd, "targetEnd");
// Validate that the specified target entity ref is:
// 1. Non-null
EntityUtil.CheckArgumentNull(targetEntityRef, "targetEntityRef");
// Validate that the specified source and target ends are:
// 1. Declared by the same relationship type
if (!object.ReferenceEquals(sourceEnd.DeclaringType, targetEnd.DeclaringType))
{
throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEndFromDifferentRelationship, "targetEnd");
}
// 2. Not the same end
if (object.ReferenceEquals(sourceEnd, targetEnd))
{
throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEndSameAsSourceEnd, "targetEnd");
}
// Validate that the specified target end has multiplicity of at most one
if (targetEnd.RelationshipMultiplicity != RelationshipMultiplicity.One &&
targetEnd.RelationshipMultiplicity != RelationshipMultiplicity.ZeroOrOne)
{
throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEndMustBeAtMostOne, "targetEnd");
}
// Validate that the specified target entity ref actually has a ref result type
if (!TypeSemantics.IsReferenceType(targetEntityRef.ResultType))
{
throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEntityNotRef, "targetEntityRef");
}
// Validate that the specified target entity is of a type that can be reached by navigating to the specified relationship end
EntityTypeBase endType = TypeHelpers.GetEdmType<RefType>(targetEnd.TypeUsage).ElementType;
EntityTypeBase targetType = TypeHelpers.GetEdmType<RefType>(targetEntityRef.ResultType).ElementType;
//
if (!endType.EdmEquals(targetType) && !TypeSemantics.IsSubTypeOf(targetType, endType))
{
throw EntityUtil.Argument(System.Data.Entity.Strings.Cqt_RelatedEntityRef_TargetEntityNotCompatible, "targetEntityRef");
}
// Validation succeeded, initialize state
_targetEntityRef = targetEntityRef;
_targetEnd = targetEnd;
_sourceEnd = sourceEnd;
}
/// <summary>
/// Retrieves the 'source' end of the relationship navigation satisfied by this related entity Ref
/// </summary>
internal RelationshipEndMember SourceEnd { get { return _sourceEnd; } }
/// <summary>
/// Retrieves the 'target' end of the relationship navigation satisfied by this related entity Ref
/// </summary>
internal RelationshipEndMember TargetEnd { get { return _targetEnd; } }
/// <summary>
/// Retrieves the entity Ref that is the result of navigating from the source to the target end of this related entity Ref
/// </summary>
internal DbExpression TargetEntityReference { get { return _targetEntityRef; } }
}
/// <summary>
/// Represents the construction of a new instance of a given type, including set and record types.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbNewInstanceExpression : DbExpression
{
private readonly DbExpressionList _elements;
private readonly System.Collections.ObjectModel.ReadOnlyCollection<DbRelatedEntityRef> _relatedEntityRefs;
internal DbNewInstanceExpression(TypeUsage type, DbExpressionList args)
: base(DbExpressionKind.NewInstance, type)
{
Debug.Assert(args != null, "DbNewInstanceExpression arguments cannot be null");
Debug.Assert(args.Count > 0 || TypeSemantics.IsCollectionType(type), "DbNewInstanceExpression requires at least one argument when not creating an empty collection");
this._elements = args;
}
internal DbNewInstanceExpression(TypeUsage resultType, DbExpressionList attributeValues, System.Collections.ObjectModel.ReadOnlyCollection<DbRelatedEntityRef> relationships)
: this(resultType, attributeValues)
{
Debug.Assert(TypeSemantics.IsEntityType(resultType), "An entity type is required to create a NewEntityWithRelationships expression");
Debug.Assert(relationships != null, "Related entity ref collection cannot be null");
this._relatedEntityRefs = (relationships.Count > 0 ? relationships : null);
}
/// <summary>
/// Gets an <see cref="DbExpression"/> list that provides the property/column values or set elements for the new instance.
/// </summary>
public IList<DbExpression> Arguments { get { return _elements; } }
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
internal bool HasRelatedEntityReferences { get { return (_relatedEntityRefs != null); } }
/// <summary>
/// Gets the related entity references (if any) for an entity constructor.
/// May be null if no related entities were specified - use the <see cref="HasRelatedEntityReferences"/> property to determine this.
/// </summary>
internal System.Collections.ObjectModel.ReadOnlyCollection<DbRelatedEntityRef> RelatedEntityReferences { get { return _relatedEntityRefs; } }
}
/// <summary>
/// Represents a (strongly typed) reference to a specific instance within a given entity set.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbRefExpression : DbUnaryExpression
{
private readonly EntitySet _entitySet;
internal DbRefExpression(TypeUsage refResultType, EntitySet entitySet, DbExpression refKeys)
: base(DbExpressionKind.Ref, refResultType, refKeys)
{
Debug.Assert(TypeSemantics.IsReferenceType(refResultType), "DbRefExpression requires a reference result type");
this._entitySet = entitySet;
}
/// <summary>
/// Gets the metadata for the entity set that contains the instance.
/// </summary>
public EntitySet EntitySet { get { return _entitySet; } }
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
/// <summary>
/// Represents the retrieval of a given entity using the specified Ref.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Deref"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbDerefExpression : DbUnaryExpression
{
internal DbDerefExpression(TypeUsage entityResultType, DbExpression refExpr)
: base(DbExpressionKind.Deref, entityResultType, refExpr)
{
Debug.Assert(TypeSemantics.IsEntityType(entityResultType), "DbDerefExpression requires an entity result type");
}
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
/// <summary>
/// Represents a 'scan' of all elements of a given entity set.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public sealed class DbScanExpression : DbExpression
{
private readonly EntitySetBase _targetSet;
internal DbScanExpression(TypeUsage collectionOfEntityType, EntitySetBase entitySet)
: base(DbExpressionKind.Scan, collectionOfEntityType)
{
Debug.Assert(entitySet != null, "DbScanExpression entity set cannot be null");
this._targetSet = entitySet;
}
/// <summary>
/// Gets the metadata for the referenced entity or relationship set.
/// </summary>
public EntitySetBase Target { get { return _targetSet; } }
/// <summary>
/// The visitor pattern method for expression visitors that do not produce a result value.
/// </summary>
/// <param name="visitor">An instance of DbExpressionVisitor.</param>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
public override void Accept(DbExpressionVisitor visitor) { if (visitor != null) { visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
/// <summary>
/// The visitor pattern method for expression visitors that produce a result value of a specific type.
/// </summary>
/// <param name="visitor">An instance of a typed DbExpressionVisitor that produces a result value of type TResultType.</param>
/// <typeparam name="TResultType">The type of the result produced by <paramref name="visitor"/></typeparam>
/// <exception cref="ArgumentNullException"><paramref name="visitor"/> is null</exception>
/// <returns>An instance of <typeparamref name="TResultType"/>.</returns>
public override TResultType Accept<TResultType>(DbExpressionVisitor<TResultType> visitor) { if (visitor != null) { return visitor.Visit(this); } else { throw EntityUtil.ArgumentNull("visitor"); } }
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenMetaverse.StructuredData;
using Nwc.XmlRpc;
using log4net;
using OpenSim.Services.Connectors.Simulation;
namespace OpenSim.Services.Connectors.Hypergrid
{
public class GatekeeperServiceConnector : SimulationServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static UUID m_HGMapImage = new UUID("00000000-0000-1111-9999-000000000013");
private IAssetService m_AssetService;
public GatekeeperServiceConnector() : base()
{
}
public GatekeeperServiceConnector(IAssetService assService)
{
m_AssetService = assService;
}
protected override string AgentPath()
{
return "foreignagent/";
}
protected override string ObjectPath()
{
return "foreignobject/";
}
public bool LinkRegion(GridRegion info, out UUID regionID, out ulong realHandle, out string externalName, out string imageURL, out string reason)
{
regionID = UUID.Zero;
imageURL = string.Empty;
realHandle = 0;
externalName = string.Empty;
reason = string.Empty;
Hashtable hash = new Hashtable();
hash["region_name"] = info.RegionName;
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("link_region", paramList);
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Linking to " + info.ServerURI);
XmlRpcResponse response = null;
try
{
response = request.Send(info.ServerURI, 10000);
}
catch (Exception e)
{
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Exception " + e.Message);
reason = "Error contacting remote server";
return false;
}
if (response.IsFault)
{
reason = response.FaultString;
m_log.ErrorFormat("[GATEKEEPER SERVICE CONNECTOR]: remote call returned an error: {0}", response.FaultString);
return false;
}
hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
bool success = false;
Boolean.TryParse((string)hash["result"], out success);
if (success)
{
UUID.TryParse((string)hash["uuid"], out regionID);
//m_log.Debug(">> HERE, uuid: " + regionID);
if ((string)hash["handle"] != null)
{
realHandle = Convert.ToUInt64((string)hash["handle"]);
//m_log.Debug(">> HERE, realHandle: " + realHandle);
}
if (hash["region_image"] != null) {
imageURL = (string)hash["region_image"];
//m_log.Debug(">> HERE, imageURL: " + imageURL);
}
if (hash["external_name"] != null) {
externalName = (string)hash["external_name"];
//m_log.Debug(">> HERE, externalName: " + externalName);
}
}
}
catch (Exception e)
{
reason = "Error parsing return arguments";
m_log.Error("[GATEKEEPER SERVICE CONNECTOR]: Got exception while parsing hyperlink response " + e.StackTrace);
return false;
}
return true;
}
public UUID GetMapImage(UUID regionID, string imageURL, string storagePath)
{
if (m_AssetService == null)
{
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: No AssetService defined. Map tile not retrieved.");
return m_HGMapImage;
}
UUID mapTile = m_HGMapImage;
string filename = string.Empty;
Bitmap bitmap = null;
try
{
WebClient c = new WebClient();
string name = regionID.ToString();
filename = Path.Combine(storagePath, name + ".jpg");
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: Map image at {0}, cached at {1}", imageURL, filename);
if (!File.Exists(filename))
{
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: downloading...");
c.DownloadFile(imageURL, filename);
}
else
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: using cached image");
bitmap = new Bitmap(filename);
//m_log.Debug("Size: " + m.PhysicalDimension.Height + "-" + m.PhysicalDimension.Width);
byte[] imageData = OpenJPEG.EncodeFromImage(bitmap, true);
AssetBase ass = new AssetBase(UUID.Random(), "region " + name, (sbyte)AssetType.Texture, regionID.ToString());
// !!! for now
//info.RegionSettings.TerrainImageID = ass.FullID;
ass.Data = imageData;
mapTile = ass.FullID;
// finally
m_AssetService.Store(ass);
}
catch // LEGIT: Catching problems caused by OpenJPEG p/invoke
{
m_log.Info("[GATEKEEPER SERVICE CONNECTOR]: Failed getting/storing map image, because it is probably already in the cache");
}
return mapTile;
}
public GridRegion GetHyperlinkRegion(GridRegion gatekeeper, UUID regionID)
{
Hashtable hash = new Hashtable();
hash["region_uuid"] = regionID.ToString();
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("get_region", paramList);
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: contacting " + gatekeeper.ServerURI);
XmlRpcResponse response = null;
try
{
response = request.Send(gatekeeper.ServerURI, 10000);
}
catch (Exception e)
{
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Exception " + e.Message);
return null;
}
if (response.IsFault)
{
m_log.ErrorFormat("[GATEKEEPER SERVICE CONNECTOR]: remote call returned an error: {0}", response.FaultString);
return null;
}
hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
bool success = false;
Boolean.TryParse((string)hash["result"], out success);
if (success)
{
GridRegion region = new GridRegion();
UUID.TryParse((string)hash["uuid"], out region.RegionID);
//m_log.Debug(">> HERE, uuid: " + region.RegionID);
int n = 0;
if (hash["x"] != null)
{
Int32.TryParse((string)hash["x"], out n);
region.RegionLocX = n;
//m_log.Debug(">> HERE, x: " + region.RegionLocX);
}
if (hash["y"] != null)
{
Int32.TryParse((string)hash["y"], out n);
region.RegionLocY = n;
//m_log.Debug(">> HERE, y: " + region.RegionLocY);
}
if (hash["region_name"] != null)
{
region.RegionName = (string)hash["region_name"];
//m_log.Debug(">> HERE, region_name: " + region.RegionName);
}
if (hash["hostname"] != null) {
region.ExternalHostName = (string)hash["hostname"];
//m_log.Debug(">> HERE, hostname: " + region.ExternalHostName);
}
if (hash["http_port"] != null)
{
uint p = 0;
UInt32.TryParse((string)hash["http_port"], out p);
region.HttpPort = p;
//m_log.Debug(">> HERE, http_port: " + region.HttpPort);
}
if (hash["internal_port"] != null)
{
int p = 0;
Int32.TryParse((string)hash["internal_port"], out p);
region.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), p);
//m_log.Debug(">> HERE, internal_port: " + region.InternalEndPoint);
}
if (hash["server_uri"] != null)
{
region.ServerURI = (string) hash["server_uri"];
//m_log.Debug(">> HERE, server_uri: " + region.ServerURI);
}
// Successful return
return region;
}
}
catch (Exception e)
{
m_log.Error("[GATEKEEPER SERVICE CONNECTOR]: Got exception while parsing hyperlink response " + e.StackTrace);
return null;
}
return null;
}
public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint flags, out string myipaddress, out string reason)
{
// m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: CreateAgent start");
myipaddress = String.Empty;
reason = String.Empty;
if (destination == null)
{
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Given destination is null");
return false;
}
string uri = destination.ServerURI + AgentPath() + aCircuit.AgentID + "/";
try
{
OSDMap args = aCircuit.PackAgentCircuitData();
args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
args["destination_name"] = OSD.FromString(destination.RegionName);
args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
args["teleport_flags"] = OSD.FromString(flags.ToString());
OSDMap result = WebUtil.PostToService(uri,args);
if (result["Success"].AsBoolean())
{
OSDMap unpacked = (OSDMap)result["_Result"];
if (unpacked != null)
{
reason = unpacked["reason"].AsString();
myipaddress = unpacked["your_ip"].AsString();
return unpacked["success"].AsBoolean();
}
}
reason = result["Message"] != null ? result["Message"].AsString() : "error";
return false;
}
catch (Exception e)
{
m_log.Warn("[REMOTE SIMULATION CONNECTOR]: CreateAgent failed with exception: " + e.ToString());
reason = e.Message;
}
return false;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/timestamp.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 Google.Protobuf.WellKnownTypes {
/// <summary>Holder for reflection information generated from google/protobuf/timestamp.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class TimestampReflection {
#region Descriptor
/// <summary>File descriptor for google/protobuf/timestamp.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TimestampReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJv",
"dG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MY",
"AiABKAVCVAoTY29tLmdvb2dsZS5wcm90b2J1ZkIOVGltZXN0YW1wUHJvdG9Q",
"AaABAfgBAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBl",
"c2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Timestamp), global::Google.Protobuf.WellKnownTypes.Timestamp.Parser, new[]{ "Seconds", "Nanos" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A Timestamp represents a point in time independent of any time zone
/// or calendar, represented as seconds and fractions of seconds at
/// nanosecond resolution in UTC Epoch time. It is encoded using the
/// Proleptic Gregorian Calendar which extends the Gregorian calendar
/// backwards to year one. It is encoded assuming all minutes are 60
/// seconds long, i.e. leap seconds are "smeared" so that no leap second
/// table is needed for interpretation. Range is from
/// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
/// By restricting to that range, we ensure that we can convert to
/// and from RFC 3339 date strings.
/// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
///
/// Example 1: Compute Timestamp from POSIX `time()`.
///
/// Timestamp timestamp;
/// timestamp.set_seconds(time(NULL));
/// timestamp.set_nanos(0);
///
/// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
///
/// struct timeval tv;
/// gettimeofday(&tv, NULL);
///
/// Timestamp timestamp;
/// timestamp.set_seconds(tv.tv_sec);
/// timestamp.set_nanos(tv.tv_usec * 1000);
///
/// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
///
/// FILETIME ft;
/// GetSystemTimeAsFileTime(&ft);
/// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
///
/// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
/// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
/// Timestamp timestamp;
/// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
/// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
///
/// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
///
/// long millis = System.currentTimeMillis();
///
/// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
/// .setNanos((int) ((millis % 1000) * 1000000)).build();
///
/// Example 5: Compute Timestamp from current time in Python.
///
/// now = time.time()
/// seconds = int(now)
/// nanos = int((now - seconds) * 10**9)
/// timestamp = Timestamp(seconds=seconds, nanos=nanos)
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Timestamp : pb::IMessage<Timestamp> {
private static readonly pb::MessageParser<Timestamp> _parser = new pb::MessageParser<Timestamp>(() => new Timestamp());
public static pb::MessageParser<Timestamp> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Timestamp() {
OnConstruction();
}
partial void OnConstruction();
public Timestamp(Timestamp other) : this() {
seconds_ = other.seconds_;
nanos_ = other.nanos_;
}
public Timestamp Clone() {
return new Timestamp(this);
}
/// <summary>Field number for the "seconds" field.</summary>
public const int SecondsFieldNumber = 1;
private long seconds_;
/// <summary>
/// Represents seconds of UTC time since Unix epoch
/// 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to
/// 9999-12-31T23:59:59Z inclusive.
/// </summary>
public long Seconds {
get { return seconds_; }
set {
seconds_ = value;
}
}
/// <summary>Field number for the "nanos" field.</summary>
public const int NanosFieldNumber = 2;
private int nanos_;
/// <summary>
/// Non-negative fractions of a second at nanosecond resolution. Negative
/// second values with fractions must still have non-negative nanos values
/// that count forward in time. Must be from 0 to 999,999,999
/// inclusive.
/// </summary>
public int Nanos {
get { return nanos_; }
set {
nanos_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as Timestamp);
}
public bool Equals(Timestamp other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Seconds != other.Seconds) return false;
if (Nanos != other.Nanos) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Seconds != 0L) hash ^= Seconds.GetHashCode();
if (Nanos != 0) hash ^= Nanos.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Seconds != 0L) {
output.WriteRawTag(8);
output.WriteInt64(Seconds);
}
if (Nanos != 0) {
output.WriteRawTag(16);
output.WriteInt32(Nanos);
}
}
public int CalculateSize() {
int size = 0;
if (Seconds != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Seconds);
}
if (Nanos != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos);
}
return size;
}
public void MergeFrom(Timestamp other) {
if (other == null) {
return;
}
if (other.Seconds != 0L) {
Seconds = other.Seconds;
}
if (other.Nanos != 0) {
Nanos = other.Nanos;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Seconds = input.ReadInt64();
break;
}
case 16: {
Nanos = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
#if ANDROID
#define REQUIRES_PRIMARY_THREAD_LOADING
#endif
using BitmapFont = FlatRedBall.Graphics.BitmapFont;
using Cursor = FlatRedBall.Gui.Cursor;
using GuiManager = FlatRedBall.Gui.GuiManager;
// Generated Usings
using FrbTicTacToe.Screens;
using FlatRedBall.Graphics;
using FlatRedBall.Math;
using FrbTicTacToe.Entities;
using FlatRedBall;
using FlatRedBall.Screens;
using System;
using System.Collections.Generic;
using System.Text;
#if XNA4 || WINDOWS_8
using Color = Microsoft.Xna.Framework.Color;
#elif FRB_MDX
using Color = System.Drawing.Color;
#else
using Color = Microsoft.Xna.Framework.Graphics.Color;
#endif
#if FRB_XNA || SILVERLIGHT
using Keys = Microsoft.Xna.Framework.Input.Keys;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
#endif
#if FRB_XNA && !MONODROID
using Model = Microsoft.Xna.Framework.Graphics.Model;
#endif
namespace FrbTicTacToe.Entities
{
public partial class AiSelector : PositionedObject, IDestroyable, IVisible
{
// This is made global so that static lazy-loaded content can access it.
public static string ContentManagerName
{
get;
set;
}
// Generated Fields
#if DEBUG
static bool HasBeenLoadedWithGlobalContentManager = false;
#endif
public enum VariableState
{
Uninitialized = 0, //This exists so that the first set call actually does something
Unknown = 1, //This exists so that if the entity is actually a child entity and has set a child state, you will get this
Easy = 2,
NormalOffensive = 3,
NormalDefensive = 4,
Hard = 5
}
protected int mCurrentState = 0;
public Entities.AiSelector.VariableState CurrentState
{
get
{
if (Enum.IsDefined(typeof(VariableState), mCurrentState))
{
return (VariableState)mCurrentState;
}
else
{
return VariableState.Unknown;
}
}
set
{
mCurrentState = (int)value;
switch(CurrentState)
{
case VariableState.Uninitialized:
break;
case VariableState.Unknown:
break;
case VariableState.Easy:
EasySelectionBlue = 0f;
HardSelectionBlue = 1f;
NormalDefensiveSelectionBlue = 1f;
NormalOffensiveSelectionBlue = 1f;
break;
case VariableState.NormalOffensive:
EasySelectionBlue = 1f;
HardSelectionBlue = 1f;
NormalDefensiveSelectionBlue = 1f;
NormalOffensiveSelectionBlue = 0f;
break;
case VariableState.NormalDefensive:
EasySelectionBlue = 1f;
HardSelectionBlue = 1f;
NormalDefensiveSelectionBlue = 0f;
NormalOffensiveSelectionBlue = 1f;
break;
case VariableState.Hard:
EasySelectionBlue = 1f;
HardSelectionBlue = 0f;
NormalDefensiveSelectionBlue = 1f;
NormalOffensiveSelectionBlue = 1f;
break;
}
}
}
static object mLockObject = new object();
static List<string> mRegisteredUnloads = new List<string>();
static List<string> LoadedContentManagers = new List<string>();
private FrbTicTacToe.Entities.Label EasySelection;
private FrbTicTacToe.Entities.Label NormalOffensiveSelection;
private FrbTicTacToe.Entities.Label NormalDefensiveSelection;
private FrbTicTacToe.Entities.Label HardSelection;
public float EasySelectionBlue
{
get
{
return EasySelection.Blue;
}
set
{
EasySelection.Blue = value;
}
}
public float HardSelectionBlue
{
get
{
return HardSelection.Blue;
}
set
{
HardSelection.Blue = value;
}
}
public float NormalDefensiveSelectionBlue
{
get
{
return NormalDefensiveSelection.Blue;
}
set
{
NormalDefensiveSelection.Blue = value;
}
}
public float NormalOffensiveSelectionBlue
{
get
{
return NormalOffensiveSelection.Blue;
}
set
{
NormalOffensiveSelection.Blue = value;
}
}
public event EventHandler BeforeVisibleSet;
public event EventHandler AfterVisibleSet;
protected bool mVisible = true;
public virtual bool Visible
{
get
{
return mVisible;
}
set
{
if (BeforeVisibleSet != null)
{
BeforeVisibleSet(this, null);
}
mVisible = value;
if (AfterVisibleSet != null)
{
AfterVisibleSet(this, null);
}
}
}
public bool IgnoresParentVisibility { get; set; }
public bool AbsoluteVisible
{
get
{
return Visible && (Parent == null || IgnoresParentVisibility || Parent is IVisible == false || (Parent as IVisible).AbsoluteVisible);
}
}
IVisible IVisible.Parent
{
get
{
if (this.Parent != null && this.Parent is IVisible)
{
return this.Parent as IVisible;
}
else
{
return null;
}
}
}
protected Layer LayerProvidedByContainer = null;
public AiSelector()
: this(FlatRedBall.Screens.ScreenManager.CurrentScreen.ContentManagerName, true)
{
}
public AiSelector(string contentManagerName) :
this(contentManagerName, true)
{
}
public AiSelector(string contentManagerName, bool addToManagers) :
base()
{
// Don't delete this:
ContentManagerName = contentManagerName;
InitializeEntity(addToManagers);
}
protected virtual void InitializeEntity(bool addToManagers)
{
// Generated Initialize
LoadStaticContent(ContentManagerName);
EasySelection = new FrbTicTacToe.Entities.Label(ContentManagerName, false);
EasySelection.Name = "EasySelection";
NormalOffensiveSelection = new FrbTicTacToe.Entities.Label(ContentManagerName, false);
NormalOffensiveSelection.Name = "NormalOffensiveSelection";
NormalDefensiveSelection = new FrbTicTacToe.Entities.Label(ContentManagerName, false);
NormalDefensiveSelection.Name = "NormalDefensiveSelection";
HardSelection = new FrbTicTacToe.Entities.Label(ContentManagerName, false);
HardSelection.Name = "HardSelection";
PostInitialize();
if (addToManagers)
{
AddToManagers(null);
}
}
// Generated AddToManagers
public virtual void ReAddToManagers (Layer layerToAddTo)
{
LayerProvidedByContainer = layerToAddTo;
SpriteManager.AddPositionedObject(this);
EasySelection.ReAddToManagers(LayerProvidedByContainer);
NormalOffensiveSelection.ReAddToManagers(LayerProvidedByContainer);
NormalDefensiveSelection.ReAddToManagers(LayerProvidedByContainer);
HardSelection.ReAddToManagers(LayerProvidedByContainer);
}
public virtual void AddToManagers (Layer layerToAddTo)
{
LayerProvidedByContainer = layerToAddTo;
SpriteManager.AddPositionedObject(this);
EasySelection.AddToManagers(LayerProvidedByContainer);
NormalOffensiveSelection.AddToManagers(LayerProvidedByContainer);
NormalDefensiveSelection.AddToManagers(LayerProvidedByContainer);
HardSelection.AddToManagers(LayerProvidedByContainer);
AddToManagersBottomUp(layerToAddTo);
CustomInitialize();
}
public virtual void Activity()
{
// Generated Activity
EasySelection.Activity();
NormalOffensiveSelection.Activity();
NormalDefensiveSelection.Activity();
HardSelection.Activity();
CustomActivity();
// After Custom Activity
}
public virtual void Destroy()
{
// Generated Destroy
SpriteManager.RemovePositionedObject(this);
if (EasySelection != null)
{
EasySelection.Destroy();
EasySelection.Detach();
}
if (NormalOffensiveSelection != null)
{
NormalOffensiveSelection.Destroy();
NormalOffensiveSelection.Detach();
}
if (NormalDefensiveSelection != null)
{
NormalDefensiveSelection.Destroy();
NormalDefensiveSelection.Detach();
}
if (HardSelection != null)
{
HardSelection.Destroy();
HardSelection.Detach();
}
CustomDestroy();
}
// Generated Methods
public virtual void PostInitialize ()
{
bool oldShapeManagerSuppressAdd = FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = true;
if (EasySelection.Parent == null)
{
EasySelection.CopyAbsoluteToRelative();
EasySelection.AttachTo(this, false);
}
if (EasySelection.Parent == null)
{
EasySelection.Y = 0f;
}
else
{
EasySelection.RelativeY = 0f;
}
EasySelection.Text = "Easy";
EasySelection.FontSize = 9;
EasySelection.Red = 1f;
EasySelection.Green = 1f;
EasySelection.Blue = 1f;
EasySelection.HorizontalAlignment = FlatRedBall.Graphics.HorizontalAlignment.Left;
EasySelection.VerticalAlignment = FlatRedBall.Graphics.VerticalAlignment.Top;
if (NormalOffensiveSelection.Parent == null)
{
NormalOffensiveSelection.CopyAbsoluteToRelative();
NormalOffensiveSelection.AttachTo(this, false);
}
if (NormalOffensiveSelection.Parent == null)
{
NormalOffensiveSelection.Y = -20f;
}
else
{
NormalOffensiveSelection.RelativeY = -20f;
}
NormalOffensiveSelection.Text = "Normal Offensive";
NormalOffensiveSelection.FontSize = 9;
NormalOffensiveSelection.Red = 1f;
NormalOffensiveSelection.Green = 1f;
NormalOffensiveSelection.Blue = 1f;
NormalOffensiveSelection.HorizontalAlignment = FlatRedBall.Graphics.HorizontalAlignment.Left;
NormalOffensiveSelection.VerticalAlignment = FlatRedBall.Graphics.VerticalAlignment.Top;
if (NormalDefensiveSelection.Parent == null)
{
NormalDefensiveSelection.CopyAbsoluteToRelative();
NormalDefensiveSelection.AttachTo(this, false);
}
if (NormalDefensiveSelection.Parent == null)
{
NormalDefensiveSelection.Y = -40f;
}
else
{
NormalDefensiveSelection.RelativeY = -40f;
}
NormalDefensiveSelection.Text = "Normal Defensive";
NormalDefensiveSelection.FontSize = 9;
NormalDefensiveSelection.Red = 1f;
NormalDefensiveSelection.Green = 1f;
NormalDefensiveSelection.Blue = 1f;
NormalDefensiveSelection.HorizontalAlignment = FlatRedBall.Graphics.HorizontalAlignment.Left;
NormalDefensiveSelection.VerticalAlignment = FlatRedBall.Graphics.VerticalAlignment.Top;
if (HardSelection.Parent == null)
{
HardSelection.CopyAbsoluteToRelative();
HardSelection.AttachTo(this, false);
}
if (HardSelection.Parent == null)
{
HardSelection.Y = -60f;
}
else
{
HardSelection.RelativeY = -60f;
}
HardSelection.Text = "Hard";
HardSelection.FontSize = 9;
HardSelection.Red = 1f;
HardSelection.Green = 1f;
HardSelection.Blue = 1f;
HardSelection.HorizontalAlignment = FlatRedBall.Graphics.HorizontalAlignment.Left;
HardSelection.VerticalAlignment = FlatRedBall.Graphics.VerticalAlignment.Top;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = oldShapeManagerSuppressAdd;
}
public virtual void AddToManagersBottomUp (Layer layerToAddTo)
{
AssignCustomVariables(false);
}
public virtual void RemoveFromManagers ()
{
SpriteManager.ConvertToManuallyUpdated(this);
EasySelection.RemoveFromManagers();
NormalOffensiveSelection.RemoveFromManagers();
NormalDefensiveSelection.RemoveFromManagers();
HardSelection.RemoveFromManagers();
}
public virtual void AssignCustomVariables (bool callOnContainedElements)
{
if (callOnContainedElements)
{
EasySelection.AssignCustomVariables(true);
NormalOffensiveSelection.AssignCustomVariables(true);
NormalDefensiveSelection.AssignCustomVariables(true);
HardSelection.AssignCustomVariables(true);
}
if (EasySelection.Parent == null)
{
EasySelection.Y = 0f;
}
else
{
EasySelection.RelativeY = 0f;
}
EasySelection.Text = "Easy";
EasySelection.FontSize = 9;
EasySelection.Red = 1f;
EasySelection.Green = 1f;
EasySelection.Blue = 1f;
EasySelection.HorizontalAlignment = FlatRedBall.Graphics.HorizontalAlignment.Left;
EasySelection.VerticalAlignment = FlatRedBall.Graphics.VerticalAlignment.Top;
if (NormalOffensiveSelection.Parent == null)
{
NormalOffensiveSelection.Y = -20f;
}
else
{
NormalOffensiveSelection.RelativeY = -20f;
}
NormalOffensiveSelection.Text = "Normal Offensive";
NormalOffensiveSelection.FontSize = 9;
NormalOffensiveSelection.Red = 1f;
NormalOffensiveSelection.Green = 1f;
NormalOffensiveSelection.Blue = 1f;
NormalOffensiveSelection.HorizontalAlignment = FlatRedBall.Graphics.HorizontalAlignment.Left;
NormalOffensiveSelection.VerticalAlignment = FlatRedBall.Graphics.VerticalAlignment.Top;
if (NormalDefensiveSelection.Parent == null)
{
NormalDefensiveSelection.Y = -40f;
}
else
{
NormalDefensiveSelection.RelativeY = -40f;
}
NormalDefensiveSelection.Text = "Normal Defensive";
NormalDefensiveSelection.FontSize = 9;
NormalDefensiveSelection.Red = 1f;
NormalDefensiveSelection.Green = 1f;
NormalDefensiveSelection.Blue = 1f;
NormalDefensiveSelection.HorizontalAlignment = FlatRedBall.Graphics.HorizontalAlignment.Left;
NormalDefensiveSelection.VerticalAlignment = FlatRedBall.Graphics.VerticalAlignment.Top;
if (HardSelection.Parent == null)
{
HardSelection.Y = -60f;
}
else
{
HardSelection.RelativeY = -60f;
}
HardSelection.Text = "Hard";
HardSelection.FontSize = 9;
HardSelection.Red = 1f;
HardSelection.Green = 1f;
HardSelection.Blue = 1f;
HardSelection.HorizontalAlignment = FlatRedBall.Graphics.HorizontalAlignment.Left;
HardSelection.VerticalAlignment = FlatRedBall.Graphics.VerticalAlignment.Top;
CurrentState = AiSelector.VariableState.Hard;
}
public virtual void ConvertToManuallyUpdated ()
{
this.ForceUpdateDependenciesDeep();
SpriteManager.ConvertToManuallyUpdated(this);
EasySelection.ConvertToManuallyUpdated();
NormalOffensiveSelection.ConvertToManuallyUpdated();
NormalDefensiveSelection.ConvertToManuallyUpdated();
HardSelection.ConvertToManuallyUpdated();
}
public static void LoadStaticContent (string contentManagerName)
{
if (string.IsNullOrEmpty(contentManagerName))
{
throw new ArgumentException("contentManagerName cannot be empty or null");
}
ContentManagerName = contentManagerName;
#if DEBUG
if (contentManagerName == FlatRedBallServices.GlobalContentManager)
{
HasBeenLoadedWithGlobalContentManager = true;
}
else if (HasBeenLoadedWithGlobalContentManager)
{
throw new Exception("This type has been loaded with a Global content manager, then loaded with a non-global. This can lead to a lot of bugs");
}
#endif
bool registerUnload = false;
if (LoadedContentManagers.Contains(contentManagerName) == false)
{
LoadedContentManagers.Add(contentManagerName);
lock (mLockObject)
{
if (!mRegisteredUnloads.Contains(ContentManagerName) && ContentManagerName != FlatRedBallServices.GlobalContentManager)
{
FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("AiSelectorStaticUnload", UnloadStaticContent);
mRegisteredUnloads.Add(ContentManagerName);
}
}
}
FrbTicTacToe.Entities.Label.LoadStaticContent(contentManagerName);
if (registerUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager)
{
lock (mLockObject)
{
if (!mRegisteredUnloads.Contains(ContentManagerName) && ContentManagerName != FlatRedBallServices.GlobalContentManager)
{
FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("AiSelectorStaticUnload", UnloadStaticContent);
mRegisteredUnloads.Add(ContentManagerName);
}
}
}
CustomLoadStaticContent(contentManagerName);
}
public static void UnloadStaticContent ()
{
if (LoadedContentManagers.Count != 0)
{
LoadedContentManagers.RemoveAt(0);
mRegisteredUnloads.RemoveAt(0);
}
if (LoadedContentManagers.Count == 0)
{
}
}
static VariableState mLoadingState = VariableState.Uninitialized;
public static VariableState LoadingState
{
get
{
return mLoadingState;
}
set
{
mLoadingState = value;
}
}
public FlatRedBall.Instructions.Instruction InterpolateToState (VariableState stateToInterpolateTo, double secondsToTake)
{
switch(stateToInterpolateTo)
{
case VariableState.Easy:
break;
case VariableState.NormalOffensive:
break;
case VariableState.NormalDefensive:
break;
case VariableState.Hard:
break;
}
var instruction = new FlatRedBall.Instructions.DelegateInstruction<VariableState>(StopStateInterpolation, stateToInterpolateTo);
instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + secondsToTake;
this.Instructions.Add(instruction);
return instruction;
}
public void StopStateInterpolation (VariableState stateToStop)
{
switch(stateToStop)
{
case VariableState.Easy:
break;
case VariableState.NormalOffensive:
break;
case VariableState.NormalDefensive:
break;
case VariableState.Hard:
break;
}
CurrentState = stateToStop;
}
public void InterpolateBetween (VariableState firstState, VariableState secondState, float interpolationValue)
{
#if DEBUG
if (float.IsNaN(interpolationValue))
{
throw new Exception("interpolationValue cannot be NaN");
}
#endif
bool setEasySelectionBlue = true;
float EasySelectionBlueFirstValue= 0;
float EasySelectionBlueSecondValue= 0;
bool setHardSelectionBlue = true;
float HardSelectionBlueFirstValue= 0;
float HardSelectionBlueSecondValue= 0;
bool setNormalDefensiveSelectionBlue = true;
float NormalDefensiveSelectionBlueFirstValue= 0;
float NormalDefensiveSelectionBlueSecondValue= 0;
bool setNormalOffensiveSelectionBlue = true;
float NormalOffensiveSelectionBlueFirstValue= 0;
float NormalOffensiveSelectionBlueSecondValue= 0;
switch(firstState)
{
case VariableState.Easy:
EasySelectionBlueFirstValue = 0f;
HardSelectionBlueFirstValue = 1f;
NormalDefensiveSelectionBlueFirstValue = 1f;
NormalOffensiveSelectionBlueFirstValue = 1f;
break;
case VariableState.NormalOffensive:
EasySelectionBlueFirstValue = 1f;
HardSelectionBlueFirstValue = 1f;
NormalDefensiveSelectionBlueFirstValue = 1f;
NormalOffensiveSelectionBlueFirstValue = 0f;
break;
case VariableState.NormalDefensive:
EasySelectionBlueFirstValue = 1f;
HardSelectionBlueFirstValue = 1f;
NormalDefensiveSelectionBlueFirstValue = 0f;
NormalOffensiveSelectionBlueFirstValue = 1f;
break;
case VariableState.Hard:
EasySelectionBlueFirstValue = 1f;
HardSelectionBlueFirstValue = 0f;
NormalDefensiveSelectionBlueFirstValue = 1f;
NormalOffensiveSelectionBlueFirstValue = 1f;
break;
}
switch(secondState)
{
case VariableState.Easy:
EasySelectionBlueSecondValue = 0f;
HardSelectionBlueSecondValue = 1f;
NormalDefensiveSelectionBlueSecondValue = 1f;
NormalOffensiveSelectionBlueSecondValue = 1f;
break;
case VariableState.NormalOffensive:
EasySelectionBlueSecondValue = 1f;
HardSelectionBlueSecondValue = 1f;
NormalDefensiveSelectionBlueSecondValue = 1f;
NormalOffensiveSelectionBlueSecondValue = 0f;
break;
case VariableState.NormalDefensive:
EasySelectionBlueSecondValue = 1f;
HardSelectionBlueSecondValue = 1f;
NormalDefensiveSelectionBlueSecondValue = 0f;
NormalOffensiveSelectionBlueSecondValue = 1f;
break;
case VariableState.Hard:
EasySelectionBlueSecondValue = 1f;
HardSelectionBlueSecondValue = 0f;
NormalDefensiveSelectionBlueSecondValue = 1f;
NormalOffensiveSelectionBlueSecondValue = 1f;
break;
}
if (setEasySelectionBlue)
{
EasySelectionBlue = EasySelectionBlueFirstValue * (1 - interpolationValue) + EasySelectionBlueSecondValue * interpolationValue;
}
if (setHardSelectionBlue)
{
HardSelectionBlue = HardSelectionBlueFirstValue * (1 - interpolationValue) + HardSelectionBlueSecondValue * interpolationValue;
}
if (setNormalDefensiveSelectionBlue)
{
NormalDefensiveSelectionBlue = NormalDefensiveSelectionBlueFirstValue * (1 - interpolationValue) + NormalDefensiveSelectionBlueSecondValue * interpolationValue;
}
if (setNormalOffensiveSelectionBlue)
{
NormalOffensiveSelectionBlue = NormalOffensiveSelectionBlueFirstValue * (1 - interpolationValue) + NormalOffensiveSelectionBlueSecondValue * interpolationValue;
}
if (interpolationValue < 1)
{
mCurrentState = (int)firstState;
}
else
{
mCurrentState = (int)secondState;
}
}
public static void PreloadStateContent (VariableState state, string contentManagerName)
{
ContentManagerName = contentManagerName;
switch(state)
{
case VariableState.Easy:
break;
case VariableState.NormalOffensive:
break;
case VariableState.NormalDefensive:
break;
case VariableState.Hard:
break;
}
}
[System.Obsolete("Use GetFile instead")]
public static object GetStaticMember (string memberName)
{
return null;
}
public static object GetFile (string memberName)
{
return null;
}
object GetMember (string memberName)
{
return null;
}
protected bool mIsPaused;
public override void Pause (FlatRedBall.Instructions.InstructionList instructions)
{
base.Pause(instructions);
mIsPaused = true;
}
public virtual void SetToIgnorePausing ()
{
FlatRedBall.Instructions.InstructionManager.IgnorePausingFor(this);
EasySelection.SetToIgnorePausing();
NormalOffensiveSelection.SetToIgnorePausing();
NormalDefensiveSelection.SetToIgnorePausing();
HardSelection.SetToIgnorePausing();
}
public virtual void MoveToLayer (Layer layerToMoveTo)
{
EasySelection.MoveToLayer(layerToMoveTo);
NormalOffensiveSelection.MoveToLayer(layerToMoveTo);
NormalDefensiveSelection.MoveToLayer(layerToMoveTo);
HardSelection.MoveToLayer(layerToMoveTo);
LayerProvidedByContainer = layerToMoveTo;
}
}
public static class AiSelectorExtensionMethods
{
public static void SetVisible (this PositionedObjectList<AiSelector> list, bool value)
{
int count = list.Count;
for (int i = 0; i < count; i++)
{
list[i].Visible = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Platform.Utilities
{
/// <summary>
/// Provides a pool of reusable (usually resource of memory intensive) objects
/// that can be reused/recycled. The ObjectPool is made up of one or more sets
/// identified by key. Each set contains its own unique pool of reusable objects.
/// Reusable objects are thus identified by a key and their type. Usually only
/// one set (the default set) is required, thus objects can be retrieved by only
/// their type.
/// </summary>
/// <typeparam name="V">The base type for objects stored in the pool</typeparam>
public class RecylingObjectPool<V>
: IEnumerable<V>
{
/// <summary>
/// Used for indexing keys that are null in the pool dictionary.
/// </summary>
private class NullKey
{
public static readonly Type Default = typeof(NullKey);
}
/// <summary>
/// A dictionary that holds all the sets int he pool.
/// </summary>
private readonly IDictionary<object, IDictionary<Type, Queue<V>>> pool;
/// <summary>
/// The object used to synchronize this object pool.
/// </summary>
public virtual object SyncLock => this;
/// <summary>
/// The <see cref="ObjectActivator"/> used by the pool to create new
/// objects if an object is not available and no alternative <see cref="ObjectActivator"/>
/// is provided by in the <c>GetObject</c> call.
/// </summary>
public virtual ObjectActivator<V> ObjectActivator
{
get;
private set;
}
public RecylingObjectPool()
: this(DefaultObjectActivator)
{
}
public RecylingObjectPool(ObjectActivator<V> objectActivator)
{
this.ObjectActivator = objectActivator;
pool = new Dictionary<object, IDictionary<Type, Queue<V>>>();
}
public virtual IEnumerator<V> GetEnumerator()
{
foreach (var dictionary in pool.Values)
{
foreach (var queue in dictionary.Values)
{
foreach (var obj in queue)
{
yield return obj;
}
}
}
}
/// <summary>
/// Clears the pool of objects.
/// </summary>
public virtual void Clear()
{
pool.Clear();
}
/// <summary>
/// Gets an enumerator for all the objects in the pool.
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => this.GetEnumerator();
/// <summary>
/// An <see cref="ObjectActivator"/> that returns null or the default value for the type
/// </summary>
/// <param name="type"></param>
/// <returns>A newly created object</returns>
public static V NullObjectActivator(Type type)
{
if (!typeof(V).IsAssignableFrom(type))
{
throw new ArgumentException($"Type {type.Name} does not inherit from {typeof(V).Name}");
}
if (typeof(V).IsValueType)
{
return typeof(V) == type ? default(V) : (V)Activator.CreateInstance(type);
}
return default(V);
}
/// <summary>
/// A <see cref="ObjectActivator"/> that creates an object of type <see cref="type"/>
/// by using its default constructor.
/// </summary>
/// <param name="type">The type of object to create</param>
/// <returns>A newly created object</returns>
public static V DefaultObjectActivator(Type type)
{
if (!typeof(V).IsAssignableFrom(type))
{
throw new ArgumentException($"Type {type.Name} does not inherit from {typeof(V).Name}");
}
return (V)Activator.CreateInstance(type);
}
/// <summary>
/// Puts an object back into the pool to be available for reuse.
/// </summary>
/// <param name="key">
/// The key for the set in the pool to place the object into
/// (can be null or default(V) for the default pool)/
/// </param>
/// <param name="value">The object to place back into the pool for reuse</param>
public virtual void Recycle(object key, V value)
{
Queue<V> queue;
IDictionary<Type, Queue<V>> dictionary;
if (key == null)
{
key = NullKey.Default;
}
if (!pool.TryGetValue(key, out dictionary))
{
dictionary = new Dictionary<Type, Queue<V>>();
pool[key] = dictionary;
}
if (!dictionary.TryGetValue(value.GetType(), out queue))
{
queue = new Queue<V>();
dictionary[value.GetType()] = queue;
}
queue.Enqueue(value);
}
/// <summary>
/// Puts an object back into the pool to be available for reuse. The object
/// will be placed back into the default set (null key).
/// </summary>
/// <param name="value">The object to place back into the pool for reuse</param>
public virtual void Recycle(V value)
{
Recycle(null, value);
}
/// <summary>
/// Gets an object from the pool. Creates a new object if none is available
/// in the pool.
/// </summary>
/// <typeparam name="T">The type of object to get or create</typeparam>
/// <param name="key">The key for the set in the pool to use (null to use the default set)</param>
/// <param name="objectActivator">
/// An <see cref="ObjectActivator"/> that will be used to create the object if none already exist in the pool
/// </param>
/// <returns>An object (either from the pool or newly created)</returns>
public virtual T GetObject<T>(object key, ObjectActivator<V> objectActivator)
where T : V
{
return (T)GetObject(key, typeof(T), objectActivator);
}
/// <summary>
/// Gets an object from the pool. Creates a new object if none is available
/// in the pool.
/// </summary>
/// <param name="key">The key for the set in the pool to use (null to use the default set)</param>
/// <param name="type">The type of object to create</param>
/// <param name="objectActivator">
/// An <see cref="ObjectActivator"/> that will be used to create the object if none already exist in the pool
/// </param>
/// <returns>An object (either from the pool or newly created)</returns>
public virtual object GetObject(object key, Type type, ObjectActivator<V> objectActivator)
{
Queue<V> queue;
IDictionary<Type, Queue<V>> dictionary;
if (key == null)
{
key = NullKey.Default;
}
if (!pool.TryGetValue(key, out dictionary))
{
return objectActivator(type);
}
if (!(dictionary.TryGetValue(type, out queue) && queue.Count > 0))
{
return objectActivator(type);
}
return queue.Dequeue();
}
/// <summary>
/// Gets an object from the pool's default set. Creates a new object if none is available
/// in the pool.
/// </summary>
/// <typeparam name="T">The type of object to get or create</typeparam>
/// <param name="objectActivator">
/// An <see cref="ObjectActivator"/> that will be used to create the object if none already exist in the pool
/// </param>
/// <returns>An object (either from the pool or newly created)</returns>
public virtual T GetObject<T>(ObjectActivator<V> objectActivator) => (T)this.GetObject(typeof(T), objectActivator);
/// <summary>
/// Gets an object from the pool's default set.
/// Creates a new object if none is available in the pool.
/// </summary>
/// <param name="type">The type of object to create</param>
/// <param name="objectActivator">
/// An <see cref="ObjectActivator"/> that will be used to create the object if none already exist in the pool
/// </param>
/// <returns>An object (either from the pool or newly created)</returns>
public virtual object GetObject(Type type, ObjectActivator<V> objectActivator) => this.GetObject(null, type, objectActivator);
/// <summary>
/// Gets an object from the pool's default set. Uses the pool's default
/// <see cref="ObjectActivator"/> to create a new object if none is available in the pool.
/// </summary>
/// <typeparam name="T">The type of object to create</typeparam>
/// <returns>An object(either from the pool or newly created)</returns>
public virtual T GetObject<T>() => (T)this.GetObject(typeof(T));
/// <summary>
/// Gets an object from the pool's default set. Uses the pool's default
/// <see cref="ObjectActivator"/> to create a new object if none is available in the pool.
/// </summary>
/// <param name="type">The type of object to create</param>
/// <returns>An object(either from the pool or newly created)</returns>
public virtual object GetObject(Type type) => this.GetObject(type, this.ObjectActivator);
}
}
| |
using System.Linq;
using Raging.Data.ReverseEngineering.Infrastructure.Metadata;
using Raging.Data.ReverseEngineering.Infrastructure.Pluralization;
using Raging.Data.Schema;
using Raging.Toolbox.Extensions;
namespace Raging.Data.ReverseEngineering.EntityFramework.Adapters
{
public class NavigationPropertyInfoAdapter : INavigationPropertyInfoAdapter
{
private readonly ISchemaForeignKey foreignKey;
private readonly IIdentifierGenerationService identifierGenerationService;
private readonly ISchemaTable table;
#region . Ctors .
public NavigationPropertyInfoAdapter(ISchemaForeignKey foreignKey, ISchemaTable table, IIdentifierGenerationService identifierGenerationService)
{
this.foreignKey = foreignKey;
this.table = table;
this.identifierGenerationService = identifierGenerationService;
}
#endregion
#region . INavigationPropertyInfoAdapter .
private const string MappingTextTemplate = "this.{0}(a => a.{1})\r\n\t.WithMany(b => b.{2})\r\n\t.HasForeignKey(c => c.{3}); // {4}";
private const string PropertyTextOneToManyTemplate = "public virtual ICollection<{0}> {1} {{ get; set; }} // {2}.{3}";
private const string PropertyTextOneToOneTemplate = "public virtual {0} {1} {{ get; set; }} // {2}";
public string GetMapppingText()
{
string text = null;
// 1:n
if(this.table.FullName == this.foreignKey.ForeignKeyTableFullName)
{
if(this.foreignKey.PrimaryKeyColumn == this.foreignKey.ForeignKeyColumn)
{
text = MappingTextTemplate
.FormatWith(
table.Columns.Single(column => column.Name == this.foreignKey.ForeignKeyColumn).IsNullable
? "HasOptional"
: "HasRequired",
this.foreignKey.PrimaryKeyTableName,
this.identifierGenerationService.Generate(
this.foreignKey.ForeignKeyTableName,
NounForms.Plural,
"{0}.{1}".FormatWith(this.foreignKey.ForeignKeyTableFullName, this.foreignKey.ForeignKeyTableName)),
this.foreignKey.ForeignKeyColumn,
this.foreignKey.ConstraintName);
}
else
{
var propertyName = this.foreignKey.ForeignKeyColumn.ToLowerInvariant().EndsWith("id")
? this.foreignKey.ForeignKeyColumn.Substring(0, this.foreignKey.ForeignKeyColumn.Length - 2)
: this.foreignKey.ForeignKeyColumn;
text = MappingTextTemplate
.FormatWith(
table.Columns.Single(column => column.Name == this.foreignKey.ForeignKeyColumn).IsNullable
? "HasOptional"
: "HasRequired",
propertyName,
this.identifierGenerationService.Generate(propertyName, NounForms.Plural, "{0}.{1}".FormatWith(this.foreignKey.ForeignKeyTableFullName, propertyName)),
this.foreignKey.ForeignKeyColumn,
this.foreignKey.ConstraintName);
}
}
return text;
}
public string GetConstructorInitializationText()
{
string template = "this.{0} = new List<{1}>();";
//one to many
if(this.table.FullName == this.foreignKey.PrimaryKeyTableFullName)
{
if(this.foreignKey.PrimaryKeyColumn == this.foreignKey.ForeignKeyColumn)
{
return template.FormatWith(
this.identifierGenerationService.Generate(
this.foreignKey.ForeignKeyTableName,
NounForms.Plural,
"{0}.{1}".FormatWith(this.foreignKey.ForeignKeyTableFullName, this.foreignKey.ForeignKeyTableName)),
this.foreignKey.ForeignKeyTableName);
}
else
{
var propertyName = this.foreignKey.ForeignKeyColumn.ToLowerInvariant().EndsWith("id")
? this.foreignKey.ForeignKeyColumn.Substring(0, this.foreignKey.ForeignKeyColumn.Length - 2)
: this.foreignKey.ForeignKeyColumn;
return template.FormatWith(
this.identifierGenerationService.Generate(
propertyName,
NounForms.Plural,
"{0}.{1}".FormatWith(this.foreignKey.ForeignKeyTableFullName, propertyName)),
this.foreignKey.ForeignKeyTableName);
}
}
// this.Models = new List<Singular>();
//throw new NotImplementedException();
////one to many
//if (foreignKey.PrimaryKeySchema == table.Schema && foreignKey.PrimaryKeyTableName == table.Name)
//{
// return "public virtual ICollection<{0}> {1} {{ get; set; }} //{2}"
// .FormatWith(
// identifierGenerationService.Transform(foreignKey.ForeignKeyTableName, NounForms.Singular),
// identifierGenerationService.Transform(foreignKey.ForeignKeyTableName, NounForms.Plural),
// foreignKey.ConstraintName
// );
//}
////one to many
//return "public virtual ICollection<{0}> {1} {{ get; set; }} //{2}"
// .FormatWith(
// foreignKey.ForeignKeyTableName,
// foreignKey.ForeignKeyTableName,
// foreignKey.ConstraintName
// );
return string.Empty;
}
public string GetPropertyText()
{
string text = null;
var propertyName = this.foreignKey.ForeignKeyColumn.ToLowerInvariant().EndsWith("id")
? this.foreignKey.ForeignKeyColumn.Substring(0, this.foreignKey.ForeignKeyColumn.Length - 2)
: this.foreignKey.ForeignKeyColumn;
//one to many
if(this.table.FullName == this.foreignKey.PrimaryKeyTableFullName)
{
if(this.foreignKey.PrimaryKeyColumn == this.foreignKey.ForeignKeyColumn)
{
text = PropertyTextOneToManyTemplate
.FormatWith(
this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Singular, "{0}.{1}".FormatWith(this.foreignKey.ForeignKeyTableFullName, this.foreignKey.ForeignKeyTableName)),
this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Plural, "{0}.{1}".FormatWith(this.foreignKey.ForeignKeyTableFullName, this.foreignKey.ForeignKeyTableName)),
this.foreignKey.ForeignKeyTableName,
this.foreignKey.ConstraintName);
}
else
{
text = PropertyTextOneToManyTemplate
.FormatWith(
this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Singular, "{0}.{1}".FormatWith(this.foreignKey.ForeignKeyTableFullName, this.foreignKey.ForeignKeyTableName)),
this.identifierGenerationService.Generate(propertyName, NounForms.Plural, "{0}.{1}".FormatWith(this.foreignKey.ForeignKeyTableFullName, propertyName)),
this.foreignKey.ForeignKeyTableName,
this.foreignKey.ConstraintName);
}
}
//one to one
if(this.table.FullName == this.foreignKey.ForeignKeyTableFullName)
{
if(text.IsNotBlank()) text += "\r\n";
text += PropertyTextOneToOneTemplate
.FormatWith(
//this.identifierGenerationService.Generate(this.foreignKey.PrimaryKeyTableName, NounForms.Singular),
this.identifierGenerationService.Generate(this.foreignKey.PrimaryKeyTableName, NounForms.Singular, "{0}.{1}".FormatWith(this.foreignKey.PrimaryKeyTableFullName, this.foreignKey.PrimaryKeyTableName)),
this.identifierGenerationService.Generate(propertyName, NounForms.Singular, "{0}.{1}".FormatWith(this.foreignKey.ForeignKeyTableFullName, propertyName)),
this.foreignKey.ConstraintName);
}
return text;
}
#endregion
}
}
//public string GetPropertyText()
// {
// string text = null;
// //one to many
// if (this.table.FullName == this.foreignKey.PrimaryKeyTableFullName)
// {
// //var text = PropertyTextTemplate
// // .FormatWith(
// // this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Singular),
// // this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Plural),
// // this.foreignKey.ForeignKeyTableName,
// // this.foreignKey.ConstraintName);
// //return text;
// //// public virtual ICollection<RelatedSaga> SecondarySagas { get; set; } // RelatedSaga.FK_RelatedSaga_SecondarySaga
// //if (this.foreignKey.PrimaryKeyTableFullName != this.foreignKey.ForeignKeyTableFullName)
// //{
// var propertyName = this.foreignKey.ForeignKeyColumn.ToLowerInvariant().EndsWith("id")
// ? this.foreignKey.ForeignKeyColumn.Substring(0, this.foreignKey.ForeignKeyColumn.Length - 2)
// : this.foreignKey.ForeignKeyColumn;
// text = "public virtual ICollection<{0}> {1} {{ get; set; }} // {2}.{3}"
// .FormatWith(
// this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Singular),
// this.identifierGenerationService.Generate(propertyName, NounForms.Plural),
// this.foreignKey.ForeignKeyTableName,
// this.foreignKey.ConstraintName);
// //}
// //// public virtual ICollection<Person> People { get; set; } // Person.FK_Person_Father
// //// public virtual ICollection<SagaMessage> SagaMessages { get; set; } // SagaMessage.FK_SagaMessage_Saga
// //else
// //{
// // var text = PropertyTextTemplate
// // .FormatWith(
// // this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Singular),
// // this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Plural),
// // this.foreignKey.ForeignKeyTableName,
// // this.foreignKey.ConstraintName);
// // return text;
// //}
// //if (this.foreignKey.PrimaryKeyTableFullName != this.foreignKey.ForeignKeyTableFullName)
// //{
// // var propertyName = this.foreignKey.ForeignKeyColumn.ToLowerInvariant().EndsWith("id")
// // ? this.foreignKey.ForeignKeyColumn.Substring(0, this.foreignKey.ForeignKeyColumn.Length - 2)
// // : this.foreignKey.ForeignKeyColumn;
// // var text = "public virtual ICollection<{0}> {1} {{ get; set; }} // {2}.{3}"
// // .FormatWith(
// // this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Singular),
// // this.identifierGenerationService.Generate(propertyName, NounForms.Plural),
// // this.foreignKey.ForeignKeyTableName,
// // this.foreignKey.ConstraintName);
// // return text;
// //}
// //else
// //{
// // var text = "public virtual ICollection<{0}> {1} {{ get; set; }} // {2}.{3}"
// // .FormatWith(
// // this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Singular),
// // this.identifierGenerationService.Generate(this.foreignKey.ForeignKeyTableName, NounForms.Plural),
// // this.foreignKey.ForeignKeyTableName,
// // this.foreignKey.ConstraintName);
// // return text;
// //}
// }
// //one to one
// if (this.table.FullName == this.foreignKey.ForeignKeyTableFullName)
// {
// // public virtual Saga PrimarySaga { get; set; } // FK_RelatedSaga_PrimarySaga
// // public virtual Saga Saga { get; set; } // FK_SagaMessage_Saga
// var propertyName = this.foreignKey.ForeignKeyColumn.ToLowerInvariant().EndsWith("id")
// ? this.foreignKey.ForeignKeyColumn.Substring(0, this.foreignKey.ForeignKeyColumn.Length - 2)
// : this.foreignKey.ForeignKeyColumn;
// text += "\r\npublic virtual {0} {1} {{ get; set; }} // {2}"
// .FormatWith(
// this.identifierGenerationService.Generate(this.foreignKey.PrimaryKeyTableName, NounForms.Singular),
// this.identifierGenerationService.Generate(propertyName, NounForms.Singular),
// this.foreignKey.ConstraintName);
// }
// return text;
// }
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Runtime.InteropServices;
using Avalonia.Cairo.Media.Imaging;
using Avalonia.Media;
namespace Avalonia.Cairo.Media
{
using Avalonia.Media.Imaging;
using Cairo = global::Cairo;
/// <summary>
/// Draws using Cairo.
/// </summary>
public class DrawingContext : IDrawingContextImpl, IDisposable
{
/// <summary>
/// The cairo context.
/// </summary>
private readonly Cairo.Context _context;
private readonly Stack<BrushImpl> _maskStack = new Stack<BrushImpl>();
/// <summary>
/// Initializes a new instance of the <see cref="DrawingContext"/> class.
/// </summary>
/// <param name="surface">The target surface.</param>
public DrawingContext(Cairo.Surface surface)
{
_context = new Cairo.Context(surface);
}
/// <summary>
/// Initializes a new instance of the <see cref="DrawingContext"/> class.
/// </summary>
/// <param name="surface">The GDK drawable.</param>
public DrawingContext(Gdk.Drawable drawable)
{
_context = Gdk.CairoHelper.Create(drawable);
}
private Matrix _transform = Matrix.Identity;
/// <summary>
/// Gets the current transform of the drawing context.
/// </summary>
public Matrix Transform
{
get { return _transform; }
set
{
_transform = value;
_context.Matrix = value.ToCairo();
}
}
/// <summary>
/// Ends a draw operation.
/// </summary>
public void Dispose()
{
_context.Dispose();
}
/// <summary>
/// Draws a bitmap image.
/// </summary>
/// <param name="source">The bitmap image.</param>
/// <param name="opacity">The opacity to draw with.</param>
/// <param name="sourceRect">The rect in the image to draw.</param>
/// <param name="destRect">The rect in the output to draw to.</param>
public void DrawImage(IBitmap bitmap, double opacity, Rect sourceRect, Rect destRect)
{
var impl = bitmap.PlatformImpl as BitmapImpl;
var size = new Size(impl.PixelWidth, impl.PixelHeight);
var scale = new Vector(destRect.Width / sourceRect.Width, destRect.Height / sourceRect.Height);
_context.Save();
_context.Scale(scale.X, scale.Y);
destRect /= scale;
if (opacityOverride < 1.0f) {
_context.PushGroup ();
Gdk.CairoHelper.SetSourcePixbuf (
_context,
impl,
-sourceRect.X + destRect.X,
-sourceRect.Y + destRect.Y);
_context.Rectangle (destRect.ToCairo ());
_context.Fill ();
_context.PopGroupToSource ();
_context.PaintWithAlpha (opacityOverride);
} else {
_context.PushGroup ();
Gdk.CairoHelper.SetSourcePixbuf (
_context,
impl,
-sourceRect.X + destRect.X,
-sourceRect.Y + destRect.Y);
_context.Rectangle (destRect.ToCairo ());
_context.Fill ();
_context.PopGroupToSource ();
_context.PaintWithAlpha (opacityOverride);
}
_context.Restore();
}
/// <summary>
/// Draws a line.
/// </summary>
/// <param name="pen">The stroke pen.</param>
/// <param name="p1">The first point of the line.</param>
/// <param name="p1">The second point of the line.</param>
public void DrawLine(Pen pen, Point p1, Point p2)
{
var size = new Rect(p1, p2).Size;
using (var p = SetPen(pen, size))
{
_context.MoveTo(p1.ToCairo());
_context.LineTo(p2.ToCairo());
_context.Stroke();
}
}
/// <summary>
/// Draws a geometry.
/// </summary>
/// <param name="brush">The fill brush.</param>
/// <param name="pen">The stroke pen.</param>
/// <param name="geometry">The geometry.</param>
public void DrawGeometry(IBrush brush, Pen pen, Geometry geometry)
{
var impl = geometry.PlatformImpl as StreamGeometryImpl;
var oldMatrix = Transform;
Transform = impl.Transform * Transform;
if (brush != null)
{
_context.AppendPath(impl.Path);
using (var b = SetBrush(brush, geometry.Bounds.Size))
{
_context.FillRule = impl.FillRule == FillRule.EvenOdd
? Cairo.FillRule.EvenOdd
: Cairo.FillRule.Winding;
if (pen != null)
_context.FillPreserve();
else
_context.Fill();
}
}
Transform = oldMatrix;
if (pen != null)
{
_context.AppendPath(impl.Path);
using (var p = SetPen(pen, geometry.Bounds.Size))
{
_context.Stroke();
}
}
}
/// <summary>
/// Draws the outline of a rectangle.
/// </summary>
/// <param name="pen">The pen.</param>
/// <param name="rect">The rectangle bounds.</param>
public void DrawRectangle(Pen pen, Rect rect, float cornerRadius)
{
using (var p = SetPen(pen, rect.Size))
{
_context.Rectangle(rect.ToCairo ());
_context.Stroke();
}
}
/// <summary>
/// Draws text.
/// </summary>
/// <param name="foreground">The foreground brush.</param>
/// <param name="origin">The upper-left corner of the text.</param>
/// <param name="text">The text.</param>
public void DrawText(IBrush foreground, Point origin, FormattedText text)
{
var layout = ((FormattedTextImpl)text.PlatformImpl).Layout;
_context.MoveTo(origin.X, origin.Y);
using (var b = SetBrush(foreground, new Size(0, 0)))
{
Pango.CairoHelper.ShowLayout(_context, layout);
}
}
/// <summary>
/// Draws a filled rectangle.
/// </summary>
/// <param name="brush">The brush.</param>
/// <param name="rect">The rectangle bounds.</param>
public void FillRectangle(IBrush brush, Rect rect, float cornerRadius)
{
using (var b = SetBrush(brush, rect.Size))
{
_context.Rectangle(rect.ToCairo ());
_context.Fill();
}
}
/// <summary>
/// Pushes a clip rectange.
/// </summary>
/// <param name="clip">The clip rectangle.</param>
/// <returns>A disposable used to undo the clip rectangle.</returns>
public void PushClip(Rect clip)
{
_context.Save();
_context.Rectangle(clip.ToCairo());
_context.Clip();
}
public void PopClip()
{
_context.Restore();
}
readonly Stack<double> _opacityStack = new Stack<double>();
/// <summary>
/// Pushes an opacity value.
/// </summary>
/// <param name="opacity">The opacity.</param>
/// <returns>A disposable used to undo the opacity.</returns>
public void PushOpacity(double opacity)
{
_opacityStack.Push(opacityOverride);
if (opacity < 1.0f)
opacityOverride *= opacity;
}
public void PopOpacity()
{
opacityOverride = _opacityStack.Pop();
}
/// <summary>
/// Pushes a matrix transformation.
/// </summary>
/// <param name="matrix">The matrix</param>
/// <returns>A disposable used to undo the transformation.</returns>
public IDisposable PushTransform(Matrix matrix)
{
_context.Save();
_context.Transform(matrix.ToCairo());
return Disposable.Create(() =>
{
_context.Restore();
});
}
private double opacityOverride = 1.0f;
private IDisposable SetBrush(IBrush brush, Size destinationSize)
{
_context.Save();
BrushImpl impl = CreateBrushImpl(brush, destinationSize);
_context.SetSource(impl.PlatformBrush);
return Disposable.Create(() =>
{
impl.Dispose();
_context.Restore();
});
}
private BrushImpl CreateBrushImpl(IBrush brush, Size destinationSize)
{
var solid = brush as SolidColorBrush;
var linearGradientBrush = brush as LinearGradientBrush;
var radialGradientBrush = brush as RadialGradientBrush;
var imageBrush = brush as ImageBrush;
var visualBrush = brush as VisualBrush;
BrushImpl impl = null;
if (solid != null)
{
impl = new SolidColorBrushImpl(solid, opacityOverride);
}
else if (linearGradientBrush != null)
{
impl = new LinearGradientBrushImpl(linearGradientBrush, destinationSize);
}
else if (radialGradientBrush != null)
{
impl = new RadialGradientBrushImpl(radialGradientBrush, destinationSize);
}
else if (imageBrush != null)
{
impl = new ImageBrushImpl(imageBrush, destinationSize);
}
else if (visualBrush != null)
{
impl = new VisualBrushImpl(visualBrush, destinationSize);
}
else
{
impl = new SolidColorBrushImpl(null, opacityOverride);
}
return impl;
}
private IDisposable SetPen(Pen pen, Size destinationSize)
{
if (pen.DashStyle != null)
{
if (pen.DashStyle.Dashes != null && pen.DashStyle.Dashes.Count > 0)
{
var cray = pen.DashStyle.Dashes.ToArray();
_context.SetDash(cray, pen.DashStyle.Offset);
}
}
_context.LineWidth = pen.Thickness;
_context.MiterLimit = pen.MiterLimit;
// Line caps and joins are currently broken on Cairo. I've defaulted them to sensible defaults for now.
// Cairo does not have StartLineCap, EndLineCap, and DashCap properties, whereas Direct2D does.
// TODO: Figure out a solution for this.
_context.LineJoin = Cairo.LineJoin.Miter;
_context.LineCap = Cairo.LineCap.Butt;
if (pen.Brush == null)
return Disposable.Empty;
return SetBrush(pen.Brush, destinationSize);
}
public void PushGeometryClip(Geometry clip)
{
_context.Save();
_context.AppendPath(((StreamGeometryImpl)clip.PlatformImpl).Path);
_context.Clip();
}
public void PopGeometryClip()
{
_context.Restore();
}
public void PushOpacityMask(IBrush mask, Rect bounds)
{
_context.PushGroup();
var impl = CreateBrushImpl(mask, bounds.Size);
_maskStack.Push(impl);
}
public void PopOpacityMask()
{
_context.PopGroupToSource();
_context.Mask(_maskStack.Pop().PlatformBrush);
}
}
}
| |
using System;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Data;
using System.Drawing;
using System.Data.OleDb;
using System.Reflection;
using C1.Win.C1Preview;
using PCSComUtils.Common;
using PCSUtils.Utils;
namespace StockTakingReport
{
[Serializable]
public class StockTakingReport : MarshalByRefObject, IDynamicReport
{
public StockTakingReport()
{
}
#region Constants
private const string TABLE_NAME = "tbl_OutsideProcessing";
private const int DATA_MAX_LENGTH = 250;
private const string NAME_FLD = "Name";
private const string EXCHANGE_RATE_FLD = "ExchangeRate";
private const string PRODUCT_ID_FLD = "ProductID";
private const string PRODUCT_CODE_FLD = "Code";
private const string PRODUCT_NAME_FLD = "Description";
#endregion
#region IDynamicReport Members
private bool mUseReportViewerRenderEngine = false;
private string mConnectionString;
private ReportBuilder mReportBuilder;
private C1PrintPreviewControl mReportViewer;
private object mResult;
/// <summary>
/// ConnectionString, provide for the Dynamic Report
/// ALlow Dynamic Report to access the DataBase of PCS
/// </summary>
public string PCSConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
/// <summary>
/// Report Builder Utility Object
/// Dynamic Report can use this object to render, modify, layout the report
/// </summary>
public ReportBuilder PCSReportBuilder
{
get { return mReportBuilder; }
set { mReportBuilder = value; }
}
/// <summary>
/// ReportViewer Object, provide for the DynamicReport,
/// allow Dynamic Report to manipulate with the REportViewer,
/// modify the report after rendered if needed
/// </summary>
public C1PrintPreviewControl PCSReportViewer
{
get { return mReportViewer; }
set { mReportViewer = value; }
}
/// <summary>
/// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid
/// </summary>
public object Result
{
get { return mResult; }
set { mResult = value; }
}
/// <summary>
/// Notify PCS whether the rendering report process is run by
/// this IDynamicReport or the ReportViewer Engine (in the ReportViewer form)
/// </summary>
public bool UseReportViewerRenderEngine
{
get { return mUseReportViewerRenderEngine; }
set { mUseReportViewerRenderEngine = value; }
}
private string mstrReportDefinitionFolder = string.Empty;
/// <summary>
/// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path )
/// </summary>
public string ReportDefinitionFolder
{
get { return mstrReportDefinitionFolder; }
set { mstrReportDefinitionFolder = value; }
}
private string mstrReportLayoutFile = string.Empty;
/// <summary>
/// Inform External Process about the Layout file
/// in which PCS instruct to use
/// (PCS will assign this property while ReportViewer Form execute,
/// ReportVIewer form will use the layout file in the report config entry to put in this property)
/// </summary>
public string ReportLayoutFile
{
get
{
return mstrReportLayoutFile;
}
set
{
mstrReportLayoutFile = value;
}
}
#endregion
#region Detailed Item Price By PO Receipt Datat: Tuan TQ
DataTable GetStockTakingData(string pstrCCNID,
string pstrStockTakingPeriodID,
string pstrDepartmentIDs,
string pstrProductionLineIDs,
string pstrLocationIDs,
string pstrBinIDs
)
{
DataTable dtbResult = new DataTable();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
StringBuilder strSqlBuilder = new StringBuilder();
strSqlBuilder.Append(" SELECT IV_StockTaking.StockTakingID, IV_StockTaking.Quantity,IV_StockTaking.BookQuantity, IV_StockTaking.SlipCode, IV_StockTaking.Note, ");
strSqlBuilder.Append(" IV_StockTaking.StockTakingPeriodID, IV_StockTaking.DepartmentID, IV_StockTaking.ProductionLineID, ");
strSqlBuilder.Append(" IV_StockTaking.LocationID, IV_StockTaking.BinID, IV_StockTaking.ProductID, IV_StockTaking.StockUMID, ");
strSqlBuilder.Append(" IV_StockTaking.CountingMethodID, ");
strSqlBuilder.Append(" MST_Department.Code Department_Code, ");
strSqlBuilder.Append(" PRO_ProductionLine.Code ProductionLine_Code, ");
strSqlBuilder.Append(" MST_Location.Code Location_Code, ");
strSqlBuilder.Append(" MST_Bin.Code Bin_Code, ");
strSqlBuilder.Append(" ITM_Category.Code Category_Code, ");
strSqlBuilder.Append(" ITM_Product.Code PartNumber, ITM_Product.Description PartName, ITM_Product.Revision PartModel, ITM_Product.SourceID, ");
strSqlBuilder.Append(" MST_UnitOfMeasure.Code UMCode, ");
strSqlBuilder.Append(" ITM_Source.Code Source_Code, ");
strSqlBuilder.Append(" ActualCost.ActualCost UnitPrice, ");
strSqlBuilder.Append(" ActualCost.ActualCost*IV_StockTaking.Quantity ActualAmount, ");
strSqlBuilder.Append(" ActualCost.ActualCost*IV_StockTaking.BookQuantity BookAmount, ");
strSqlBuilder.Append(" IV_StockTaking.Quantity -IV_StockTaking.BookQuantity DiffQuantity, ");
strSqlBuilder.Append(" (ActualCost.ActualCost*IV_StockTaking.Quantity - ");
strSqlBuilder.Append(" ActualCost.ActualCost *IV_StockTaking.BookQuantity ) DiffAmount");/*ActualAmount-BookAmount*/
strSqlBuilder.Append(" FROM IV_StockTaking ");
strSqlBuilder.Append(" INNER JOIN IV_StockTakingPeriod ON IV_StockTaking.StockTakingPeriodID = IV_StockTakingPeriod.StockTakingPeriodID ");
strSqlBuilder.Append(" INNER JOIN ITM_Product ON IV_StockTaking.ProductID = ITM_Product.ProductID ");
strSqlBuilder.Append(" LEFT JOIN ITM_Category ON ITM_Product.CategoryID = ITM_Category.CategoryID ");
strSqlBuilder.Append(" LEFT JOIN ITM_Source ON ITM_Product.SourceID = ITM_Source.SourceID ");
strSqlBuilder.Append(" LEFT JOIN MST_UnitOfMeasure ON IV_StockTaking.StockUMID = MST_UnitOfMeasure.UnitOfMeasureID ");
strSqlBuilder.Append(" LEFT JOIN MST_Department ON IV_StockTaking.DepartmentID = MST_Department.DepartmentID ");
strSqlBuilder.Append(" LEFT JOIN PRO_ProductionLine ON IV_StockTaking.ProductionLineID = PRO_ProductionLine.ProductionLineID ");
strSqlBuilder.Append(" LEFT JOIN MST_Location ON IV_StockTaking.LocationID = MST_Location.LocationID ");
strSqlBuilder.Append(" LEFT JOIN MST_Bin ON IV_StockTaking.BinID = MST_Bin.BinID ");
strSqlBuilder.Append(" LEFT JOIN ( ");
strSqlBuilder.Append(" SELECT CST_ActualCostHistory.ProductID,SUM(CST_ActualCostHistory.ActualCost) ActualCost ");
strSqlBuilder.Append(" FROM CST_ActualCostHistory ");
strSqlBuilder.Append(" INNER JOIN cst_ActCostAllocationMaster ON CST_ActualCostHistory.ActCostAllocationMasterID=cst_ActCostAllocationMaster.ActCostAllocationMasterID ");
strSqlBuilder.Append(" AND ((SELECT StockTakingDate FROM IV_StockTakingPeriod WHERE StockTakingPeriodID="+pstrStockTakingPeriodID+") >= cst_ActCostAllocationMaster.FromDate) ");
strSqlBuilder.Append(" AND ((SELECT StockTakingDate FROM IV_StockTakingPeriod WHERE StockTakingPeriodID="+pstrStockTakingPeriodID+") < cst_ActCostAllocationMaster.ToDate) ");
strSqlBuilder.Append(" GROUP BY CST_ActualCostHistory.ProductID ");
strSqlBuilder.Append(" ) ActualCost ON IV_StockTaking.ProductID = ActualCost.ProductID ");
strSqlBuilder.Append(" WHERE IV_StockTakingPeriod.CCNID = "+pstrCCNID+" AND IV_StockTaking.StockTakingPeriodID = "+pstrStockTakingPeriodID+" ");
if(pstrDepartmentIDs != string.Empty && pstrDepartmentIDs != null)
{
strSqlBuilder.Append(" AND IV_StockTaking.DepartmentID IN ("+pstrDepartmentIDs+") ");
}
if(pstrProductionLineIDs != string.Empty && pstrProductionLineIDs != null)
{
strSqlBuilder.Append(" AND IV_StockTaking.ProductionLineID IN ("+pstrProductionLineIDs+") ");
}
if(pstrLocationIDs != string.Empty && pstrLocationIDs != null)
{
strSqlBuilder.Append(" AND IV_StockTaking.LocationID IN ("+pstrLocationIDs+") ");
}
if(pstrBinIDs != string.Empty && pstrBinIDs != null)
{
strSqlBuilder.Append(" AND IV_StockTaking.BinID IN (" + pstrBinIDs + ") ");
}
strSqlBuilder.Append(" ORDER BY MST_Department.Code, ");
strSqlBuilder.Append(" PRO_ProductionLine.Code, ");
strSqlBuilder.Append(" MST_Location.Code, ");
strSqlBuilder.Append(" MST_Bin.Code, ");
strSqlBuilder.Append(" ITM_Category.Code, ");
strSqlBuilder.Append(" ITM_Product.Code, ");
strSqlBuilder.Append(" ITM_Product.Description ");
//Write SQL string for debugging
Console.WriteLine(strSqlBuilder.ToString());
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSqlBuilder.ToString(), oconPCS);
ocmdPCS.CommandTimeout = 1000;
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbResult);
return dtbResult;
}
/// <summary>
/// Get CCN Info
/// </summary>
/// <returns></returns>
private string GetCompanyFullName()
{
const string FULL_COMPANY_NAME = "CompanyFullName";
OleDbConnection oconPCS = null;
try
{
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbCommand ocmdPCS = null;
string strSql = "SELECT [Value]"
+ " FROM Sys_Param"
+ " WHERE [Name] = '" + FULL_COMPANY_NAME + "'";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
if(odrPCS.Read())
{
strResult = odrPCS["Value"].ToString().Trim();
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get Master Location Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetMasLocInfoByID(string pstrID)
{
const string NAME_FLD = "Name";
string strResult = string.Empty;
OleDbConnection oconPCS = null;
try
{
OleDbDataReader odrPCS = null;
OleDbCommand ocmdPCS = null;
string strSql = "SELECT Code, Name"
+ " FROM MST_MasterLocation"
+ " WHERE MasterLocationID = " + pstrID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
if(odrPCS.Read())
{
strResult = odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + " (" + odrPCS[NAME_FLD].ToString().Trim() + ")";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get CCN Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetCCNInfoByID(string pstrID)
{
string strResult = string.Empty;
OleDbConnection oconPCS = null;
try
{
OleDbDataReader odrPCS = null;
OleDbCommand ocmdPCS = null;
string strSql = "SELECT " + PRODUCT_CODE_FLD + ", " + PRODUCT_NAME_FLD
+ " FROM MST_CCN"
+ " WHERE MST_CCN.CCNID = " + pstrID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
if(odrPCS.Read())
{
strResult = odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + " (" + odrPCS[PRODUCT_NAME_FLD].ToString().Trim() + ")";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get Location Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetLocationInfo(string pstrIDList)
{
const string SEMI_COLON = "; ";
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT Code";
strSql += " FROM MST_Location";
strSql += " WHERE LocationID IN (" + pstrIDList + ")";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
while(odrPCS.Read())
{
strResult += odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + SEMI_COLON;
}
}
if(strResult.Length > DATA_MAX_LENGTH)
{
int i = strResult.IndexOf(SEMI_COLON, DATA_MAX_LENGTH);
if(i > 0)
{
strResult = strResult.Substring(0, i + SEMI_COLON.Length) + "...";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get Location Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetTransTypeInfo(string pstrIDList)
{
const string SEMI_COLON = "; ";
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT Description";
strSql += " FROM MST_TranType";
strSql += " WHERE TranTypeID IN (" + pstrIDList + ")";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
while(odrPCS.Read())
{
strResult += odrPCS[PRODUCT_NAME_FLD].ToString().Trim() + SEMI_COLON;
}
}
if(strResult.Length > DATA_MAX_LENGTH)
{
int i = strResult.IndexOf(SEMI_COLON, DATA_MAX_LENGTH);
if(i > 0)
{
strResult = strResult.Substring(0, i + SEMI_COLON.Length) + "...";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get Product Code List
/// </summary>
/// <param name="pstrIDList"></param>
/// <returns></returns>
private string GetProductInfo(string pstrIDList)
{
const string SEMI_COLON = "; ";
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT Code";
strSql += " FROM ITM_Product";
strSql += " WHERE ProductID IN (" + pstrIDList + ")";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
while(odrPCS.Read())
{
strResult += odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + SEMI_COLON;
}
}
if(strResult.Length > DATA_MAX_LENGTH)
{
int i = strResult.IndexOf(SEMI_COLON, DATA_MAX_LENGTH);
if(i > 0)
{
strResult = strResult.Substring(0, i + SEMI_COLON.Length) + "...";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
private string GetFieldInfoFromTable(string pstrTableName,string pstrFieldName,string pstrFieldKey, string pstrIDList)
{
const string SEMI_COLON = "; ";
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT " + pstrFieldName
+ " FROM " + pstrTableName
+ " WHERE " + pstrFieldKey + " IN (" + pstrIDList + ")";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
while(odrPCS.Read())
{
strResult += odrPCS[pstrFieldName].ToString().Trim() + SEMI_COLON;
}
}
if(strResult.Length > DATA_MAX_LENGTH)
{
int i = strResult.IndexOf(SEMI_COLON, DATA_MAX_LENGTH);
if(i > 0)
{
strResult = strResult.Substring(0, i + SEMI_COLON.Length) + "...";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
#endregion Delivery To Customer Schedule Report: Tuan TQ
#region Public Method
public object Invoke(string pstrMethod, object[] pobjParameters)
{
return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters);
}
/// <summary>
/// Build and show Detai lItem Price By PO Receipt
/// </summary>
/// <author> Tuan TQ, 11 Apr, 2006</author>
public DataTable ExecuteReport(string pstrCCNID,
string pstrStockTakingPeriodID,
string pstrDepartmentIDs,
string pstrProductionLineIDs,
string pstrLocationIDs,
string pstrBinIDs
)
{
// try
// {
string strPOTypeID = Convert.ToString((int)PCSComUtils.Common.POReceiptTypeEnum.ByInvoice);
const string DATE_HOUR_FORMAT = "dd-MM-yyyy HH:mm";
const string REPORT_TEMPLATE = "StockTakingReport.xml";
const string RPT_PAGE_HEADER = "PageHeader";
const string REPORT_NAME = "StockTakingReport";
const string RPT_TITLE_FLD = "fldTitle";
const string RPT_COMPANY_FLD = "fldCompany";
const string RPT_CCN_FLD = "CCN";
const string RPT_MASTER_LOCATION_FLD = "Master Location";
const string RPT_LOCATION_FLD = "Master Location";
const string RPT_FROM_DATE_FLD = "From Date";
const string RPT_TO_DATE_FLD = "To Date";
const string RPT_PART_NO_FLD = "Part No.";
const string RPT_TRANSACTION_TYPE_FLD = "Trans. Type";
DataTable dtbDataSource = null;
dtbDataSource = GetStockTakingData(pstrCCNID,
pstrStockTakingPeriodID,
pstrDepartmentIDs,
pstrProductionLineIDs,
pstrLocationIDs,
pstrBinIDs);
//Create builder object
ReportBuilder reportBuilder = new ReportBuilder();
//Set report name
reportBuilder.ReportName = REPORT_NAME;
//Set Datasource
reportBuilder.SourceDataTable = dtbDataSource;
//Set report layout location
reportBuilder.ReportDefinitionFolder = mstrReportDefinitionFolder;
reportBuilder.ReportLayoutFile = REPORT_TEMPLATE;
reportBuilder.UseLayoutFile = true;
reportBuilder.MakeDataTableForRender();
// and show it in preview dialog
PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog printPreview = new PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog();
//Attach report viewer
reportBuilder.ReportViewer = printPreview.ReportViewer;
reportBuilder.RenderReport();
reportBuilder.DrawPredefinedField(RPT_COMPANY_FLD, GetCompanyFullName());
//Draw parameters
System.Collections.Specialized.NameValueCollection arrParamAndValue = new System.Collections.Specialized.NameValueCollection();
arrParamAndValue.Add(RPT_CCN_FLD, GetCCNInfoByID(pstrCCNID));
arrParamAndValue.Add("StockTakingPeriod ", GetFieldInfoFromTable("IV_StockTakingPeriod","Description","StockTakingPeriodID", pstrStockTakingPeriodID));
//
if(pstrDepartmentIDs != null && pstrDepartmentIDs != string.Empty)
{
arrParamAndValue.Add("Department ", GetFieldInfoFromTable(MST_DepartmentTable.TABLE_NAME,"Code",MST_DepartmentTable.DEPARTMENTID_FLD, pstrDepartmentIDs));
}
//
if(pstrProductionLineIDs != null && pstrProductionLineIDs != string.Empty)
{
arrParamAndValue.Add("Production Line ", GetFieldInfoFromTable(PRO_ProductionLineTable.TABLE_NAME,"Code",PRO_ProductionLineTable.PRODUCTIONLINEID_FLD,pstrProductionLineIDs));
}
//Location list
if(pstrLocationIDs != null && pstrLocationIDs != string.Empty)
{
arrParamAndValue.Add("Location ", GetLocationInfo(pstrLocationIDs));
}
//Part no list
if(pstrBinIDs != null && pstrBinIDs != string.Empty)
{
arrParamAndValue.Add("Bin " , GetFieldInfoFromTable(MST_BINTable.TABLE_NAME,"Code",MST_BINTable.BINID_FLD,pstrBinIDs));
}
//
// //Trans. type list
// if(pstrTransTypeIDList != null && pstrTransTypeIDList != string.Empty)
// {
// arrParamAndValue.Add(RPT_TRANSACTION_TYPE_FLD, GetTransTypeInfo(pstrTransTypeIDList));
// }
//Anchor the Parameter drawing canvas cordinate to the fldTitle
C1.C1Report.Field fldTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD);
double dblStartX = fldTitle.Left;
double dblStartY = fldTitle.Top + 1.3 * fldTitle.RenderHeight;
reportBuilder.GetSectionByName(RPT_PAGE_HEADER).CanGrow = true;
reportBuilder.DrawParameters(reportBuilder.GetSectionByName(RPT_PAGE_HEADER), dblStartX, dblStartY, arrParamAndValue, reportBuilder.Report.Font.Size);
try
{
printPreview.FormTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD).Text;
}
catch
{}
reportBuilder.RefreshReport();
printPreview.Show();
//return table
return dtbDataSource;
// }
// catch (Exception ex)
// {
// throw ex;
// }
}
#endregion Public Method
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Schema;
using Ripple.Core.Enums;
using Ripple.Core.Types;
namespace Ripple.Core.Transactions
{
public class TxFormat : Dictionary<Field, TxFormat.Requirement>
{
public enum Requirement
{
Default,
Optional,
Required
}
public TxFormat()
{
// Common fields
this[Field.TransactionType] = Requirement.Required;
this[Field.Account] = Requirement.Required;
this[Field.Fee] = Requirement.Required;
this[Field.Sequence] = Requirement.Required;
this[Field.SigningPubKey] = Requirement.Required;
this[Field.Flags] = Requirement.Optional;
this[Field.SourceTag] = Requirement.Optional;
this[Field.PreviousTxnID] = Requirement.Optional;
this[Field.LastLedgerSequence] = Requirement.Optional;
this[Field.AccountTxnID] = Requirement.Optional;
this[Field.OperationLimit] = Requirement.Optional;
this[Field.Memos] = Requirement.Optional;
this[Field.TxnSignature] = Requirement.Optional;
this[Field.Signers] = Requirement.Optional;
}
public static void Validate(StObject obj)
{
var errors = new List<string>();
Validate(obj, errors.Add);
if (errors.Count > 0)
{
throw new TxFormatValidationException(string.Join("\n", errors));
}
}
internal static void Validate(StObject obj, Action<string> onError)
{
if (!obj.Has(Field.TransactionType))
{
onError("Missing `TransactionType` field");
return;
}
var tt = obj[Field.TransactionType];
if (tt == null)
{
onError("`TransactionType` is set to null");
return;
}
var format = Formats[tt];
var allFields = new SortedSet<Field>(obj.Fields.Keys);
allFields.UnionWith(format.Keys);
foreach (var field in allFields)
{
var inFormat = format.ContainsKey(field);
ISerializedType fieldValue;
var inObject = obj.Fields.TryGetValue(field, out fieldValue);
if (!inFormat)
{
onError($"`{tt}` has no `{field}` field");
}
else if (format[field] == Requirement.Required)
{
if (!inObject)
{
onError($"`{tt}` has required field `{field}`");
}
else if (fieldValue == null)
{
onError($"Required field `{field}` is set to null");
}
// TODO: associated type for field is wrong
// It should be nearly impossible anyway because FromJson
// throws when the json is invalid for the field type and
// the StObject[] indexers all use typed fields externally
}
}
}
public static Dictionary<TransactionType, TxFormat> Formats;
static TxFormat()
{
Formats = new Dictionary<TransactionType, TxFormat>
{
[TransactionType.AccountSet] = new TxFormat
{
[Field.EmailHash] = Requirement.Optional,
[Field.WalletLocator] = Requirement.Optional,
[Field.WalletSize] = Requirement.Optional,
[Field.MessageKey] = Requirement.Optional,
[Field.Domain] = Requirement.Optional,
[Field.TransferRate] = Requirement.Optional,
[Field.SetFlag] = Requirement.Optional,
[Field.ClearFlag] = Requirement.Optional
},
[TransactionType.TrustSet] = new TxFormat
{
[Field.LimitAmount] = Requirement.Optional,
[Field.QualityIn] = Requirement.Optional,
[Field.QualityOut] = Requirement.Optional
},
[TransactionType.OfferCreate] = new TxFormat
{
[Field.TakerPays] = Requirement.Required,
[Field.TakerGets] = Requirement.Required,
[Field.Expiration] = Requirement.Optional,
[Field.OfferSequence] = Requirement.Optional
},
[TransactionType.OfferCancel] = new TxFormat
{
[Field.OfferSequence] = Requirement.Required
},
[TransactionType.SetRegularKey] = new TxFormat
{
[Field.RegularKey] = Requirement.Optional
},
[TransactionType.Payment] = new TxFormat
{
[Field.Destination] = Requirement.Required,
[Field.Amount] = Requirement.Required,
[Field.SendMax] = Requirement.Optional,
[Field.Paths] = Requirement.Default,
[Field.InvoiceID] = Requirement.Optional,
[Field.DestinationTag] = Requirement.Optional,
[Field.DeliverMin] = Requirement.Optional
},
[TransactionType.EnableAmendment] = new TxFormat
{
[Field.LedgerSequence] = Requirement.Optional,
[Field.Amendment] = Requirement.Required
},
[TransactionType.SetFee] = new TxFormat
{
[Field.LedgerSequence] = Requirement.Optional,
[Field.BaseFee] = Requirement.Required,
[Field.ReferenceFeeUnits] = Requirement.Required,
[Field.ReserveBase] = Requirement.Required,
[Field.ReserveIncrement] = Requirement.Required
},
[TransactionType.SuspendedPaymentCreate] = new TxFormat
{
[Field.Destination] = Requirement.Required,
[Field.Amount] = Requirement.Required,
[Field.Digest] = Requirement.Optional,
[Field.CancelAfter] = Requirement.Optional,
[Field.FinishAfter] = Requirement.Optional,
[Field.DestinationTag] = Requirement.Optional
},
[TransactionType.SuspendedPaymentFinish] = new TxFormat
{
[Field.Owner] = Requirement.Required,
[Field.OfferSequence] = Requirement.Required,
[Field.Method] = Requirement.Optional,
[Field.Digest] = Requirement.Optional,
[Field.Proof] = Requirement.Optional
},
[TransactionType.SuspendedPaymentCancel] = new TxFormat
{
[Field.Owner] = Requirement.Required,
[Field.OfferSequence] = Requirement.Required
},
[TransactionType.TicketCreate] = new TxFormat
{
[Field.Target] = Requirement.Optional,
[Field.Expiration] = Requirement.Optional
},
[TransactionType.TicketCancel] = new TxFormat
{
[Field.TicketID] = Requirement.Required
},
// The SignerEntries are optional because a SignerList is deleted by
// setting the SignerQuorum to zero and omitting SignerEntries.
[TransactionType.SignerListSet] = new TxFormat
{
[Field.SignerQuorum] = Requirement.Required,
[Field.SignerEntries] = Requirement.Optional
}
};
}
}
public class TxFormatValidationException : FormatException
{
public TxFormatValidationException(string msg) : base(msg)
{
}
}
}
| |
// #######################################################
//
// # Copyright (C) 2010, Dave Taylor and Arnold Zokas
//
// # This source code is subject to terms and conditions of the New BSD License.
// # A copy of the license can be found in the license.txt file at the root of this distribution.
// # If you cannot locate the New BSD License, please send an email to dave@the-taylors.org or arnold.zokas@coderoom.net.
// # By using this source code in any fashion, you are agreeing to be bound by the terms of the New BSD License.
// # You must not remove this notice, or any other, from this software.
//
// #######################################################
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Rivet.Console
{
public sealed class Runner
{
private readonly ILogWriter _logWriter;
private readonly IParameterParser _parameterParser;
public Runner(ILogWriter logWriter, IParameterParser parameterParser)
{
_logWriter = logWriter;
_parameterParser = parameterParser;
}
public RivetParameters Parameters { get; private set; }
public bool Execute(params string[] args)
{
try
{
DisplayVersionAndCopyrightInformation();
Parameters = _parameterParser.Parse(args);
if (Parameters.DisplayHelpInformation)
{
DisplayHelpInformation();
return false;
}
if (!Directory.Exists(Parameters.TargetDirectory))
{
_logWriter.WriteErrorMessage(string.Format("Directory \"{0}\" could not be found.", Parameters.TargetDirectory));
Parameters.DisplayHelpInformation = true;
DisplayHelpInformation();
return false;
}
DisplayTargetDirectory(Parameters.TargetDirectory);
SourceFiles sourceFiles = GetSourceFiles(Parameters.TargetDirectory);
if (sourceFiles.Count == 0)
{
_logWriter.WriteErrorMessage(string.Format("Directory \"{0}\" does not contain any javascript files.", Parameters.TargetDirectory));
return false;
}
DisplayDiscoveredSourceFiles(sourceFiles);
ParserOptions parserOptions = Parameters.ToParserOptions();
DisplayParserOptions(parserOptions);
var outputFiles = Combine(sourceFiles, parserOptions);
SaveOutputFiles(outputFiles);
DeleteComponents(outputFiles);
return true;
}
catch (Exception ex)
{
_logWriter.WriteErrorMessage(ex.Message);
return false;
}
}
private void SaveOutputFiles(IEnumerable<SourceFile> outputFiles)
{
foreach (var outputFile in outputFiles)
{
var path = Path.Combine(Parameters.TargetDirectory, outputFile.Identity);
File.WriteAllText(path, outputFile.Body);
DisplaySavedOutputFilePath(path);
}
}
private static SourceFiles GetSourceFiles(string sourceDirectoryPath)
{
const string fileSearchPattern = "*.js";
var sourceFiles = from path in Directory.GetFiles(sourceDirectoryPath, fileSearchPattern, SearchOption.AllDirectories)
let identity = path
let content = File.ReadAllText(path)
select new SourceFile(identity, content);
return new SourceFiles(sourceFiles);
}
private static IEnumerable<SourceFile> Combine(SourceFiles sourceFiles, ParserOptions parserOptions)
{
var parser = new Parser();
return parser.ParseSourceFiles(sourceFiles, parserOptions);
}
private void DeleteComponents(IEnumerable<SourceFile> outputFiles)
{
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage("Deleting components:");
foreach (var outputFile in outputFiles)
{
// delete components
foreach (var component in outputFile.Components)
{
var componentPath = Path.Combine(Parameters.TargetDirectory, component.Identity);
if (File.Exists(componentPath))
{
File.Delete(componentPath);
_logWriter.WriteMessage(string.Format("\t- {0}", FlattenPath(component.Identity)));
}
}
// delete empty subdirectories
DeleteSubDirectories(Parameters.TargetDirectory);
}
}
private void DeleteSubDirectories(string targetDirectory)
{
const string fileSearchPattern = "*";
var subDirectories = Directory.GetDirectories(targetDirectory);
foreach (var subDirectory in subDirectories)
{
if (Directory.GetFiles(subDirectory, fileSearchPattern, SearchOption.AllDirectories).Any())
DeleteSubDirectories(subDirectory);
else
{
Directory.Delete(subDirectory, recursive: true);
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage(string.Format("Deleted empty subdirectory \"{0}\"", subDirectory));
}
}
}
private void DisplayVersionAndCopyrightInformation()
{
var rivetAssembly = Assembly.GetAssembly(typeof (Parser));
var version = rivetAssembly.GetName().Version;
var title = GetAttribute<AssemblyDescriptionAttribute>(rivetAssembly).Description;
var copyright = GetAttribute<AssemblyCopyrightAttribute>(rivetAssembly).Copyright;
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteImportantMessage(string.Format("{0} v{1}.{2}", title, version.Major, version.Minor));
_logWriter.WriteImportantMessage(copyright);
}
private void DisplayHelpInformation()
{
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage("Usage: Rivet.Console.exe [/help] <path> [options]");
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage("\t/help\tShows this help information");
_logWriter.WriteMessage("\t<path>\tPath to directory containing javascript files");
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage("Options:");
_logWriter.WriteMessage("\t-v:name=value\tReplaces token [name] with [value] in processed files.");
_logWriter.WriteMessage("\t\t\tThis can be specified multiple times to replace");
_logWriter.WriteMessage("\t\t\tmultiple tokens.");
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage("Example:");
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage("\tRivet.Console.exe D:\\website\\js -v:debug=false -v:trace=true");
}
private void DisplayTargetDirectory(string targetDirectory)
{
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage(string.Format("Target directory: {0}", targetDirectory));
}
private void DisplayDiscoveredSourceFiles(SourceFiles sourceFiles)
{
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage(string.Format("Discovered {0} javascript file(s):", sourceFiles.Count));
foreach (var sourceFile in sourceFiles)
{
_logWriter.WriteMessage(string.Format("\t- {0}", FlattenPath(sourceFile.Identity)));
}
}
private void DisplayParserOptions(ParserOptions parserOptions)
{
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage("Variables:");
foreach (var variable in parserOptions.Variables)
{
_logWriter.WriteMessage(string.Format("\t- {0}={1}", variable.Key, variable.Value));
}
}
private void DisplaySavedOutputFilePath(string path)
{
_logWriter.WriteMessage(string.Empty);
_logWriter.WriteMessage(string.Format("Saved combined file: {0}", path));
}
private static TAttribute GetAttribute<TAttribute>(Assembly assembly)
{
return ((TAttribute)assembly.GetCustomAttributes(typeof (TAttribute), inherit: false).First());
}
private string FlattenPath(string absolutePath)
{
const int lengthOfDirectorySeparatorChar = 1;
return absolutePath.Remove(0, Parameters.TargetDirectory.Length + lengthOfDirectorySeparatorChar);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdigEngine.Extensions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Markdig.Helpers;
using Markdig.Parsers;
using Markdig.Syntax;
using Microsoft.DocAsCode.Common;
public class QuoteSectionNoteParser : BlockParser
{
private List<string> _noteTypes = new List<string>{ "[!NOTE]", "[!TIP]", "[!WARNING]", "[!IMPORTANT]", "[!CAUTION]" };
public QuoteSectionNoteParser()
{
OpeningCharacters = new[] { '>' };
}
public override BlockState TryOpen(BlockProcessor processor)
{
if (processor.IsCodeIndent)
{
return BlockState.None;
}
var column = processor.Column;
var sourcePosition = processor.Start;
var quoteChar = processor.CurrentChar;
var c = processor.NextChar();
if (c.IsSpaceOrTab())
{
processor.NextColumn();
}
var rawNewBlock = new QuoteSectionNoteBlock(this)
{
QuoteChar = quoteChar,
Column = column,
Span = new SourceSpan(sourcePosition, processor.Line.End),
};
TryParseFromLine(processor, rawNewBlock);
processor.NewBlocks.Push(rawNewBlock);
if (rawNewBlock.QuoteType == QuoteSectionNoteType.DFMVideo)
{
return BlockState.BreakDiscard;
}
else
{
return BlockState.Continue;
}
}
public override BlockState TryContinue(BlockProcessor processor, Block block)
{
if (processor.IsCodeIndent)
{
return BlockState.None;
}
var quote = (QuoteSectionNoteBlock)block;
var column = processor.Column;
if (quote.QuoteType == QuoteSectionNoteType.DFMVideo)
{
return BlockState.BreakDiscard;
}
var c = processor.CurrentChar;
if (c != quote.QuoteChar)
{
return processor.IsBlankLine ? BlockState.BreakDiscard : BlockState.None;
}
c = processor.NextChar(); // Skip opening char
if (c.IsSpace())
{
processor.NextChar(); // Skip following space
}
// Check for New DFM block
if (TryParseFromLine(processor, new QuoteSectionNoteBlock(this)))
{
// Meet note or section, close this block, new block will be open in the next steps
processor.GoToColumn(column);
return BlockState.None;
}
else
{
block.UpdateSpanEnd(processor.Line.End);
return BlockState.Continue;
}
}
private bool TryParseFromLine(BlockProcessor processor, QuoteSectionNoteBlock block)
{
int originalColumn = processor.Column;
block.QuoteType = QuoteSectionNoteType.MarkdownQuote;
if (processor.CurrentChar != '[')
{
return false;
}
var stringBuilder = StringBuilderCache.Local();
var c = processor.CurrentChar;
var hasExcape = false;
while (c != '\0' && (c != ']' || hasExcape))
{
if (c == '\\' && !hasExcape)
{
hasExcape = true;
}
else
{
stringBuilder.Append(c);
hasExcape = false;
}
c = processor.NextChar();
}
stringBuilder.Append(c);
var infoString = stringBuilder.ToString().Trim();
if (c == '\0')
{
processor.GoToColumn(originalColumn);
return false;
}
if (c == ']')
{
// "> [!NOTE] content" is invalid, go to end to see it.
processor.NextChar();
while (processor.CurrentChar.IsSpaceOrTab()) processor.NextChar();
var isNoteVideoDiv = (infoString.StartsWith("[!div", StringComparison.OrdinalIgnoreCase)) ||
(infoString.StartsWith("[!Video", StringComparison.OrdinalIgnoreCase)) ||
IsNoteType(infoString);
if (processor.CurrentChar != '\0' && isNoteVideoDiv)
{
Logger.LogWarning("Text in the first line of Note/Section/Video is not valid. Will be rendererd to <blockquote>");
processor.GoToColumn(originalColumn);
return false;
}
}
if (IsNoteType(infoString))
{
block.QuoteType = QuoteSectionNoteType.DFMNote;
block.NoteTypeString = infoString.Substring(2, infoString.Length - 3);
return true;
}
if (infoString.StartsWith("[!div", StringComparison.OrdinalIgnoreCase))
{
block.QuoteType = QuoteSectionNoteType.DFMSection;
string attribute = infoString.Substring(5, infoString.Length - 6).Trim();
if (attribute.Length >= 2 && attribute.First() == '`' && attribute.Last() == '`')
{
block.SectionAttributeString = attribute.Substring(1, attribute.Length - 2).Trim();
}
if (attribute.Length >= 1 && attribute.First() != '`' && attribute.Last() != '`')
{
block.SectionAttributeString = attribute;
}
return true;
}
if (infoString.StartsWith("[!Video", StringComparison.OrdinalIgnoreCase))
{
string link = infoString.Substring(7, infoString.Length - 8);
if (link.StartsWith(" http://") || link.StartsWith(" https://"))
{
block.QuoteType = QuoteSectionNoteType.DFMVideo;
block.VideoLink = link.Trim();
return true;
}
}
processor.GoToColumn(originalColumn);
return false;
}
private bool IsRestLineEmpty(BlockProcessor processor, int movedCharCount)
{
int column = processor.Column;
while (movedCharCount-- > 0) processor.NextChar();
while (processor.CurrentChar.IsSpaceOrTab()) processor.NextChar();
return processor.CurrentChar == '\0';
}
private bool IsNoteType(string infoString)
{
foreach (var noteType in _noteTypes)
{
if (string.Equals(infoString, noteType, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
[Trait("connection", "tcp")]
public static class WeakRefTestYukonSpecific
{
private const string COMMAND_TEXT_1 = "SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax from Customers";
private const string COMMAND_TEXT_2 = "SELECT CompanyName from Customers";
private const string COLUMN_NAME_2 = "CompanyName";
private const string DATABASE_NAME = "master";
private const int CONCURRENT_COMMANDS = 5;
[CheckConnStrSetupFact]
public static void TestReaderMars()
{
string connectionString =
(new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
{
MultipleActiveResultSets = true,
MaxPoolSize = 1
}).ConnectionString;
TestReaderMarsCase("Case 1: ExecuteReader*5 Close, ExecuteReader.", connectionString, ReaderTestType.ReaderClose, ReaderVerificationType.ExecuteReader);
TestReaderMarsCase("Case 2: ExecuteReader*5 Dispose, ExecuteReader.", connectionString, ReaderTestType.ReaderDispose, ReaderVerificationType.ExecuteReader);
TestReaderMarsCase("Case 3: ExecuteReader*5 GC, ExecuteReader.", connectionString, ReaderTestType.ReaderGC, ReaderVerificationType.ExecuteReader);
TestReaderMarsCase("Case 4: ExecuteReader*5 Connection Close, ExecuteReader.", connectionString, ReaderTestType.ConnectionClose, ReaderVerificationType.ExecuteReader);
TestReaderMarsCase("Case 5: ExecuteReader*5 GC, Connection Close, ExecuteReader.", connectionString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.ExecuteReader);
TestReaderMarsCase("Case 6: ExecuteReader*5 Close, ChangeDatabase.", connectionString, ReaderTestType.ReaderClose, ReaderVerificationType.ChangeDatabase);
TestReaderMarsCase("Case 7: ExecuteReader*5 Dispose, ChangeDatabase.", connectionString, ReaderTestType.ReaderDispose, ReaderVerificationType.ChangeDatabase);
TestReaderMarsCase("Case 8: ExecuteReader*5 GC, ChangeDatabase.", connectionString, ReaderTestType.ReaderGC, ReaderVerificationType.ChangeDatabase);
TestReaderMarsCase("Case 9: ExecuteReader*5 Connection Close, ChangeDatabase.", connectionString, ReaderTestType.ConnectionClose, ReaderVerificationType.ChangeDatabase);
TestReaderMarsCase("Case 10: ExecuteReader*5 GC, Connection Close, ChangeDatabase.", connectionString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.ChangeDatabase);
TestReaderMarsCase("Case 11: ExecuteReader*5 Close, BeginTransaction.", connectionString, ReaderTestType.ReaderClose, ReaderVerificationType.BeginTransaction);
TestReaderMarsCase("Case 12: ExecuteReader*5 Dispose, BeginTransaction.", connectionString, ReaderTestType.ReaderDispose, ReaderVerificationType.BeginTransaction);
TestReaderMarsCase("Case 13: ExecuteReader*5 Connection Close, BeginTransaction.", connectionString, ReaderTestType.ConnectionClose, ReaderVerificationType.BeginTransaction);
TestReaderMarsCase("Case 14: ExecuteReader*5 GC, Connection Close, BeginTransaction.", connectionString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.BeginTransaction);
}
[CheckConnStrSetupFact]
public static void TestTransactionSingle()
{
string connectionString =
(new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
{
MultipleActiveResultSets = true,
MaxPoolSize = 1
}).ConnectionString;
TestTransactionSingleCase("Case 1: BeginTransaction, Rollback.", connectionString, TransactionTestType.TransactionRollback);
TestTransactionSingleCase("Case 2: BeginTransaction, Dispose.", connectionString, TransactionTestType.TransactionDispose);
TestTransactionSingleCase("Case 3: BeginTransaction, GC.", connectionString, TransactionTestType.TransactionGC);
TestTransactionSingleCase("Case 4: BeginTransaction, Connection Close.", connectionString, TransactionTestType.ConnectionClose);
TestTransactionSingleCase("Case 5: BeginTransaction, GC, Connection Close.", connectionString, TransactionTestType.TransactionGCConnectionClose);
}
private enum ReaderTestType
{
ReaderClose,
ReaderDispose,
ReaderGC,
ConnectionClose,
ReaderGCConnectionClose,
}
private enum ReaderVerificationType
{
ExecuteReader,
ChangeDatabase,
BeginTransaction,
EnlistDistributedTransaction,
}
private enum TransactionTestType
{
TransactionRollback,
TransactionDispose,
TransactionGC,
ConnectionClose,
TransactionGCConnectionClose,
}
public static int GCCount = 0;
[MethodImpl(MethodImplOptions.NoInlining)]
private static void TestReaderMarsCase(string caseName, string connectionString, ReaderTestType testType, ReaderVerificationType verificationType)
{
WeakReference weak = null;
SqlCommand[] cmd = new SqlCommand[CONCURRENT_COMMANDS];
SqlDataReader[] gch = new SqlDataReader[CONCURRENT_COMMANDS];
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
for (int i = 0; i < CONCURRENT_COMMANDS; i++)
{
cmd[i] = con.CreateCommand();
cmd[i].CommandText = COMMAND_TEXT_1;
if ((testType != ReaderTestType.ReaderGC) && (testType != ReaderTestType.ReaderGCConnectionClose))
gch[i] = cmd[i].ExecuteReader();
else
gch[i] = null;
}
for (int i = 0; i < CONCURRENT_COMMANDS; i++)
{
switch (testType)
{
case ReaderTestType.ReaderClose:
gch[i].Dispose();
break;
case ReaderTestType.ReaderDispose:
gch[i].Dispose();
break;
case ReaderTestType.ReaderGC:
weak = OpenNullifyReader(cmd[i]);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Transaction is still alive on TestReaderMars: ReaderGC");
break;
case ReaderTestType.ConnectionClose:
GC.SuppressFinalize(gch[i]);
con.Close();
con.Open();
break;
case ReaderTestType.ReaderGCConnectionClose:
weak = OpenNullifyReader(cmd[i]);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Transaction is still alive on TestReaderMars: ReaderGCConnectionClose");
con.Close();
con.Open();
break;
}
cmd[i].Dispose();
}
SqlCommand verificationCmd = con.CreateCommand();
switch (verificationType)
{
case ReaderVerificationType.ExecuteReader:
verificationCmd.CommandText = COMMAND_TEXT_2;
using (SqlDataReader rdr = verificationCmd.ExecuteReader())
{
rdr.Read();
DataTestUtility.AssertEqualsWithDescription(1, rdr.FieldCount, "Execute Reader should return expected Field count");
DataTestUtility.AssertEqualsWithDescription(COLUMN_NAME_2, rdr.GetName(0), "Execute Reader should return expected Field name");
}
break;
case ReaderVerificationType.ChangeDatabase:
con.ChangeDatabase(DATABASE_NAME);
DataTestUtility.AssertEqualsWithDescription(DATABASE_NAME, con.Database, "Change Database should return expected Database Name");
break;
case ReaderVerificationType.BeginTransaction:
verificationCmd.Transaction = con.BeginTransaction();
verificationCmd.CommandText = "select @@trancount";
int tranCount = (int)verificationCmd.ExecuteScalar();
DataTestUtility.AssertEqualsWithDescription(1, tranCount, "Begin Transaction should return expected Transaction count");
break;
}
verificationCmd.Dispose();
}
}
private static WeakReference OpenNullifyReader(SqlCommand command)
{
SqlDataReader reader = command.ExecuteReader();
WeakReference weak = new WeakReference(reader);
reader = null;
return weak;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void TestTransactionSingleCase(string caseName, string connectionString, TransactionTestType testType)
{
WeakReference weak = null;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlTransaction gch = null;
if ((testType != TransactionTestType.TransactionGC) && (testType != TransactionTestType.TransactionGCConnectionClose))
gch = con.BeginTransaction();
switch (testType)
{
case TransactionTestType.TransactionRollback:
gch.Rollback();
break;
case TransactionTestType.TransactionDispose:
gch.Dispose();
break;
case TransactionTestType.TransactionGC:
weak = OpenNullifyTransaction(con);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Transaction is still alive on TestTransactionSingle: TransactionGC");
break;
case TransactionTestType.ConnectionClose:
GC.SuppressFinalize(gch);
con.Close();
con.Open();
break;
case TransactionTestType.TransactionGCConnectionClose:
weak = OpenNullifyTransaction(con);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Transaction is still alive on TestTransactionSingle: TransactionGCConnectionClose");
con.Close();
con.Open();
break;
}
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select @@trancount";
int tranCount = (int)cmd.ExecuteScalar();
DataTestUtility.AssertEqualsWithDescription(0, tranCount, "TransactionSingle Case " + caseName + " should return expected trans count");
}
}
}
private static WeakReference OpenNullifyTransaction(SqlConnection connection)
{
SqlTransaction transaction = connection.BeginTransaction();
WeakReference weak = new WeakReference(transaction);
transaction = null;
return weak;
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A head-tracked stereoscopic virtual reality camera rig.
/// </summary>
[ExecuteInEditMode]
public class OVRCameraRig : MonoBehaviour
{
/// <summary>
/// The left eye camera.
/// </summary>
public Camera leftEyeCamera { get; private set; }
/// <summary>
/// The right eye camera.
/// </summary>
public Camera rightEyeCamera { get; private set; }
/// <summary>
/// Provides a root transform for all anchors in tracking space.
/// </summary>
public Transform trackingSpace { get; private set; }
/// <summary>
/// Always coincides with the pose of the left eye.
/// </summary>
public Transform leftEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with average of the left and right eye poses.
/// </summary>
public Transform centerEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the right eye.
/// </summary>
public Transform rightEyeAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the left hand.
/// </summary>
public Transform leftHandAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the right hand.
/// </summary>
public Transform rightHandAnchor { get; private set; }
/// <summary>
/// Always coincides with the pose of the tracker.
/// </summary>
public Transform trackerAnchor { get; private set; }
/// <summary>
/// Occurs when the eye pose anchors have been set.
/// </summary>
public event System.Action<OVRCameraRig> UpdatedAnchors;
private bool needsCameraConfigure = true;
private readonly string trackingSpaceName = "TrackingSpace";
private readonly string trackerAnchorName = "TrackerAnchor";
private readonly string eyeAnchorName = "EyeAnchor";
private readonly string handAnchorName = "HandAnchor";
private readonly string legacyEyeAnchorName = "Camera";
private Material mat;
#if !UNITY_ANDROID || UNITY_EDITOR
private Camera mirrorCamera;
#endif
#region Unity Messages
private void Awake()
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
OVRManager.Created += () => { needsCameraConfigure = true; };
OVRManager.NativeTextureScaleModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.VirtualTextureScaleModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.EyeTextureAntiAliasingModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.EyeTextureDepthModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.EyeTextureFormatModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.MonoscopicModified += (prev, current) => { needsCameraConfigure = true; };
OVRManager.HdrModified += (prev, current) => { needsCameraConfigure = true; };
}
private void Start()
{
if (Application.isPlaying)
OVRManager.display.UpdatedTracking += ApplyTracking;
ApplyTracking();
}
private void OnDestroy()
{
if (Application.isPlaying)
OVRManager.display.UpdatedTracking -= ApplyTracking;
}
void ApplyTracking()
{
EnsureGameObjectIntegrity();
if (!Application.isPlaying)
return;
UpdateCameras();
UpdateAnchors();
}
#if !UNITY_ANDROID || UNITY_EDITOR
void OnRenderImage(RenderTexture src, RenderTexture dst)
{
if (!OVRManager.display.mirrorMode || !OVRManager.instance.isVRPresent || leftEyeCamera.targetTexture == null)
{
Graphics.Blit(src, dst);
return;
}
Vector2 scale = Vector2.one;
Vector2 offset = Vector2.zero;
// Correct the texture's aspect ratio to match the viewport.
float texAspect = (float)leftEyeCamera.targetTexture.width / (float)leftEyeCamera.targetTexture.height;
float screenAspect = (float)Screen.width / (float)Screen.height;
float aspect = screenAspect / texAspect;
if (aspect < 1f)
{
scale.x = aspect;
offset.x = -0.5f * (aspect - 1f);
}
else
{
scale.y = 1f/aspect;
offset.y = -0.5f * (1f/aspect - 1f);
}
float virtualScale = OVRPlugin.virtualTextureScale;
// Apply render scaling.
scale *= virtualScale;
offset *= virtualScale;
// Flip vertically.
offset.y = 1f - virtualScale + offset.y;
if (!mat)
mat = new Material(Shader.Find("Oculus/BlitCopy"));
mat.SetTextureScale("_MainTex", scale);
mat.SetTextureOffset("_MainTex", offset);
Graphics.Blit(leftEyeCamera.targetTexture, dst, mat);
}
#endif
#endregion
private void UpdateAnchors()
{
if (!OVRManager.instance.isVRPresent)
return;
bool monoscopic = OVRManager.instance.monoscopic;
OVRPose tracker = OVRManager.tracker.GetPose(0f);
OVRPose leftHand = OVRPlugin.GetNodePose(OVRPlugin.Node.LeftHand).ToOVRPose();
OVRPose rightHand = OVRPlugin.GetNodePose(OVRPlugin.Node.RightHand).ToOVRPose();
OVRPose hmdLeftEye = OVRManager.display.GetEyePose(OVREye.Left);
OVRPose hmdRightEye = OVRManager.display.GetEyePose(OVREye.Right);
trackerAnchor.localRotation = tracker.orientation;
leftHandAnchor.localRotation = leftHand.orientation;
rightHandAnchor.localRotation = rightHand.orientation;
centerEyeAnchor.localRotation = hmdLeftEye.orientation; // using left eye for now
leftEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : hmdLeftEye.orientation;
rightEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : hmdRightEye.orientation;
trackerAnchor.localPosition = tracker.position;
leftHandAnchor.localPosition = leftHand.position;
rightHandAnchor.localPosition = rightHand.position;
centerEyeAnchor.localPosition = 0.5f * (hmdLeftEye.position + hmdRightEye.position);
leftEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : hmdLeftEye.position;
rightEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : hmdRightEye.position;
if (UpdatedAnchors != null)
{
UpdatedAnchors(this);
}
}
private void UpdateCameras()
{
if (!OVRManager.instance.isVRPresent)
return;
if (needsCameraConfigure)
{
leftEyeCamera = ConfigureCamera(OVREye.Left);
rightEyeCamera = ConfigureCamera(OVREye.Right);
#if !UNITY_ANDROID || UNITY_EDITOR
if (Application.isPlaying)
{
mirrorCamera.cullingMask = 0;
mirrorCamera.renderingPath = RenderingPath.Forward;
mirrorCamera.targetTexture = null;
mirrorCamera.tag = "";
}
needsCameraConfigure = false;
#endif
}
}
public void EnsureGameObjectIntegrity()
{
if (trackingSpace == null)
trackingSpace = ConfigureRootAnchor(trackingSpaceName);
if (leftEyeAnchor == null)
leftEyeAnchor = ConfigureEyeAnchor(trackingSpace, OVREye.Left);
if (centerEyeAnchor == null)
centerEyeAnchor = ConfigureEyeAnchor(trackingSpace, OVREye.Center);
if (rightEyeAnchor == null)
rightEyeAnchor = ConfigureEyeAnchor(trackingSpace, OVREye.Right);
if (leftHandAnchor == null)
leftHandAnchor = ConfigureHandAnchor(trackingSpace, OVRPlugin.Node.LeftHand);
if (rightHandAnchor == null)
rightHandAnchor = ConfigureHandAnchor(trackingSpace, OVRPlugin.Node.RightHand);
if (trackerAnchor == null)
trackerAnchor = ConfigureTrackerAnchor(trackingSpace);
if (leftEyeCamera == null)
{
leftEyeCamera = leftEyeAnchor.GetComponent<Camera>();
if (leftEyeCamera == null)
{
leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>();
}
#if UNITY_ANDROID && !UNITY_EDITOR
if (leftEyeCamera.GetComponent<OVRPostRender>() == null)
{
leftEyeCamera.gameObject.AddComponent<OVRPostRender>();
}
#endif
}
if (rightEyeCamera == null)
{
rightEyeCamera = rightEyeAnchor.GetComponent<Camera>();
if (rightEyeCamera == null)
{
rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>();
}
#if UNITY_ANDROID && !UNITY_EDITOR
if (rightEyeCamera.GetComponent<OVRPostRender>() == null)
{
rightEyeCamera.gameObject.AddComponent<OVRPostRender>();
}
#endif
}
#if !UNITY_ANDROID || UNITY_EDITOR
if (Application.isPlaying && mirrorCamera == null)
{
mirrorCamera = GetComponent<Camera>();
if (mirrorCamera == null)
mirrorCamera = gameObject.AddComponent<Camera>();
}
#endif
}
private Transform ConfigureRootAnchor(string name)
{
Transform root = transform.Find(name);
if (root == null)
{
root = new GameObject(name).transform;
}
root.parent = transform;
root.localScale = Vector3.one;
root.localPosition = Vector3.zero;
root.localRotation = Quaternion.identity;
return root;
}
private Transform ConfigureEyeAnchor(Transform root, OVREye eye)
{
string name = eye.ToString() + eyeAnchorName;
Transform anchor = transform.Find(root.name + "/" + name);
if (anchor == null)
{
anchor = transform.Find(name);
}
if (anchor == null)
{
string legacyName = legacyEyeAnchorName + eye.ToString();
anchor = transform.Find(legacyName);
}
if (anchor == null)
{
anchor = new GameObject(name).transform;
}
anchor.name = name;
anchor.parent = root;
anchor.localScale = Vector3.one;
anchor.localPosition = Vector3.zero;
anchor.localRotation = Quaternion.identity;
return anchor;
}
private Transform ConfigureTrackerAnchor(Transform root)
{
string name = trackerAnchorName;
Transform anchor = transform.Find(root.name + "/" + name);
if (anchor == null)
{
anchor = new GameObject(name).transform;
}
anchor.parent = root;
anchor.localScale = Vector3.one;
anchor.localPosition = Vector3.zero;
anchor.localRotation = Quaternion.identity;
return anchor;
}
private Transform ConfigureHandAnchor(Transform root, OVRPlugin.Node hand)
{
if (hand != OVRPlugin.Node.LeftHand && hand != OVRPlugin.Node.RightHand)
return null;
string handName = (hand == OVRPlugin.Node.LeftHand) ? "Left" : "Right";
string name = handName + handAnchorName;
Transform anchor = transform.Find(root.name + "/" + name);
if (anchor == null)
{
anchor = transform.Find(name);
}
if (anchor == null)
{
anchor = new GameObject(name).transform;
}
anchor.name = name;
anchor.parent = root;
anchor.localScale = Vector3.one;
anchor.localPosition = Vector3.zero;
anchor.localRotation = Quaternion.identity;
return anchor;
}
private Camera ConfigureCamera(OVREye eye)
{
Transform anchor = (eye == OVREye.Left) ? leftEyeAnchor : rightEyeAnchor;
Camera cam = anchor.GetComponent<Camera>();
OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(eye);
cam.fieldOfView = eyeDesc.fov.y;
cam.aspect = eyeDesc.resolution.x / eyeDesc.resolution.y;
cam.targetTexture = OVRManager.display.GetEyeTexture(eye);
cam.hdr = OVRManager.instance.hdr;
#if UNITY_ANDROID && !UNITY_EDITOR
// Enforce camera render order
cam.depth = (eye == OVREye.Left) ?
(int)RenderEventType.LeftEyeEndFrame :
(int)RenderEventType.RightEyeEndFrame;
// If we don't clear the color buffer with a glClear, tiling GPUs
// will be forced to do an "unresolve" and read back the color buffer information.
// The clear is free on PowerVR, and possibly Mali, but it is a performance cost
// on Adreno, and we would be better off if we had the ability to discard/invalidate
// the color buffer instead of clearing.
// NOTE: The color buffer is not being invalidated in skybox mode, forcing an additional,
// wasted color buffer read before the skybox is drawn.
bool hasSkybox = ((cam.clearFlags == CameraClearFlags.Skybox) &&
((cam.gameObject.GetComponent<Skybox>() != null) || (RenderSettings.skybox != null)));
cam.clearFlags = (hasSkybox) ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;
#else
float vs = OVRManager.instance.virtualTextureScale;
cam.rect = new Rect(0f, 1f - vs, vs, vs);
#endif
// When rendering monoscopic, we will use the left camera render for both eyes.
if (eye == OVREye.Right)
{
cam.enabled = !OVRManager.instance.monoscopic;
}
// AA is documented to have no effect in deferred, but it causes black screens.
if (cam.actualRenderingPath == RenderingPath.DeferredLighting)
OVRManager.instance.eyeTextureAntiAliasing = OVRManager.RenderTextureAntiAliasing._1;
return cam;
}
}
| |
// 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.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Principal;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Threading.Tasks;
namespace System.ServiceModel
{
public class ClientCredentialsSecurityTokenManager : SecurityTokenManager
{
public ClientCredentialsSecurityTokenManager(ClientCredentials clientCredentials)
{
ClientCredentials = clientCredentials ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(clientCredentials));
}
public ClientCredentials ClientCredentials { get; }
private string GetServicePrincipalName(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
{
EndpointAddress targetAddress = initiatorRequirement.TargetAddress;
if (targetAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement));
}
IdentityVerifier identityVerifier;
SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement;
if (securityBindingElement != null)
{
identityVerifier = securityBindingElement.LocalClientSettings.IdentityVerifier;
}
else
{
identityVerifier = IdentityVerifier.CreateDefault();
}
EndpointIdentity identity;
identityVerifier.TryGetIdentity(targetAddress, out identity);
return SecurityUtils.GetSpnFromIdentity(identity, targetAddress);
}
private bool IsDigestAuthenticationScheme(SecurityTokenRequirement requirement)
{
if (requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty))
{
AuthenticationSchemes authScheme = (AuthenticationSchemes)requirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty];
if (!authScheme.IsSingleton() && authScheme != AuthenticationSchemes.IntegratedWindowsAuthentication)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authScheme", string.Format(SR.HttpRequiresSingleAuthScheme, authScheme));
}
return (authScheme == AuthenticationSchemes.Digest);
}
else
{
return false;
}
}
internal protected bool IsIssuedSecurityTokenRequirement(SecurityTokenRequirement requirement)
{
if (requirement != null && requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.IssuerAddressProperty))
{
// handle all issued token requirements except for spnego, tlsnego and secure conversation
if (requirement.TokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego || requirement.TokenType == ServiceModelSecurityTokenTypes.MutualSslnego
|| requirement.TokenType == ServiceModelSecurityTokenTypes.SecureConversation || requirement.TokenType == ServiceModelSecurityTokenTypes.Spnego)
{
return false;
}
else
{
return true;
}
}
return false;
}
public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
{
if (tokenRequirement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(tokenRequirement));
}
SecurityTokenProvider result = null;
if (tokenRequirement is RecipientServiceModelSecurityTokenRequirement && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate && tokenRequirement.KeyUsage == SecurityKeyUsage.Exchange)
{
// this is the uncorrelated duplex case
if (ClientCredentials.ClientCertificate.Certificate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCertificateNotProvidedOnClientCredentials)));
}
result = new X509SecurityTokenProvider(ClientCredentials.ClientCertificate.Certificate, ClientCredentials.ClientCertificate.CloneCertificate);
}
else if (tokenRequirement is InitiatorServiceModelSecurityTokenRequirement)
{
InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement;
string tokenType = initiatorRequirement.TokenType;
if (IsIssuedSecurityTokenRequirement(initiatorRequirement))
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider (IsIssuedSecurityTokenRequirement(initiatorRequirement)");
}
else if (tokenType == SecurityTokenTypes.X509Certificate)
{
if (initiatorRequirement.Properties.ContainsKey(SecurityTokenRequirement.KeyUsageProperty) && initiatorRequirement.KeyUsage == SecurityKeyUsage.Exchange)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider X509Certificate - SecurityKeyUsage.Exchange");
}
else
{
if (ClientCredentials.ClientCertificate.Certificate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCertificateNotProvidedOnClientCredentials)));
}
result = new X509SecurityTokenProvider(ClientCredentials.ClientCertificate.Certificate, ClientCredentials.ClientCertificate.CloneCertificate);
}
}
else if (tokenType == SecurityTokenTypes.Kerberos)
{
string spn = GetServicePrincipalName(initiatorRequirement);
result = new KerberosSecurityTokenProviderWrapper(
new KerberosSecurityTokenProvider(spn, ClientCredentials.Windows.AllowedImpersonationLevel, SecurityUtils.GetNetworkCredentialOrDefault(ClientCredentials.Windows.ClientCredential)));
}
else if (tokenType == SecurityTokenTypes.UserName)
{
if (ClientCredentials.UserName.UserName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.UserNamePasswordNotProvidedOnClientCredentials));
}
result = new UserNameSecurityTokenProvider(ClientCredentials.UserName.UserName, ClientCredentials.UserName.Password);
}
else if (tokenType == ServiceModelSecurityTokenTypes.SspiCredential)
{
if (IsDigestAuthenticationScheme(initiatorRequirement))
{
result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(ClientCredentials.HttpDigest.ClientCredential), true, TokenImpersonationLevel.Delegation);
}
else
{
#pragma warning disable 618 // to disable AllowNtlm obsolete warning.
result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(ClientCredentials.Windows.ClientCredential),
ClientCredentials.Windows.AllowNtlm,
ClientCredentials.Windows.AllowedImpersonationLevel);
#pragma warning restore 618
}
}
else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation)
{
result = CreateSecureConversationSecurityTokenProvider(initiatorRequirement);
}
}
if ((result == null) && !tokenRequirement.IsOptionalToken)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SecurityTokenManagerCannotCreateProviderForRequirement, tokenRequirement)));
}
return result;
}
public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version)
{
if (version == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(version));
}
MessageSecurityTokenVersion wsVersion = version as MessageSecurityTokenVersion;
if (wsVersion != null)
{
return new WSSecurityTokenSerializer(wsVersion.SecurityVersion, wsVersion.TrustVersion, wsVersion.SecureConversationVersion, wsVersion.EmitBspRequiredAttributes, null, null, null);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SecurityTokenManagerCannotCreateSerializerForVersion, version)));
}
}
private SecurityTokenProvider CreateSecureConversationSecurityTokenProvider(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement)
{
EndpointAddress targetAddress = initiatorRequirement.TargetAddress;
if (targetAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement));
}
SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement;
if (securityBindingElement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.TokenProviderRequiresSecurityBindingElement, initiatorRequirement));
}
LocalClientSecuritySettings localClientSettings = securityBindingElement.LocalClientSettings;
BindingContext issuerBindingContext = initiatorRequirement.GetProperty<BindingContext>(ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty);
ChannelParameterCollection channelParameters = initiatorRequirement.GetPropertyOrDefault<ChannelParameterCollection>(ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty, null);
bool isSessionMode = initiatorRequirement.SupportSecurityContextCancellation;
if (isSessionMode)
{
SecuritySessionSecurityTokenProvider sessionTokenProvider = new SecuritySessionSecurityTokenProvider();
sessionTokenProvider.BootstrapSecurityBindingElement = SecurityUtils.GetIssuerSecurityBindingElement(initiatorRequirement);
sessionTokenProvider.IssuedSecurityTokenParameters = initiatorRequirement.GetProperty<SecurityTokenParameters>(ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty);
sessionTokenProvider.IssuerBindingContext = issuerBindingContext;
sessionTokenProvider.KeyEntropyMode = securityBindingElement.KeyEntropyMode;
sessionTokenProvider.SecurityAlgorithmSuite = initiatorRequirement.SecurityAlgorithmSuite;
sessionTokenProvider.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(initiatorRequirement, this);
sessionTokenProvider.TargetAddress = targetAddress;
sessionTokenProvider.Via = initiatorRequirement.GetPropertyOrDefault<Uri>(InitiatorServiceModelSecurityTokenRequirement.ViaProperty, null);
Uri privacyNoticeUri;
if (initiatorRequirement.TryGetProperty(ServiceModelSecurityTokenRequirement.PrivacyNoticeUriProperty, out privacyNoticeUri))
{
sessionTokenProvider.PrivacyNoticeUri = privacyNoticeUri;
}
int privacyNoticeVersion;
if (initiatorRequirement.TryGetProperty(ServiceModelSecurityTokenRequirement.PrivacyNoticeVersionProperty, out privacyNoticeVersion))
{
sessionTokenProvider.PrivacyNoticeVersion = privacyNoticeVersion;
}
EndpointAddress localAddress;
if (initiatorRequirement.TryGetProperty(ServiceModelSecurityTokenRequirement.DuplexClientLocalAddressProperty, out localAddress))
{
sessionTokenProvider.LocalAddress = localAddress;
}
sessionTokenProvider.ChannelParameters = channelParameters;
sessionTokenProvider.WebHeaders = initiatorRequirement.WebHeaders;
return sessionTokenProvider;
}
else
{
AcceleratedTokenProvider acceleratedTokenProvider = new AcceleratedTokenProvider();
acceleratedTokenProvider.IssuerAddress = initiatorRequirement.IssuerAddress;
acceleratedTokenProvider.BootstrapSecurityBindingElement = SecurityUtils.GetIssuerSecurityBindingElement(initiatorRequirement);
acceleratedTokenProvider.CacheServiceTokens = localClientSettings.CacheCookies;
acceleratedTokenProvider.IssuerBindingContext = issuerBindingContext;
acceleratedTokenProvider.KeyEntropyMode = securityBindingElement.KeyEntropyMode;
acceleratedTokenProvider.MaxServiceTokenCachingTime = localClientSettings.MaxCookieCachingTime;
acceleratedTokenProvider.SecurityAlgorithmSuite = initiatorRequirement.SecurityAlgorithmSuite;
acceleratedTokenProvider.ServiceTokenValidityThresholdPercentage = localClientSettings.CookieRenewalThresholdPercentage;
acceleratedTokenProvider.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(initiatorRequirement, this);
acceleratedTokenProvider.TargetAddress = targetAddress;
acceleratedTokenProvider.Via = initiatorRequirement.GetPropertyOrDefault<Uri>(InitiatorServiceModelSecurityTokenRequirement.ViaProperty, null);
return acceleratedTokenProvider;
}
}
private X509SecurityTokenAuthenticator CreateServerX509TokenAuthenticator()
{
return new X509SecurityTokenAuthenticator(ClientCredentials.ServiceCertificate.Authentication.GetCertificateValidator(), false);
}
private X509SecurityTokenAuthenticator CreateServerSslX509TokenAuthenticator()
{
if (ClientCredentials.ServiceCertificate.SslCertificateAuthentication != null)
{
return new X509SecurityTokenAuthenticator(ClientCredentials.ServiceCertificate.SslCertificateAuthentication.GetCertificateValidator(), false);
}
return CreateServerX509TokenAuthenticator();
}
public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
{
if (tokenRequirement == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(tokenRequirement));
}
outOfBandTokenResolver = null;
SecurityTokenAuthenticator result = null;
InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement;
if (initiatorRequirement != null)
{
string tokenType = initiatorRequirement.TokenType;
if (IsIssuedSecurityTokenRequirement(initiatorRequirement))
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : GenericXmlSecurityTokenAuthenticator");
}
else if (tokenType == SecurityTokenTypes.X509Certificate)
{
if (initiatorRequirement.IsOutOfBandToken)
{
// when the client side soap security asks for a token authenticator, its for doing
// identity checks on the out of band server certificate
result = new X509SecurityTokenAuthenticator(X509CertificateValidator.None);
}
else if (initiatorRequirement.PreferSslCertificateAuthenticator)
{
result = CreateServerSslX509TokenAuthenticator();
}
else
{
result = CreateServerX509TokenAuthenticator();
}
}
else if (tokenType == SecurityTokenTypes.Rsa)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : SecurityTokenTypes.Rsa");
}
else if (tokenType == SecurityTokenTypes.Kerberos)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : SecurityTokenTypes.Kerberos");
}
else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation
|| tokenType == ServiceModelSecurityTokenTypes.MutualSslnego
|| tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego
|| tokenType == ServiceModelSecurityTokenTypes.Spnego)
{
throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : GenericXmlSecurityTokenAuthenticator");
}
}
else if ((tokenRequirement is RecipientServiceModelSecurityTokenRequirement) && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate)
{
// uncorrelated duplex case
result = CreateServerX509TokenAuthenticator();
}
if (result == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SecurityTokenManagerCannotCreateAuthenticatorForRequirement, tokenRequirement)));
}
return result;
}
}
internal class KerberosSecurityTokenProviderWrapper : CommunicationObjectSecurityTokenProvider
{
private KerberosSecurityTokenProvider _innerProvider;
public KerberosSecurityTokenProviderWrapper(KerberosSecurityTokenProvider innerProvider)
{
_innerProvider = innerProvider;
}
protected override SecurityToken GetTokenCore(TimeSpan timeout)
{
return new KerberosRequestorSecurityToken(_innerProvider.ServicePrincipalName,
_innerProvider.TokenImpersonationLevel, _innerProvider.NetworkCredential,
SecurityUniqueId.Create().Value);
}
internal Task<SecurityToken> GetTokenAsync(TimeSpan timeout, ChannelBinding channelbinding)
{
return Task.FromResult(GetTokenCore(timeout));
}
internal override Task<SecurityToken> GetTokenCoreInternalAsync(TimeSpan timeout)
{
return GetTokenAsync(timeout, null);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
internal partial class VisualStudioDiagnosticListTable : VisualStudioBaseDiagnosticListTable
{
private class BuildTableDataSource : AbstractTableDataSource<DiagnosticData>
{
private readonly object _key = new object();
private readonly Workspace _workspace;
private readonly ExternalErrorDiagnosticUpdateSource _buildErrorSource;
public BuildTableDataSource(Workspace workspace, ExternalErrorDiagnosticUpdateSource errorSource) :
base(workspace)
{
_workspace = workspace;
_buildErrorSource = errorSource;
ConnectToBuildUpdateSource(errorSource);
}
private void ConnectToBuildUpdateSource(ExternalErrorDiagnosticUpdateSource errorSource)
{
if (errorSource == null)
{
return;
}
SetStableState(errorSource.IsInProgress);
errorSource.BuildStarted += OnBuildStarted;
}
private void OnBuildStarted(object sender, bool started)
{
SetStableState(started);
if (!started)
{
OnDataAddedOrChanged(_key);
}
}
private void SetStableState(bool started)
{
IsStable = !started;
ChangeStableState(IsStable);
}
public override string DisplayName => ServicesVSResources.CSharp_VB_Build_Table_Data_Source;
public override string SourceTypeIdentifier => StandardTableDataSources.ErrorTableDataSource;
public override string Identifier => IdentifierString;
public override object GetItemKey(object data) => data;
protected override object GetOrUpdateAggregationKey(object data)
{
return data;
}
public override AbstractTableEntriesSource<DiagnosticData> CreateTableEntriesSource(object data)
{
return new TableEntriesSource(this, _workspace);
}
public override ImmutableArray<TableItem<DiagnosticData>> Deduplicate(IEnumerable<IList<TableItem<DiagnosticData>>> groupedItems)
{
return groupedItems.MergeDuplicatesOrderedBy(Order);
}
public override ITrackingPoint CreateTrackingPoint(DiagnosticData data, ITextSnapshot snapshot)
{
return snapshot.CreateTrackingPoint(data.DataLocation?.OriginalStartLine ?? 0, data.DataLocation?.OriginalStartColumn ?? 0);
}
public override AbstractTableEntriesSnapshot<DiagnosticData> CreateSnapshot(AbstractTableEntriesSource<DiagnosticData> source, int version, ImmutableArray<TableItem<DiagnosticData>> items, ImmutableArray<ITrackingPoint> trackingPoints)
{
// Build doesn't support tracking point.
return new TableEntriesSnapshot((DiagnosticTableEntriesSource)source, version, items);
}
private static IEnumerable<TableItem<DiagnosticData>> Order(IEnumerable<TableItem<DiagnosticData>> groupedItems)
{
// this should make order of result always deterministic.
return groupedItems.OrderBy(d => d.Primary.ProjectId?.Id ?? Guid.Empty)
.ThenBy(d => d.Primary.DocumentId?.Id ?? Guid.Empty)
.ThenBy(d => d.Primary.DataLocation?.OriginalStartLine ?? 0)
.ThenBy(d => d.Primary.DataLocation?.OriginalStartColumn ?? 0)
.ThenBy(d => d.Primary.Id)
.ThenBy(d => d.Primary.Message)
.ThenBy(d => d.Primary.DataLocation?.OriginalEndLine ?? 0)
.ThenBy(d => d.Primary.DataLocation?.OriginalEndColumn ?? 0);
}
private class TableEntriesSource : DiagnosticTableEntriesSource
{
private readonly BuildTableDataSource _source;
private readonly Workspace _workspace;
public TableEntriesSource(BuildTableDataSource source, Workspace workspace)
{
_source = source;
_workspace = workspace;
}
public override object Key => _source._key;
public override string BuildTool => PredefinedBuildTools.Build;
public override bool SupportSpanTracking => false;
public override DocumentId TrackingDocumentId => Contract.FailWithReturn<DocumentId>("This should never be called");
public override ImmutableArray<TableItem<DiagnosticData>> GetItems()
{
var groupedItems = _source._buildErrorSource
.GetBuildErrors()
.Select(d => new TableItem<DiagnosticData>(d, GenerateDeduplicationKey))
.GroupBy(d => d.DeduplicationKey)
.Select(g => (IList<TableItem<DiagnosticData>>)g)
.ToImmutableArray();
return _source.Deduplicate(groupedItems);
}
public override ImmutableArray<ITrackingPoint> GetTrackingPoints(ImmutableArray<TableItem<DiagnosticData>> items)
{
return ImmutableArray<ITrackingPoint>.Empty;
}
private int GenerateDeduplicationKey(DiagnosticData diagnostic)
{
if (diagnostic.DataLocation == null ||
diagnostic.DataLocation.OriginalFilePath == null)
{
return diagnostic.GetHashCode();
}
return Hash.Combine(diagnostic.DataLocation.OriginalStartColumn,
Hash.Combine(diagnostic.DataLocation.OriginalStartLine,
Hash.Combine(diagnostic.DataLocation.OriginalEndColumn,
Hash.Combine(diagnostic.DataLocation.OriginalEndLine,
Hash.Combine(diagnostic.DataLocation.OriginalFilePath,
Hash.Combine(diagnostic.IsSuppressed,
Hash.Combine(diagnostic.Id.GetHashCode(), diagnostic.Message.GetHashCode())))))));
}
}
private class TableEntriesSnapshot : AbstractTableEntriesSnapshot<DiagnosticData>
{
private readonly DiagnosticTableEntriesSource _source;
public TableEntriesSnapshot(
DiagnosticTableEntriesSource source, int version, ImmutableArray<TableItem<DiagnosticData>> items) :
base(version, items, ImmutableArray<ITrackingPoint>.Empty)
{
_source = source;
}
public override bool TryGetValue(int index, string columnName, out object content)
{
// REVIEW: this method is too-chatty to make async, but otherwise, how one can implement it async?
// also, what is cancellation mechanism?
var item = GetItem(index);
var data = item?.Primary;
if (data == null)
{
content = null;
return false;
}
switch (columnName)
{
case StandardTableKeyNames.ErrorRank:
// build error gets highest rank
content = ValueTypeCache.GetOrCreate(ErrorRank.Lexical);
return content != null;
case StandardTableKeyNames.ErrorSeverity:
content = ValueTypeCache.GetOrCreate(GetErrorCategory(data.Severity));
return content != null;
case StandardTableKeyNames.ErrorCode:
content = data.Id;
return content != null;
case StandardTableKeyNames.ErrorCodeToolTip:
content = GetHelpLinkToolTipText(data);
return content != null;
case StandardTableKeyNames.HelpKeyword:
content = data.Id;
return content != null;
case StandardTableKeyNames.HelpLink:
content = GetHelpLink(data);
return content != null;
case StandardTableKeyNames.ErrorCategory:
content = data.Category;
return content != null;
case StandardTableKeyNames.ErrorSource:
content = ValueTypeCache.GetOrCreate(ErrorSource.Build);
return content != null;
case StandardTableKeyNames.BuildTool:
content = _source.BuildTool;
return content != null;
case StandardTableKeyNames.Text:
content = data.Message;
return content != null;
case StandardTableKeyNames.DocumentName:
content = GetFileName(data.DataLocation?.OriginalFilePath, data.DataLocation?.MappedFilePath);
return content != null;
case StandardTableKeyNames.Line:
content = data.DataLocation?.MappedStartLine ?? 0;
return true;
case StandardTableKeyNames.Column:
content = data.DataLocation?.MappedStartColumn ?? 0;
return true;
case StandardTableKeyNames.ProjectName:
content = item.ProjectName;
return content != null;
case ProjectNames:
content = item.ProjectNames;
return ((string[])content).Length > 0;
case StandardTableKeyNames.ProjectGuid:
content = ValueTypeCache.GetOrCreate(item.ProjectGuid);
return (Guid)content != Guid.Empty;
case ProjectGuids:
content = item.ProjectGuids;
return ((Guid[])content).Length > 0;
case SuppressionStateColumnDefinition.ColumnName:
// Build doesn't report suppressed diagnostics.
Contract.ThrowIfTrue(data.IsSuppressed);
content = ServicesVSResources.Active;
return true;
default:
content = null;
return false;
}
}
public override bool TryNavigateTo(int index, bool previewTab)
{
var item = GetItem(index)?.Primary;
if (item == null)
{
return false;
}
// this item is not navigatable
if (item.DocumentId == null)
{
return false;
}
return TryNavigateTo(item.Workspace, GetProperDocumentId(item),
item.DataLocation?.OriginalStartLine ?? 0, item.DataLocation?.OriginalStartColumn ?? 0, previewTab);
}
private DocumentId GetProperDocumentId(DiagnosticData data)
{
// check whether documentId still exist. it might have changed if project it belong to has reloaded.
var solution = data.Workspace.CurrentSolution;
if (solution.GetDocument(data.DocumentId) != null)
{
return data.DocumentId;
}
// okay, documentId no longer exist in current solution, find it by file path.
if (string.IsNullOrWhiteSpace(data.DataLocation?.OriginalFilePath))
{
// we don't have filepath
return null;
}
var documentIds = solution.GetDocumentIdsWithFilePath(data.DataLocation.OriginalFilePath);
foreach (var id in documentIds)
{
// found right documentId;
if (id.ProjectId == data.ProjectId)
{
return id;
}
}
// okay, there is no right one, take the first one if there is any
return documentIds.FirstOrDefault();
}
protected override bool IsEquivalent(DiagnosticData item1, DiagnosticData item2)
{
// everything same except location
return item1.Id == item2.Id &&
item1.ProjectId == item2.ProjectId &&
item1.DocumentId == item2.DocumentId &&
item1.Category == item2.Category &&
item1.Severity == item2.Severity &&
item1.WarningLevel == item2.WarningLevel &&
item1.Message == item2.Message;
}
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
the Utilities SDK except in compliance with the License, which is provided at the time of installation
or download, or which otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/utilities-1.31
Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
ANY KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
************************************************************************************/
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Text;
public class OVRGearVrControllerTest : MonoBehaviour
{
public class BoolMonitor
{
public delegate bool BoolGenerator();
private string m_name = "";
private BoolGenerator m_generator;
private bool m_prevValue = false;
private bool m_currentValue = false;
private bool m_currentValueRecentlyChanged = false;
private float m_displayTimeout = 0.0f;
private float m_displayTimer = 0.0f;
public BoolMonitor(string name, BoolGenerator generator, float displayTimeout = 0.5f)
{
m_name = name;
m_generator = generator;
m_displayTimeout = displayTimeout;
}
public void Update()
{
m_prevValue = m_currentValue;
m_currentValue = m_generator();
if (m_currentValue != m_prevValue)
{
m_currentValueRecentlyChanged = true;
m_displayTimer = m_displayTimeout;
}
if (m_displayTimer > 0.0f)
{
m_displayTimer -= Time.deltaTime;
if (m_displayTimer <= 0.0f)
{
m_currentValueRecentlyChanged = false;
m_displayTimer = 0.0f;
}
}
}
public void AppendToStringBuilder(ref StringBuilder sb)
{
sb.Append(m_name);
if (m_currentValue && m_currentValueRecentlyChanged)
sb.Append(": *True*\n");
else if (m_currentValue)
sb.Append(": True \n");
else if (!m_currentValue && m_currentValueRecentlyChanged)
sb.Append(": *False*\n");
else if (!m_currentValue)
sb.Append(": False \n");
}
}
public Text uiText;
private List<BoolMonitor> monitors;
private StringBuilder data;
void Start()
{
if (uiText != null)
{
uiText.supportRichText = false;
}
data = new StringBuilder(2048);
monitors = new List<BoolMonitor>()
{
// virtual
new BoolMonitor("WasRecentered", () => OVRInput.GetControllerWasRecentered()),
new BoolMonitor("One", () => OVRInput.Get(OVRInput.Button.One)),
new BoolMonitor("OneDown", () => OVRInput.GetDown(OVRInput.Button.One)),
new BoolMonitor("OneUp", () => OVRInput.GetUp(OVRInput.Button.One)),
new BoolMonitor("One (Touch)", () => OVRInput.Get(OVRInput.Touch.One)),
new BoolMonitor("OneDown (Touch)", () => OVRInput.GetDown(OVRInput.Touch.One)),
new BoolMonitor("OneUp (Touch)", () => OVRInput.GetUp(OVRInput.Touch.One)),
new BoolMonitor("Two", () => OVRInput.Get(OVRInput.Button.Two)),
new BoolMonitor("TwoDown", () => OVRInput.GetDown(OVRInput.Button.Two)),
new BoolMonitor("TwoUp", () => OVRInput.GetUp(OVRInput.Button.Two)),
new BoolMonitor("PrimaryIndexTrigger", () => OVRInput.Get(OVRInput.Button.PrimaryIndexTrigger)),
new BoolMonitor("PrimaryIndexTriggerDown", () => OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger)),
new BoolMonitor("PrimaryIndexTriggerUp", () => OVRInput.GetUp(OVRInput.Button.PrimaryIndexTrigger)),
new BoolMonitor("PrimaryIndexTrigger (Touch)", () => OVRInput.Get(OVRInput.Touch.PrimaryIndexTrigger)),
new BoolMonitor("PrimaryIndexTriggerDown (Touch)", () => OVRInput.GetDown(OVRInput.Touch.PrimaryIndexTrigger)),
new BoolMonitor("PrimaryIndexTriggerUp (Touch)", () => OVRInput.GetUp(OVRInput.Touch.PrimaryIndexTrigger)),
new BoolMonitor("PrimaryHandTrigger", () => OVRInput.Get(OVRInput.Button.PrimaryHandTrigger)),
new BoolMonitor("PrimaryHandTriggerDown", () => OVRInput.GetDown(OVRInput.Button.PrimaryHandTrigger)),
new BoolMonitor("PrimaryHandTriggerUp", () => OVRInput.GetUp(OVRInput.Button.PrimaryHandTrigger)),
new BoolMonitor("Up", () => OVRInput.Get(OVRInput.Button.Up)),
new BoolMonitor("Down", () => OVRInput.Get(OVRInput.Button.Down)),
new BoolMonitor("Left", () => OVRInput.Get(OVRInput.Button.Left)),
new BoolMonitor("Right", () => OVRInput.Get(OVRInput.Button.Right)),
new BoolMonitor("Touchpad (Click)", () => OVRInput.Get(OVRInput.Button.PrimaryTouchpad)),
new BoolMonitor("TouchpadDown (Click)", () => OVRInput.GetDown(OVRInput.Button.PrimaryTouchpad)),
new BoolMonitor("TouchpadUp (Click)", () => OVRInput.GetUp(OVRInput.Button.PrimaryTouchpad)),
new BoolMonitor("Touchpad (Touch)", () => OVRInput.Get(OVRInput.Touch.PrimaryTouchpad)),
new BoolMonitor("TouchpadDown (Touch)", () => OVRInput.GetDown(OVRInput.Touch.PrimaryTouchpad)),
new BoolMonitor("TouchpadUp (Touch)", () => OVRInput.GetUp(OVRInput.Touch.PrimaryTouchpad)),
// raw
new BoolMonitor("Start", () => OVRInput.Get(OVRInput.RawButton.Start)),
new BoolMonitor("StartDown", () => OVRInput.GetDown(OVRInput.RawButton.Start)),
new BoolMonitor("StartUp", () => OVRInput.GetUp(OVRInput.RawButton.Start)),
new BoolMonitor("Back", () => OVRInput.Get(OVRInput.RawButton.Back)),
new BoolMonitor("BackDown", () => OVRInput.GetDown(OVRInput.RawButton.Back)),
new BoolMonitor("BackUp", () => OVRInput.GetUp(OVRInput.RawButton.Back)),
new BoolMonitor("A", () => OVRInput.Get(OVRInput.RawButton.A)),
new BoolMonitor("ADown", () => OVRInput.GetDown(OVRInput.RawButton.A)),
new BoolMonitor("AUp", () => OVRInput.GetUp(OVRInput.RawButton.A)),
};
}
static string prevConnected = "";
static BoolMonitor controllers = new BoolMonitor("Controllers Changed", () => { return OVRInput.GetConnectedControllers().ToString() != prevConnected; });
void Update()
{
OVRInput.Controller activeController = OVRInput.GetActiveController();
data.Length = 0;
byte recenterCount = OVRInput.GetControllerRecenterCount();
data.AppendFormat("RecenterCount: {0}\n", recenterCount);
byte battery = OVRInput.GetControllerBatteryPercentRemaining();
data.AppendFormat("Battery: {0}\n", battery);
float framerate = OVRPlugin.GetAppFramerate();
data.AppendFormat("Framerate: {0:F2}\n", framerate);
string activeControllerName = activeController.ToString();
data.AppendFormat("Active: {0}\n", activeControllerName);
string connectedControllerNames = OVRInput.GetConnectedControllers().ToString();
data.AppendFormat("Connected: {0}\n", connectedControllerNames);
data.AppendFormat("PrevConnected: {0}\n", prevConnected);
controllers.Update();
controllers.AppendToStringBuilder(ref data);
prevConnected = connectedControllerNames;
Quaternion rot = OVRInput.GetLocalControllerRotation(activeController);
data.AppendFormat("Orientation: ({0:F2}, {1:F2}, {2:F2}, {3:F2})\n", rot.x, rot.y, rot.z, rot.w);
Vector3 angVel = OVRInput.GetLocalControllerAngularVelocity(activeController);
data.AppendFormat("AngVel: ({0:F2}, {1:F2}, {2:F2})\n", angVel.x, angVel.y, angVel.z);
Vector3 angAcc = OVRInput.GetLocalControllerAngularAcceleration(activeController);
data.AppendFormat("AngAcc: ({0:F2}, {1:F2}, {2:F2})\n", angAcc.x, angAcc.y, angAcc.z);
Vector3 pos = OVRInput.GetLocalControllerPosition(activeController);
data.AppendFormat("Position: ({0:F2}, {1:F2}, {2:F2})\n", pos.x, pos.y, pos.z);
Vector3 vel = OVRInput.GetLocalControllerVelocity(activeController);
data.AppendFormat("Vel: ({0:F2}, {1:F2}, {2:F2})\n", vel.x, vel.y, vel.z);
Vector3 acc = OVRInput.GetLocalControllerAcceleration(activeController);
data.AppendFormat("Acc: ({0:F2}, {1:F2}, {2:F2})\n", acc.x, acc.y, acc.z);
Vector2 primaryTouchpad = OVRInput.Get(OVRInput.Axis2D.PrimaryTouchpad);
data.AppendFormat("PrimaryTouchpad: ({0:F2}, {1:F2})\n", primaryTouchpad.x, primaryTouchpad.y);
Vector2 secondaryTouchpad = OVRInput.Get(OVRInput.Axis2D.SecondaryTouchpad);
data.AppendFormat("SecondaryTouchpad: ({0:F2}, {1:F2})\n", secondaryTouchpad.x, secondaryTouchpad.y);
float indexTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger);
data.AppendFormat("PrimaryIndexTriggerAxis1D: ({0:F2})\n", indexTrigger);
float handTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger);
data.AppendFormat("PrimaryHandTriggerAxis1D: ({0:F2})\n", handTrigger);
for (int i = 0; i < monitors.Count; i++)
{
monitors[i].Update();
monitors[i].AppendToStringBuilder(ref data);
}
if (uiText != null)
{
uiText.text = data.ToString();
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using QuantConnect.Orders.Fills;
using QuantConnect.Securities;
using static QuantConnect.StringExtensions;
namespace QuantConnect.Orders.Fees
{
/// <summary>
/// Provides the default implementation of <see cref="IFeeModel"/>
/// </summary>
public class InteractiveBrokersFeeModel : FeeModel
{
private readonly decimal _forexCommissionRate;
private readonly decimal _forexMinimumOrderFee;
// option commission function takes number of contracts and the size of the option premium and returns total commission
private readonly Dictionary<string, Func<decimal, decimal, CashAmount>> _optionFee =
new Dictionary<string, Func<decimal, decimal, CashAmount>>();
private readonly Dictionary<string, CashAmount> _futureFee =
// IB fee + exchange fee
new Dictionary<string, CashAmount> { { Market.USA, new CashAmount(0.85m + 1, "USD") } };
/// <summary>
/// Initializes a new instance of the <see cref="ImmediateFillModel"/>
/// </summary>
/// <param name="monthlyForexTradeAmountInUSDollars">Monthly FX dollar volume traded</param>
/// <param name="monthlyOptionsTradeAmountInContracts">Monthly options contracts traded</param>
public InteractiveBrokersFeeModel(decimal monthlyForexTradeAmountInUSDollars = 0, decimal monthlyOptionsTradeAmountInContracts = 0)
{
ProcessForexRateSchedule(monthlyForexTradeAmountInUSDollars, out _forexCommissionRate, out _forexMinimumOrderFee);
Func<decimal, decimal, CashAmount> optionsCommissionFunc;
ProcessOptionsRateSchedule(monthlyOptionsTradeAmountInContracts, out optionsCommissionFunc);
// only USA for now
_optionFee.Add(Market.USA, optionsCommissionFunc);
}
/// <summary>
/// Gets the order fee associated with the specified order. This returns the cost
/// of the transaction in the account currency
/// </summary>
/// <param name="parameters">A <see cref="OrderFeeParameters"/> object
/// containing the security and order</param>
/// <returns>The cost of the order in units of the account currency</returns>
public override OrderFee GetOrderFee(OrderFeeParameters parameters)
{
var order = parameters.Order;
var security = parameters.Security;
// Option exercise for equity options is free of charge
if (order.Type == OrderType.OptionExercise)
{
var optionOrder = (OptionExerciseOrder)order;
// For Futures Options, contracts are charged the standard commission at expiration of the contract.
// Read more here: https://www1.interactivebrokers.com/en/index.php?f=14718#trading-related-fees
if (optionOrder.Symbol.ID.SecurityType == SecurityType.Option)
{
return OrderFee.Zero;
}
}
decimal feeResult;
string feeCurrency;
var market = security.Symbol.ID.Market;
switch (security.Type)
{
case SecurityType.Forex:
// get the total order value in the account currency
var totalOrderValue = order.GetValue(security);
var fee = Math.Abs(_forexCommissionRate*totalOrderValue);
feeResult = Math.Max(_forexMinimumOrderFee, fee);
// IB Forex fees are all in USD
feeCurrency = Currencies.USD;
break;
case SecurityType.Option:
case SecurityType.IndexOption:
Func<decimal, decimal, CashAmount> optionsCommissionFunc;
if (!_optionFee.TryGetValue(market, out optionsCommissionFunc))
{
throw new KeyNotFoundException($"InteractiveBrokersFeeModel(): unexpected option Market {market}");
}
// applying commission function to the order
var optionFee = optionsCommissionFunc(order.AbsoluteQuantity, order.Price);
feeResult = optionFee.Amount;
feeCurrency = optionFee.Currency;
break;
case SecurityType.Future:
case SecurityType.FutureOption:
// The futures options fee model is exactly the same as futures' fees on IB.
if (market == Market.Globex || market == Market.NYMEX
|| market == Market.CBOT || market == Market.ICE
|| market == Market.CBOE || market == Market.COMEX
|| market == Market.CME)
{
// just in case...
market = Market.USA;
}
CashAmount feeRatePerContract;
if (!_futureFee.TryGetValue(market, out feeRatePerContract))
{
throw new KeyNotFoundException($"InteractiveBrokersFeeModel(): unexpected future Market {market}");
}
feeResult = order.AbsoluteQuantity * feeRatePerContract.Amount;
feeCurrency = feeRatePerContract.Currency;
break;
case SecurityType.Equity:
EquityFee equityFee;
switch (market)
{
case Market.USA:
equityFee = new EquityFee("USD", feePerShare: 0.005m, minimumFee: 1, maximumFeeRate: 0.005m);
break;
default:
throw new KeyNotFoundException($"InteractiveBrokersFeeModel(): unexpected equity Market {market}");
}
var tradeValue = Math.Abs(order.GetValue(security));
//Per share fees
var tradeFee = equityFee.FeePerShare * order.AbsoluteQuantity;
//Maximum Per Order: equityFee.MaximumFeeRate
//Minimum per order. $equityFee.MinimumFee
var maximumPerOrder = equityFee.MaximumFeeRate * tradeValue;
if (tradeFee < equityFee.MinimumFee)
{
tradeFee = equityFee.MinimumFee;
}
else if (tradeFee > maximumPerOrder)
{
tradeFee = maximumPerOrder;
}
feeCurrency = equityFee.Currency;
//Always return a positive fee.
feeResult = Math.Abs(tradeFee);
break;
default:
// unsupported security type
throw new ArgumentException(Invariant($"Unsupported security type: {security.Type}"));
}
return new OrderFee(new CashAmount(
feeResult,
feeCurrency));
}
/// <summary>
/// Determines which tier an account falls into based on the monthly trading volume
/// </summary>
private static void ProcessForexRateSchedule(decimal monthlyForexTradeAmountInUSDollars, out decimal commissionRate, out decimal minimumOrderFee)
{
const decimal bp = 0.0001m;
if (monthlyForexTradeAmountInUSDollars <= 1000000000) // 1 billion
{
commissionRate = 0.20m * bp;
minimumOrderFee = 2.00m;
}
else if (monthlyForexTradeAmountInUSDollars <= 2000000000) // 2 billion
{
commissionRate = 0.15m * bp;
minimumOrderFee = 1.50m;
}
else if (monthlyForexTradeAmountInUSDollars <= 5000000000) // 5 billion
{
commissionRate = 0.10m * bp;
minimumOrderFee = 1.25m;
}
else
{
commissionRate = 0.08m * bp;
minimumOrderFee = 1.00m;
}
}
/// <summary>
/// Determines which tier an account falls into based on the monthly trading volume
/// </summary>
private static void ProcessOptionsRateSchedule(decimal monthlyOptionsTradeAmountInContracts, out Func<decimal, decimal, CashAmount> optionsCommissionFunc)
{
if (monthlyOptionsTradeAmountInContracts <= 10000)
{
optionsCommissionFunc = (orderSize, premium) =>
{
var commissionRate = premium >= 0.1m ?
0.7m :
(0.05m <= premium && premium < 0.1m ? 0.5m : 0.25m);
return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD);
};
}
else if (monthlyOptionsTradeAmountInContracts <= 50000)
{
optionsCommissionFunc = (orderSize, premium) =>
{
var commissionRate = premium >= 0.05m ? 0.5m : 0.25m;
return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD);
};
}
else if (monthlyOptionsTradeAmountInContracts <= 100000)
{
optionsCommissionFunc = (orderSize, premium) =>
{
var commissionRate = 0.25m;
return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD);
};
}
else
{
optionsCommissionFunc = (orderSize, premium) =>
{
var commissionRate = 0.15m;
return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD);
};
}
}
/// <summary>
/// Helper class to handle IB Equity fees
/// </summary>
private class EquityFee
{
public string Currency { get; }
public decimal FeePerShare { get; }
public decimal MinimumFee { get; }
public decimal MaximumFeeRate { get; }
public EquityFee(string currency,
decimal feePerShare,
decimal minimumFee,
decimal maximumFeeRate)
{
Currency = currency;
FeePerShare = feePerShare;
MinimumFee = minimumFee;
MaximumFeeRate = maximumFeeRate;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Extended.Net4;
using HappyMapper.AutoMapper.ConfigurationAPI.Execution;
namespace HappyMapper.AutoMapper.ConfigurationAPI.Configuration
{
public class MappingExpression : MappingExpression<object, object>, IMappingExpression
{
public MappingExpression(TypePair types, MemberList memberList) : base(memberList, types.SourceType, types.DestinationType)
{
}
public new IMappingExpression ReverseMap() => (IMappingExpression) base.ReverseMap();
public IMappingExpression Substitute(Func<object, object> substituteFunc)
=> (IMappingExpression) base.Substitute(substituteFunc);
public new IMappingExpression ConstructUsingServiceLocator()
=> (IMappingExpression)base.ConstructUsingServiceLocator();
public void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions)
=> base.ForAllMembers(opts => memberOptions((IMemberConfigurationExpression)opts));
void IMappingExpression.ConvertUsing<TTypeConverter>()
=> ConvertUsing(typeof(TTypeConverter));
public void ConvertUsing(Type typeConverterType)
=> TypeMapActions.Add(tm => tm.TypeConverterType = typeConverterType);
public void ForAllOtherMembers(Action<IMemberConfigurationExpression> memberOptions)
=> base.ForAllOtherMembers(o => memberOptions((IMemberConfigurationExpression)o));
public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions)
=> (IMappingExpression)base.ForMember(name, c => memberOptions((IMemberConfigurationExpression)c));
public new IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions)
=> (IMappingExpression)base.ForSourceMember(sourceMemberName, memberOptions);
public new IMappingExpression Include(Type otherSourceType, Type otherDestinationType)
=> (IMappingExpression)base.Include(otherSourceType, otherDestinationType);
public new IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter()
=> (IMappingExpression)base.IgnoreAllPropertiesWithAnInaccessibleSetter();
public new IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter()
=> (IMappingExpression)base.IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
public new IMappingExpression IncludeBase(Type sourceBase, Type destinationBase)
=> (IMappingExpression)base.IncludeBase(sourceBase, destinationBase);
public new IMappingExpression BeforeMap(Action<object, object> beforeFunction)
=> (IMappingExpression)base.BeforeMap(beforeFunction);
public new IMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>
=> (IMappingExpression)base.BeforeMap<TMappingAction>();
public new IMappingExpression AfterMap(Action<object, object> afterFunction)
=> (IMappingExpression)base.AfterMap(afterFunction);
public new IMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>
=> (IMappingExpression)base.AfterMap<TMappingAction>();
public new IMappingExpression ConstructUsing(Func<object, object> ctor)
=> (IMappingExpression)base.ConstructUsing(ctor);
public new IMappingExpression ConstructUsing(Func<object, ResolutionContext, object> ctor)
=> (IMappingExpression)base.ConstructUsing(ctor);
public IMappingExpression ConstructProjectionUsing(LambdaExpression ctor)
{
TypeMapActions.Add(tm => tm.ConstructExpression = ctor);
return this;
}
public new IMappingExpression MaxDepth(int depth)
=> (IMappingExpression)base.MaxDepth(depth);
public new IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions)
=> (IMappingExpression)base.ForCtorParam(ctorParamName, paramOptions);
public new IMappingExpression PreserveReferences() => (IMappingExpression)base.PreserveReferences();
protected override IMemberConfiguration CreateMemberConfigurationExpression<TMember>(MemberInfo member, Type sourceType)
=> new MemberConfigurationExpression(member, sourceType);
protected override MappingExpression<object, object> CreateReverseMapExpression()
=> new MappingExpression(new TypePair(DestinationType, SourceType), MemberList.Source);
internal class MemberConfigurationExpression : MemberConfigurationExpression<object, object, object>, IMemberConfigurationExpression
{
public MemberConfigurationExpression(MemberInfo destinationMember, Type sourceType)
: base(destinationMember, sourceType)
{
}
public void ResolveUsing(Type valueResolverType)
{
var config = new ValueResolverConfiguration(valueResolverType);
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing(Type valueResolverType, string memberName)
{
var config = new ValueResolverConfiguration(valueResolverType)
{
SourceMemberName = memberName
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing<TSource, TDestination, TSourceMember, TDestMember>(IMemberValueResolver<TSource, TDestination, TSourceMember, TDestMember> resolver, string memberName)
{
var config = new ValueResolverConfiguration(resolver)
{
SourceMemberName = memberName
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
}
}
public class MappingExpression<TSource, TDestination> : IMappingExpression<TSource, TDestination>, ITypeMapConfiguration
{
private readonly List<IMemberConfiguration> _memberConfigurations = new List<IMemberConfiguration>();
private readonly List<SourceMappingExpression> _sourceMemberConfigurations = new List<SourceMappingExpression>();
private readonly List<CtorParamConfigurationExpression<TSource>> _ctorParamConfigurations = new List<CtorParamConfigurationExpression<TSource>>();
private MappingExpression<TDestination, TSource> _reverseMap;
private Action<IMemberConfigurationExpression<TSource, TDestination, object>> _allMemberOptions;
private Func<MemberInfo, bool> _memberFilter;
public MappingExpression(MemberList memberList)
: this(memberList, typeof(TSource), typeof(TDestination))
{
}
public MappingExpression(MemberList memberList, Type sourceType, Type destinationType)
{
if (!UnsupportedTypeBlocker.IsValid(sourceType)) throw UnsupportedTypeBlocker.CreateException(sourceType);
if (!UnsupportedTypeBlocker.IsValid(destinationType)) throw UnsupportedTypeBlocker.CreateException(destinationType);
MemberList = memberList;
Types = new TypePair(sourceType, destinationType);
IsOpenGeneric = sourceType.IsGenericTypeDefinition() || destinationType.IsGenericTypeDefinition();
}
public MemberList MemberList { get; }
public TypePair Types { get; }
public Type SourceType => Types.SourceType;
public Type DestinationType => Types.DestinationType;
public bool IsOpenGeneric { get; }
public ITypeMapConfiguration ReverseTypeMap => _reverseMap;
protected List<Action<TypeMap>> TypeMapActions { get; } = new List<Action<TypeMap>>();
public IMappingExpression<TSource, TDestination> PreserveReferences()
{
TypeMapActions.Add(tm => tm.PreserveReferences = true);
return this;
}
protected virtual IMemberConfiguration CreateMemberConfigurationExpression<TMember>(MemberInfo member, Type sourceType)
{
return new MemberConfigurationExpression<TSource, TDestination, TMember>(member, sourceType);
}
public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => beforeFunction(src, dest);
tm.AddBeforeMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => afterFunction(src, dest);
tm.AddAfterMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> ForMember<TMember>(Expression<Func<TDestination, TMember>> destinationMember,
Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions)
{
var memberInfo = ReflectionHelper.FindProperty(destinationMember);
return ForDestinationMember(memberInfo, memberOptions);
}
#region Unsupported
protected virtual MappingExpression<TDestination, TSource> CreateReverseMapExpression()
{
return new MappingExpression<TDestination, TSource>(MemberList.None, DestinationType, SourceType);
}
public IMappingExpression<TSource, TDestination> ForMember(string name,
Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
var member = DestinationType.GetFieldOrProperty(name);
return ForDestinationMember(member, memberOptions);
}
public void ForAllOtherMembers(
Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
_allMemberOptions = memberOptions;
_memberFilter = m => _memberConfigurations.All(c => !Equals(c.DestinationMember, m));
}
public void ForAllMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
_allMemberOptions = memberOptions;
_memberFilter = _ => true;
}
public IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter()
{
foreach (var property in DestinationType.PropertiesWithAnInaccessibleSetter())
{
ForDestinationMember<object>(property, options => options.Ignore());
}
return this;
}
public IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter()
{
foreach (var property in SourceType.PropertiesWithAnInaccessibleSetter())
{
ForSourceMember(property.Name, options => options.Ignore());
}
return this;
}
public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>()
where TOtherSource : TSource
where TOtherDestination : TDestination
{
return Include(typeof (TOtherSource), typeof (TOtherDestination));
}
public IMappingExpression<TSource, TDestination> Include(Type otherSourceType, Type otherDestinationType)
{
TypeMapActions.Add(tm => tm.IncludeDerivedTypes(otherSourceType, otherDestinationType));
return this;
}
public IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>()
{
return IncludeBase(typeof (TSourceBase), typeof (TDestinationBase));
}
public IMappingExpression<TSource, TDestination> IncludeBase(Type sourceBase, Type destinationBase)
{
TypeMapActions.Add(tm => tm.IncludeBaseTypes(sourceBase, destinationBase));
return this;
}
public void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression)
{
TypeMapActions.Add(tm => tm.CustomProjection = projectionExpression);
}
public IMappingExpression<TSource, TDestination> MaxDepth(int depth)
{
TypeMapActions.Add(tm => tm.MaxDepth = depth);
return PreserveReferences();
}
public IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator()
{
TypeMapActions.Add(tm => tm.ConstructDestinationUsingServiceLocator = true);
return this;
}
public IMappingExpression<TDestination, TSource> ReverseMap()
{
var mappingExpression = CreateReverseMapExpression();
_reverseMap = mappingExpression;
return mappingExpression;
}
public IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember,
Action<ISourceMemberConfigurationExpression> memberOptions)
{
var memberInfo = ReflectionHelper.FindProperty(sourceMember);
var srcConfig = new SourceMappingExpression(memberInfo);
memberOptions(srcConfig);
_sourceMemberConfigurations.Add(srcConfig);
return this;
}
public IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName,
Action<ISourceMemberConfigurationExpression> memberOptions)
{
var memberInfo = SourceType.GetMember(sourceMemberName).First();
var srcConfig = new SourceMappingExpression(memberInfo);
memberOptions(srcConfig);
_sourceMemberConfigurations.Add(srcConfig);
return this;
}
public IMappingExpression<TSource, TDestination> Substitute<TSubstitute>(
Func<TSource, TSubstitute> substituteFunc)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TSubstitute>> expr =
(src, dest, ctxt) => substituteFunc(src);
tm.Substitution = expr;
});
return this;
}
public void ConvertUsing(Func<TSource, TDestination> mappingFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr =
(src, dest, ctxt) => mappingFunction(src);
tm.CustomMapper = expr;
});
}
public void ConvertUsing(Func<TSource, TDestination, TDestination> mappingFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr =
(src, dest, ctxt) => mappingFunction(src, dest);
tm.CustomMapper = expr;
});
}
public void ConvertUsing(Func<TSource, TDestination, ResolutionContext, TDestination> mappingFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr =
(src, dest, ctxt) => mappingFunction(src, dest, ctxt);
tm.CustomMapper = expr;
});
}
public void ConvertUsing(ITypeConverter<TSource, TDestination> converter)
{
ConvertUsing(converter.Convert);
}
public void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>
{
TypeMapActions.Add(tm => tm.TypeConverterType = typeof (TTypeConverter));
}
public IMappingExpression<TSource, TDestination> BeforeMap(
Action<TSource, TDestination, ResolutionContext> beforeFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => beforeFunction(src, dest, ctxt);
tm.AddBeforeMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>()
where TMappingAction : IMappingAction<TSource, TDestination>
{
Action<TSource, TDestination, ResolutionContext> beforeFunction = (src, dest, ctxt) =>
((TMappingAction) ctxt.Options.ServiceCtor(typeof (TMappingAction))).Process(src, dest);
return BeforeMap(beforeFunction);
}
public IMappingExpression<TSource, TDestination> AfterMap(
Action<TSource, TDestination, ResolutionContext> afterFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => afterFunction(src, dest, ctxt);
tm.AddAfterMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>()
where TMappingAction : IMappingAction<TSource, TDestination>
{
Action<TSource, TDestination, ResolutionContext> afterFunction = (src, dest, ctxt)
=> ((TMappingAction) ctxt.Options.ServiceCtor(typeof (TMappingAction))).Process(src, dest);
return AfterMap(afterFunction);
}
public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, ResolutionContext, TDestination>> expr = (src, ctxt) => ctor(src);
tm.DestinationCtor = expr;
});
return this;
}
public IMappingExpression<TSource, TDestination> ConstructUsing(
Func<TSource, ResolutionContext, TDestination> ctor)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, ResolutionContext, TDestination>> expr = (src, ctxt) => ctor(src, ctxt);
tm.DestinationCtor = expr;
});
return this;
}
public IMappingExpression<TSource, TDestination> ConstructProjectionUsing(
Expression<Func<TSource, TDestination>> ctor)
{
TypeMapActions.Add(tm =>
{
tm.ConstructExpression = ctor;
var ctxtParam = Expression.Parameter(typeof (ResolutionContext), "ctxt");
var srcParam = Expression.Parameter(typeof (TSource), "src");
var body = ctor.ReplaceParameters(srcParam);
tm.DestinationCtor = Expression.Lambda(body, srcParam, ctxtParam);
});
return this;
}
private IMappingExpression<TSource, TDestination> ForDestinationMember<TMember>(MemberInfo destinationProperty,
Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions)
{
var expression =
(MemberConfigurationExpression<TSource, TDestination, TMember>)
CreateMemberConfigurationExpression<TMember>(destinationProperty, SourceType);
_memberConfigurations.Add(expression);
memberOptions(expression);
return this;
}
public void As<T>()
{
As(typeof (T));
}
public void As(Type typeOverride) => TypeMapActions.Add(tm => tm.DestinationTypeOverride = typeOverride);
public IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName,
Action<ICtorParamConfigurationExpression<TSource>> paramOptions)
{
var ctorParamExpression = new CtorParamConfigurationExpression<TSource>(ctorParamName);
paramOptions(ctorParamExpression);
_ctorParamConfigurations.Add(ctorParamExpression);
return this;
}
public IMappingExpression<TSource, TDestination> DisableCtorValidation()
{
TypeMapActions.Add(tm =>
{
tm.DisableConstructorValidation = true;
});
return this;
}
#endregion
public void Configure(IProfileConfiguration profile, TypeMap typeMap)
{
typeMap.DelegateTypeSingleTyped = typeof(Func<TSource, TDestination, TDestination>);
typeMap.DelegateTypeSingleUntyped = typeof(Func<object, TDestination>);
foreach (var destProperty in typeMap.DestinationTypeDetails.PublicWriteAccessors)
{
var attrs = destProperty.GetCustomAttributes(true);
if (attrs.Any(x => x is IgnoreMapAttribute))
{
ForMember(destProperty.Name, y => y.Ignore());
_reverseMap?.ForMember(destProperty.Name, opt => opt.Ignore());
}
if (profile.GlobalIgnores.Contains(destProperty.Name) && !_memberConfigurations.Any(m=>m.DestinationMember == destProperty))
{
ForMember(destProperty.Name, y => y.Ignore());
}
}
if (_allMemberOptions != null)
{
foreach (var accessor in typeMap.DestinationTypeDetails.PublicReadAccessors.Where(_memberFilter))
{
ForDestinationMember(accessor, _allMemberOptions);
}
}
foreach (var action in TypeMapActions)
{
action(typeMap);
}
foreach (var memberConfig in _memberConfigurations)
{
memberConfig.Configure(typeMap);
}
foreach (var memberConfig in _sourceMemberConfigurations)
{
memberConfig.Configure(typeMap);
}
foreach (var paramConfig in _ctorParamConfigurations)
{
paramConfig.Configure(typeMap);
}
if (_reverseMap != null)
{
foreach (var destProperty in typeMap.GetPropertyMaps().Where(pm => pm.Ignored))
{
_reverseMap.ForSourceMember(destProperty.DestMember.Name, opt => opt.Ignore());
}
foreach (var includedDerivedType in typeMap.IncludedDerivedTypes)
{
_reverseMap.Include(includedDerivedType.DestinationType, includedDerivedType.SourceType);
}
}
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using BerkeleyDB.Internal;
namespace BerkeleyDB {
/// <summary>
/// A class representing a BTreeDatabase. The Btree format is a
/// representation of a sorted, balanced tree structure.
/// </summary>
public class BTreeDatabase : Database {
private BTreeCompressDelegate compressHandler;
private BTreeDecompressDelegate decompressHandler;
private EntryComparisonDelegate compareHandler, prefixCompareHandler;
private EntryComparisonDelegate dupCompareHandler;
private BDB_CompareDelegate doCompareRef;
private BDB_CompareDelegate doPrefixCompareRef;
private BDB_CompareDelegate doDupCompareRef;
private BDB_CompressDelegate doCompressRef;
private BDB_DecompressDelegate doDecompressRef;
#region Constructors
private BTreeDatabase(DatabaseEnvironment env, uint flags)
: base(env, flags) { }
internal BTreeDatabase(BaseDatabase clone) : base(clone) { }
private void Config(BTreeDatabaseConfig cfg) {
base.Config(cfg);
/*
* Database.Config calls set_flags, but that doesn't get the BTree
* specific flags. No harm in calling it again.
*/
db.set_flags(cfg.flags);
if (cfg.BTreeCompare != null)
Compare = cfg.BTreeCompare;
if (cfg.BTreePrefixCompare != null)
PrefixCompare = cfg.BTreePrefixCompare;
// The duplicate comparison function cannot change.
if (cfg.DuplicateCompare != null)
DupCompare = cfg.DuplicateCompare;
if (cfg.minkeysIsSet)
db.set_bt_minkey(cfg.MinKeysPerPage);
if (cfg.compressionIsSet) {
Compress = cfg.Compress;
Decompress = cfg.Decompress;
if (Compress == null)
doCompressRef = null;
else
doCompressRef = new BDB_CompressDelegate(doCompress);
if (Decompress == null)
doDecompressRef = null;
else
doDecompressRef = new BDB_DecompressDelegate(doDecompress);
db.set_bt_compress(doCompressRef, doDecompressRef);
}
}
/// <summary>
/// Instantiate a new BTreeDatabase object and open the database
/// represented by <paramref name="Filename"/>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation
/// will be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <returns>A new, open database object</returns>
public static BTreeDatabase Open(
string Filename, BTreeDatabaseConfig cfg) {
return Open(Filename, null, cfg, null);
}
/// <summary>
/// Instantiate a new BTreeDatabase object and open the database
/// represented by <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/>.
/// </summary>
/// <remarks>
/// <para>
/// If both <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/> are null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe. If
/// <paramref name="Filename"/> is null and
/// <paramref name="DatabaseName"/> is non-null, the database can be
/// opened by other threads of control and will be replicated to client
/// sites in any replication group.
/// </para>
/// <para>
/// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation
/// will be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="DatabaseName">
/// This parameter allows applications to have multiple databases in a
/// single file. Although no DatabaseName needs to be specified, it is
/// an error to attempt to open a second database in a file that was not
/// initially created using a database name.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <returns>A new, open database object</returns>
public static BTreeDatabase Open(
string Filename, string DatabaseName, BTreeDatabaseConfig cfg) {
return Open(Filename, DatabaseName, cfg, null);
}
/// <summary>
/// Instantiate a new BTreeDatabase object and open the database
/// represented by <paramref name="Filename"/>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but
/// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will
/// be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open. Also note that the
/// transaction must be committed before the object is closed.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>A new, open database object</returns>
public static BTreeDatabase Open(
string Filename, BTreeDatabaseConfig cfg, Transaction txn) {
return Open(Filename, null, cfg, txn);
}
/// <summary>
/// Instantiate a new BTreeDatabase object and open the database
/// represented by <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/>.
/// </summary>
/// <remarks>
/// <para>
/// If both <paramref name="Filename"/> and
/// <paramref name="DatabaseName"/> are null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe. If
/// <paramref name="Filename"/> is null and
/// <paramref name="DatabaseName"/> is non-null, the database can be
/// opened by other threads of control and will be replicated to client
/// sites in any replication group.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but
/// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will
/// be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open. Also note that the
/// transaction must be committed before the object is closed.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="DatabaseName">
/// This parameter allows applications to have multiple databases in a
/// single file. Although no DatabaseName needs to be specified, it is
/// an error to attempt to open a second database in a file that was not
/// initially created using a database name.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>A new, open database object</returns>
public static BTreeDatabase Open(string Filename,
string DatabaseName, BTreeDatabaseConfig cfg, Transaction txn) {
BTreeDatabase ret = new BTreeDatabase(cfg.Env, 0);
ret.Config(cfg);
ret.db.open(Transaction.getDB_TXN(txn),
Filename, DatabaseName, DBTYPE.DB_BTREE, cfg.openFlags, 0);
ret.isOpen = true;
return ret;
}
#endregion Constructors
#region Callbacks
private static int doCompare(IntPtr dbp, IntPtr dbtp1, IntPtr dbtp2) {
DB db = new DB(dbp, false);
DBT dbt1 = new DBT(dbtp1, false);
DBT dbt2 = new DBT(dbtp2, false);
BTreeDatabase btdb = (BTreeDatabase)(db.api_internal);
return btdb.Compare(
DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2));
}
private static int doCompress(IntPtr dbp, IntPtr prevKeyp,
IntPtr prevDatap, IntPtr keyp, IntPtr datap, IntPtr destp) {
DB db = new DB(dbp, false);
DatabaseEntry prevKey =
DatabaseEntry.fromDBT(new DBT(prevKeyp, false));
DatabaseEntry prevData =
DatabaseEntry.fromDBT(new DBT(prevDatap, false));
DatabaseEntry key = DatabaseEntry.fromDBT(new DBT(keyp, false));
DatabaseEntry data = DatabaseEntry.fromDBT(new DBT(datap, false));
DBT dest = new DBT(destp, false);
BTreeDatabase btdb = (BTreeDatabase)(db.api_internal);
byte[] arr = new byte[(int)dest.ulen];
int len;
try {
if (btdb.Compress(prevKey, prevData, key, data, ref arr, out len)) {
Marshal.Copy(arr, 0, dest.dataPtr, len);
dest.size = (uint)len;
return 0;
} else {
return DbConstants.DB_BUFFER_SMALL;
}
} catch (Exception) {
return -1;
}
}
private static int doDecompress(IntPtr dbp, IntPtr prevKeyp,
IntPtr prevDatap, IntPtr cmpp, IntPtr destKeyp, IntPtr destDatap) {
DB db = new DB(dbp, false);
DatabaseEntry prevKey =
DatabaseEntry.fromDBT(new DBT(prevKeyp, false));
DatabaseEntry prevData =
DatabaseEntry.fromDBT(new DBT(prevDatap, false));
DBT compressed = new DBT(cmpp, false);
DBT destKey = new DBT(destKeyp, false);
DBT destData = new DBT(destDatap, false);
BTreeDatabase btdb = (BTreeDatabase)(db.api_internal);
uint size;
try {
KeyValuePair<DatabaseEntry, DatabaseEntry> kvp = btdb.Decompress(prevKey, prevData, compressed.data, out size);
int keylen = kvp.Key.Data.Length;
int datalen = kvp.Value.Data.Length;
destKey.size = (uint)keylen;
destData.size = (uint)datalen;
if (keylen > destKey.ulen ||
datalen > destData.ulen)
return DbConstants.DB_BUFFER_SMALL;
Marshal.Copy(kvp.Key.Data, 0, destKey.dataPtr, keylen);
Marshal.Copy(kvp.Value.Data, 0, destData.dataPtr, datalen);
compressed.size = size;
return 0;
} catch (Exception) {
return -1;
}
}
private static int doDupCompare(
IntPtr dbp, IntPtr dbt1p, IntPtr dbt2p) {
DB db = new DB(dbp, false);
DBT dbt1 = new DBT(dbt1p, false);
DBT dbt2 = new DBT(dbt2p, false);
BTreeDatabase btdb = (BTreeDatabase)(db.api_internal);
return btdb.DupCompare(
DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2));
}
private static int doPrefixCompare(
IntPtr dbp, IntPtr dbtp1, IntPtr dbtp2) {
DB db = new DB(dbp, false);
DBT dbt1 = new DBT(dbtp1, false);
DBT dbt2 = new DBT(dbtp2, false);
BTreeDatabase btdb = (BTreeDatabase)(db.api_internal);
return btdb.PrefixCompare(
DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2));
}
#endregion Callbacks
#region Properties
// Sorted alpha by property name
/// <summary>
/// The Btree key comparison function. The comparison function is called
/// whenever it is necessary to compare a key specified by the
/// application with a key currently stored in the tree.
/// </summary>
public EntryComparisonDelegate Compare {
get { return compareHandler; }
private set {
if (value == null)
db.set_bt_compare(null);
else if (compareHandler == null) {
if (doCompareRef == null)
doCompareRef = new BDB_CompareDelegate(doCompare);
db.set_bt_compare(doCompareRef);
}
compareHandler = value;
}
}
/// <summary>
/// The compression function used to store key/data pairs in the
/// database.
/// </summary>
public BTreeCompressDelegate Compress {
get { return compressHandler; }
private set { compressHandler = value; }
}
/// <summary>
/// The decompression function used to retrieve key/data pairs from the
/// database.
/// </summary>
public BTreeDecompressDelegate Decompress {
get { return decompressHandler; }
private set { decompressHandler = value; }
}
/// <summary>
/// The duplicate data item comparison function.
/// </summary>
public EntryComparisonDelegate DupCompare {
get { return dupCompareHandler; }
private set {
/* Cannot be called after open. */
if (value == null)
db.set_dup_compare(null);
else if (dupCompareHandler == null) {
if (doDupCompareRef == null)
doDupCompareRef = new BDB_CompareDelegate(doDupCompare);
db.set_dup_compare(doDupCompareRef);
}
dupCompareHandler = value;
}
}
/// <summary>
/// Whether the insertion of duplicate data items in the database is
/// permitted, and whether duplicates items are sorted.
/// </summary>
public DuplicatesPolicy Duplicates {
get {
uint flags = 0;
db.get_flags(ref flags);
if ((flags & DbConstants.DB_DUPSORT) != 0)
return DuplicatesPolicy.SORTED;
else if ((flags & DbConstants.DB_DUP) != 0)
return DuplicatesPolicy.UNSORTED;
else
return DuplicatesPolicy.NONE;
}
}
/// <summary>
/// The minimum number of key/data pairs intended to be stored on any
/// single Btree leaf page.
/// </summary>
public uint MinKeysPerPage {
get {
uint ret = 0;
db.get_bt_minkey(ref ret);
return ret;
}
}
/// <summary>
/// The Btree prefix function. The prefix function is used to determine
/// the amount by which keys stored on the Btree internal pages can be
/// safely truncated without losing their uniqueness.
/// </summary>
public EntryComparisonDelegate PrefixCompare {
get { return prefixCompareHandler; }
private set {
if (value == null)
db.set_bt_prefix(null);
else if (prefixCompareHandler == null) {
if (doPrefixCompareRef == null)
doPrefixCompareRef =
new BDB_CompareDelegate(doPrefixCompare);
db.set_bt_prefix(doPrefixCompareRef);
}
prefixCompareHandler = value;
}
}
/// <summary>
/// If true, this object supports retrieval from the Btree using record
/// numbers.
/// </summary>
public bool RecordNumbers {
get {
uint flags = 0;
db.get_flags(ref flags);
return (flags & DbConstants.DB_RECNUM) != 0;
}
}
/// <summary>
/// If false, empty pages will not be coalesced into higher-level pages.
/// </summary>
public bool ReverseSplit {
get {
uint flags = 0;
db.get_flags(ref flags);
return (flags & DbConstants.DB_REVSPLITOFF) == 0;
}
}
#endregion Properties
#region Methods
// Sorted alpha by method name
/// <summary>
/// Compact the database, and optionally return unused database pages to
/// the underlying filesystem.
/// </summary>
/// <remarks>
/// If the operation occurs in a transactional database, the operation
/// will be implicitly transaction protected using multiple
/// transactions. These transactions will be periodically committed to
/// avoid locking large sections of the tree. Any deadlocks encountered
/// cause the compaction operation to be retried from the point of the
/// last transaction commit.
/// </remarks>
/// <param name="cdata">Compact configuration parameters</param>
/// <returns>Compact operation statistics</returns>
public CompactData Compact(CompactConfig cdata) {
return Compact(cdata, null);
}
/// <summary>
/// Compact the database, and optionally return unused database pages to
/// the underlying filesystem.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="txn"/> is non-null, then the operation is
/// performed using that transaction. In this event, large sections of
/// the tree may be locked during the course of the transaction.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but the operation occurs in a
/// transactional database, the operation will be implicitly transaction
/// protected using multiple transactions. These transactions will be
/// periodically committed to avoid locking large sections of the tree.
/// Any deadlocks encountered cause the compaction operation to be
/// retried from the point of the last transaction commit.
/// </para>
/// </remarks>
/// <param name="cdata">Compact configuration parameters</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>Compact operation statistics</returns>
public CompactData Compact(CompactConfig cdata, Transaction txn) {
DatabaseEntry end = null;
if (cdata.returnEnd)
end = new DatabaseEntry();
db.compact(Transaction.getDB_TXN(txn), cdata.start, cdata.stop,
CompactConfig.getDB_COMPACT(cdata), cdata.flags, end);
return new CompactData(CompactConfig.getDB_COMPACT(cdata), end);
}
/// <summary>
/// Create a database cursor.
/// </summary>
/// <returns>A newly created cursor</returns>
public new BTreeCursor Cursor() {
return Cursor(new CursorConfig(), null);
}
/// <summary>
/// Create a database cursor with the given configuration.
/// </summary>
/// <param name="cfg">
/// The configuration properties for the cursor.
/// </param>
/// <returns>A newly created cursor</returns>
public new BTreeCursor Cursor(CursorConfig cfg) {
return Cursor(cfg, null);
}
/// <summary>
/// Create a transactionally protected database cursor.
/// </summary>
/// <param name="txn">
/// The transaction context in which the cursor may be used.
/// </param>
/// <returns>A newly created cursor</returns>
public new BTreeCursor Cursor(Transaction txn) {
return Cursor(new CursorConfig(), txn);
}
/// <summary>
/// Create a transactionally protected database cursor with the given
/// configuration.
/// </summary>
/// <param name="cfg">
/// The configuration properties for the cursor.
/// </param>
/// <param name="txn">
/// The transaction context in which the cursor may be used.
/// </param>
/// <returns>A newly created cursor</returns>
public new BTreeCursor Cursor(CursorConfig cfg, Transaction txn) {
return new BTreeCursor(
db.cursor(Transaction.getDB_TXN(txn), cfg.flags), Pagesize);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public BTreeStats FastStats() {
return Stats(null, true, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public BTreeStats FastStats(Transaction txn) {
return Stats(txn, true, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <overloads>
/// <para>
/// Among other things, this method makes it possible for applications
/// to request key and record counts without incurring the performance
/// penalty of traversing the entire database.
/// </para>
/// <para>
/// The statistical information is described by the
/// <see cref="BTreeStats"/>, <see cref="HashStats"/>,
/// <see cref="QueueStats"/>, and <see cref="RecnoStats"/> classes.
/// </para>
/// </overloads>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="isoDegree">
/// The level of isolation for database reads.
/// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for
/// databases which did not specify
/// <see cref="DatabaseConfig.ReadUncommitted"/>.
/// </param>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public BTreeStats FastStats(Transaction txn, Isolation isoDegree) {
return Stats(txn, true, isoDegree);
}
/// <summary>
/// Retrieve a specific numbered key/data pair from the database.
/// </summary>
/// <param name="recno">
/// The record number of the record to be retrieved.
/// </param>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key
/// parameter is <paramref name="key"/> and whose Value parameter is the
/// retrieved data.
/// </returns>
public KeyValuePair<DatabaseEntry, DatabaseEntry> Get(uint recno) {
return Get(recno, null, null);
}
/// <summary>
/// Retrieve a specific numbered key/data pair from the database.
/// </summary>
/// <param name="recno">
/// The record number of the record to be retrieved.
/// </param>
/// <param name="txn">
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key
/// parameter is <paramref name="key"/> and whose Value parameter is the
/// retrieved data.
/// </returns>
public KeyValuePair<DatabaseEntry, DatabaseEntry> Get(
uint recno, Transaction txn) {
return Get(recno, txn, null);
}
/// <summary>
/// Retrieve a specific numbered key/data pair from the database.
/// </summary>
/// <param name="recno">
/// The record number of the record to be retrieved.
/// </param>
/// <param name="txn">
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="info">The locking behavior to use.</param>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key
/// parameter is <paramref name="recno"/> and whose Value parameter is
/// the retrieved data.
/// </returns>
public KeyValuePair<DatabaseEntry, DatabaseEntry> Get(
uint recno, Transaction txn, LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
key.Data = BitConverter.GetBytes(recno);
return Get(key, null, txn, info, DbConstants.DB_SET_RECNO);
}
/// <summary>
/// Retrieve a specific numbered key and all duplicate data items from
/// the database.
/// </summary>
/// <param name="recno">
/// The record number of the record to be retrieved.
/// </param>
/// <exception cref="NotFoundException">
/// A NotFoundException is thrown if <paramref name="recno"/> is not in
/// the database.
/// </exception>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key parameter is
/// <paramref name="recno"/> and whose Value parameter is the retrieved
/// data items.
/// </returns>
public KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> GetMultiple(
uint recno) {
return GetMultiple(recno, (int)Pagesize, null, null);
}
/// <summary>
/// Retrieve a specific numbered key and all duplicate data items from
/// the database.
/// </summary>
/// <param name="recno">
/// The record number of the record to be retrieved.
/// </param>
/// <param name="BufferSize">
/// The initial size of the buffer to fill with duplicate data items. If
/// the buffer is not large enough, it will be automatically resized.
/// </param>
/// <exception cref="NotFoundException">
/// A NotFoundException is thrown if <paramref name="recno"/> is not in
/// the database.
/// </exception>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key parameter is
/// <paramref name="recno"/> and whose Value parameter is the retrieved
/// data items.
/// </returns>
public KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> GetMultiple(
uint recno, int BufferSize) {
return GetMultiple(recno, BufferSize, null, null);
}
/// <summary>
/// Retrieve a specific numbered key and all duplicate data items from
/// the database.
/// </summary>
/// <param name="recno">
/// The record number of the record to be retrieved.
/// </param>
/// <param name="BufferSize">
/// The initial size of the buffer to fill with duplicate data items. If
/// the buffer is not large enough, it will be automatically resized.
/// </param>
/// <param name="txn">
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <exception cref="NotFoundException">
/// A NotFoundException is thrown if <paramref name="recno"/> is not in
/// the database.
/// </exception>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key parameter is
/// <paramref name="recno"/> and whose Value parameter is the retrieved
/// data items.
/// </returns>
public KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> GetMultiple(
uint recno, int BufferSize, Transaction txn) {
return GetMultiple(recno, BufferSize, txn, null);
}
/// <summary>
/// Retrieve a specific numbered key and all duplicate data items from
/// the database.
/// </summary>
/// <param name="recno">
/// The record number of the record to be retrieved.
/// </param>
/// <param name="BufferSize">
/// The initial size of the buffer to fill with duplicate data items. If
/// the buffer is not large enough, it will be automatically resized.
/// </param>
/// <param name="txn">
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="info">The locking behavior to use.</param>
/// <exception cref="NotFoundException">
/// A NotFoundException is thrown if <paramref name="recno"/> is not in
/// the database.
/// </exception>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key parameter is
/// <paramref name="recno"/> and whose Value parameter is the retrieved
/// data items.
/// </returns>
public KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> GetMultiple(
uint recno, int BufferSize, Transaction txn, LockingInfo info) {
KeyValuePair<DatabaseEntry, DatabaseEntry> kvp;
DatabaseEntry key = new DatabaseEntry();
key.Data = BitConverter.GetBytes(recno);
DatabaseEntry data = new DatabaseEntry();
for (; ; ) {
data.UserData = new byte[BufferSize];
try {
kvp = Get(key, data, txn, info,
DbConstants.DB_MULTIPLE | DbConstants.DB_SET_RECNO);
break;
} catch (MemoryException) {
int sz = (int)data.size;
if (sz > BufferSize)
BufferSize = sz;
else
BufferSize *= 2;
}
}
MultipleDatabaseEntry dbe = new MultipleDatabaseEntry(kvp.Value);
return new KeyValuePair<DatabaseEntry, MultipleDatabaseEntry>(
kvp.Key, dbe);
}
/// <summary>
/// Return an estimate of the proportion of keys that are less than,
/// equal to, and greater than the specified key.
/// </summary>
/// <param name="key">The key to search for</param>
/// <returns>
/// An estimate of the proportion of keys that are less than, equal to,
/// and greater than the specified key.
/// </returns>
public KeyRange KeyRange(DatabaseEntry key) {
return KeyRange(key, null);
}
/// <summary>
/// Return an estimate of the proportion of keys that are less than,
/// equal to, and greater than the specified key.
/// </summary>
/// <param name="key">The key to search for</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// An estimate of the proportion of keys that are less than, equal to,
/// and greater than the specified key.
/// </returns>
public KeyRange KeyRange(DatabaseEntry key, Transaction txn) {
DB_KEY_RANGE range = new DB_KEY_RANGE();
db.key_range(Transaction.getDB_TXN(txn), key, range, 0);
return new KeyRange(range);
}
/// <summary>
/// Store the key/data pair in the database only if it does not already
/// appear in the database.
/// </summary>
/// <param name="key">The key to store in the database</param>
/// <param name="data">The data item to store in the database</param>
public void PutNoDuplicate(DatabaseEntry key, DatabaseEntry data) {
PutNoDuplicate(key, data, null);
}
/// <summary>
/// Store the key/data pair in the database only if it does not already
/// appear in the database.
/// </summary>
/// <param name="key">The key to store in the database</param>
/// <param name="data">The data item to store in the database</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
public void PutNoDuplicate(
DatabaseEntry key, DatabaseEntry data, Transaction txn) {
Put(key, data, txn, DbConstants.DB_NODUPDATA);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <returns>Database statistical information.</returns>
public BTreeStats Stats() {
return Stats(null, false, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>Database statistical information.</returns>
public BTreeStats Stats(Transaction txn) {
return Stats(txn, false, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <overloads>
/// The statistical information is described by
/// <see cref="BTreeStats"/>.
/// </overloads>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="isoDegree">
/// The level of isolation for database reads.
/// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for
/// databases which did not specify
/// <see cref="DatabaseConfig.ReadUncommitted"/>.
/// </param>
/// <returns>Database statistical information.</returns>
public BTreeStats Stats(Transaction txn, Isolation isoDegree) {
return Stats(txn, false, isoDegree);
}
private BTreeStats Stats(
Transaction txn, bool fast, Isolation isoDegree) {
uint flags = 0;
flags |= fast ? DbConstants.DB_FAST_STAT : 0;
switch (isoDegree) {
case Isolation.DEGREE_ONE:
flags |= DbConstants.DB_READ_UNCOMMITTED;
break;
case Isolation.DEGREE_TWO:
flags |= DbConstants.DB_READ_COMMITTED;
break;
}
BTreeStatStruct st = db.stat_bt(Transaction.getDB_TXN(txn), flags);
return new BTreeStats(st);
}
/// <summary>
/// Return pages to the filesystem that are already free and at the end
/// of the file.
/// </summary>
/// <returns>
/// The number of database pages returned to the filesystem
/// </returns>
public uint TruncateUnusedPages() {
return TruncateUnusedPages(null);
}
/// <summary>
/// Return pages to the filesystem that are already free and at the end
/// of the file.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// The number of database pages returned to the filesystem
/// </returns>
public uint TruncateUnusedPages(Transaction txn) {
DB_COMPACT cdata = new DB_COMPACT();
db.compact(Transaction.getDB_TXN(txn),
null, null, cdata, DbConstants.DB_FREELIST_ONLY, null);
return cdata.compact_pages_truncated;
}
#endregion Methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RoutesOperations operations.
/// </summary>
internal partial class RoutesOperations : IServiceOperations<NetworkManagementClient>, IRoutesOperations
{
/// <summary>
/// Initializes a new instance of the RoutesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RoutesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified route from a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified route from a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Route>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (routeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Route>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route in the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Parameters supplied to the create or update route operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Route>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<Route> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all routes in a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Route>>> ListWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Route>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Route>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified route from a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (routeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route in the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Parameters supplied to the create or update route operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Route>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (routeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeName");
}
if (routeParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeParameters");
}
if (routeParameters != null)
{
routeParameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("routeParameters", routeParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(routeParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeParameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Route>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all routes in a route table.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Route>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Route>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Route>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
#if NET35
// Needed for ReadOnlyDictionary, which does not exist in .NET 3.5
using Google.Protobuf.Collections;
#endif
namespace Google.Protobuf.Reflection
{
/// <summary>
/// Describes a message type.
/// </summary>
public sealed class MessageDescriptor : DescriptorBase
{
private static readonly HashSet<string> WellKnownTypeNames = new HashSet<string>
{
"google/protobuf/any.proto",
"google/protobuf/api.proto",
"google/protobuf/duration.proto",
"google/protobuf/empty.proto",
"google/protobuf/wrappers.proto",
"google/protobuf/timestamp.proto",
"google/protobuf/field_mask.proto",
"google/protobuf/source_context.proto",
"google/protobuf/struct.proto",
"google/protobuf/type.proto",
};
private readonly IList<FieldDescriptor> fieldsInDeclarationOrder;
private readonly IList<FieldDescriptor> fieldsInNumberOrder;
private readonly IDictionary<string, FieldDescriptor> jsonFieldMap;
private Func<IMessage, bool> extensionSetIsInitialized;
internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedClrTypeInfo generatedCodeInfo)
: base(file, file.ComputeFullName(parent, proto.Name), typeIndex)
{
Proto = proto;
Parser = generatedCodeInfo?.Parser;
ClrType = generatedCodeInfo?.ClrType;
ContainingType = parent;
// If generatedCodeInfo is null, we just won't generate an accessor for any fields.
Oneofs = DescriptorUtil.ConvertAndMakeReadOnly(
proto.OneofDecl,
(oneof, index) =>
new OneofDescriptor(oneof, file, this, index, generatedCodeInfo?.OneofNames[index]));
int syntheticOneofCount = 0;
foreach (var oneof in Oneofs)
{
if (oneof.IsSynthetic)
{
syntheticOneofCount++;
}
else if (syntheticOneofCount != 0)
{
throw new ArgumentException("All synthetic oneofs should come after real oneofs");
}
}
RealOneofCount = Oneofs.Count - syntheticOneofCount;
NestedTypes = DescriptorUtil.ConvertAndMakeReadOnly(
proto.NestedType,
(type, index) =>
new MessageDescriptor(type, file, this, index, generatedCodeInfo?.NestedTypes[index]));
EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(
proto.EnumType,
(type, index) =>
new EnumDescriptor(type, file, this, index, generatedCodeInfo?.NestedEnums[index]));
Extensions = new ExtensionCollection(this, generatedCodeInfo?.Extensions);
fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly(
proto.Field,
(field, index) =>
new FieldDescriptor(field, file, this, index, generatedCodeInfo?.PropertyNames[index], null));
fieldsInNumberOrder = new ReadOnlyCollection<FieldDescriptor>(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray());
// TODO: Use field => field.Proto.JsonName when we're confident it's appropriate. (And then use it in the formatter, too.)
jsonFieldMap = CreateJsonFieldMap(fieldsInNumberOrder);
file.DescriptorPool.AddSymbol(this);
Fields = new FieldCollection(this);
}
private static ReadOnlyDictionary<string, FieldDescriptor> CreateJsonFieldMap(IList<FieldDescriptor> fields)
{
var map = new Dictionary<string, FieldDescriptor>();
foreach (var field in fields)
{
map[field.Name] = field;
map[field.JsonName] = field;
}
return new ReadOnlyDictionary<string, FieldDescriptor>(map);
}
/// <summary>
/// The brief name of the descriptor's target.
/// </summary>
public override string Name => Proto.Name;
internal override IReadOnlyList<DescriptorBase> GetNestedDescriptorListForField(int fieldNumber)
{
switch (fieldNumber)
{
case DescriptorProto.FieldFieldNumber:
return (IReadOnlyList<DescriptorBase>) fieldsInDeclarationOrder;
case DescriptorProto.NestedTypeFieldNumber:
return (IReadOnlyList<DescriptorBase>) NestedTypes;
case DescriptorProto.EnumTypeFieldNumber:
return (IReadOnlyList<DescriptorBase>) EnumTypes;
default:
return null;
}
}
internal DescriptorProto Proto { get; }
internal bool IsExtensionsInitialized(IMessage message)
{
if (Proto.ExtensionRange.Count == 0)
{
return true;
}
if (extensionSetIsInitialized == null)
{
extensionSetIsInitialized = ReflectionUtil.CreateIsInitializedCaller(ClrType);
}
return extensionSetIsInitialized(message);
}
/// <summary>
/// The CLR type used to represent message instances from this descriptor.
/// </summary>
/// <remarks>
/// <para>
/// The value returned by this property will be non-null for all regular fields. However,
/// if a message containing a map field is introspected, the list of nested messages will include
/// an auto-generated nested key/value pair message for the field. This is not represented in any
/// generated type, so this property will return null in such cases.
/// </para>
/// <para>
/// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the type returned here
/// will be the generated message type, not the native type used by reflection for fields of those types. Code
/// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents
/// a wrapper type, and handle the result appropriately.
/// </para>
/// </remarks>
public Type ClrType { get; }
/// <summary>
/// A parser for this message type.
/// </summary>
/// <remarks>
/// <para>
/// As <see cref="MessageDescriptor"/> is not generic, this cannot be statically
/// typed to the relevant type, but it should produce objects of a type compatible with <see cref="ClrType"/>.
/// </para>
/// <para>
/// The value returned by this property will be non-null for all regular fields. However,
/// if a message containing a map field is introspected, the list of nested messages will include
/// an auto-generated nested key/value pair message for the field. No message parser object is created for
/// such messages, so this property will return null in such cases.
/// </para>
/// <para>
/// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the parser returned here
/// will be the generated message type, not the native type used by reflection for fields of those types. Code
/// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents
/// a wrapper type, and handle the result appropriately.
/// </para>
/// </remarks>
public MessageParser Parser { get; }
/// <summary>
/// Returns whether this message is one of the "well known types" which may have runtime/protoc support.
/// </summary>
internal bool IsWellKnownType => File.Package == "google.protobuf" && WellKnownTypeNames.Contains(File.Name);
/// <summary>
/// Returns whether this message is one of the "wrapper types" used for fields which represent primitive values
/// with the addition of presence.
/// </summary>
internal bool IsWrapperType => File.Package == "google.protobuf" && File.Name == "google/protobuf/wrappers.proto";
/// <value>
/// If this is a nested type, get the outer descriptor, otherwise null.
/// </value>
public MessageDescriptor ContainingType { get; }
/// <value>
/// A collection of fields, which can be retrieved by name or field number.
/// </value>
public FieldCollection Fields { get; }
/// <summary>
/// An unmodifiable list of extensions defined in this message's scope.
/// Note that some extensions may be incomplete (FieldDescriptor.Extension may be null)
/// if they are declared in a file generated using a version of protoc that did not fully
/// support extensions in C#.
/// </summary>
public ExtensionCollection Extensions { get; }
/// <value>
/// An unmodifiable list of this message type's nested types.
/// </value>
public IList<MessageDescriptor> NestedTypes { get; }
/// <value>
/// An unmodifiable list of this message type's enum types.
/// </value>
public IList<EnumDescriptor> EnumTypes { get; }
/// <value>
/// An unmodifiable list of the "oneof" field collections in this message type.
/// All "real" oneofs (where <see cref="OneofDescriptor.IsSynthetic"/> returns false)
/// come before synthetic ones.
/// </value>
public IList<OneofDescriptor> Oneofs { get; }
/// <summary>
/// The number of real "oneof" descriptors in this message type. Every element in <see cref="Oneofs"/>
/// with an index less than this will have a <see cref="OneofDescriptor.IsSynthetic"/> property value
/// of <c>false</c>; every element with an index greater than or equal to this will have a
/// <see cref="OneofDescriptor.IsSynthetic"/> property value of <c>true</c>.
/// </summary>
public int RealOneofCount { get; }
/// <summary>
/// Finds a field by field name.
/// </summary>
/// <param name="name">The unqualified name of the field (e.g. "foo").</param>
/// <returns>The field's descriptor, or null if not found.</returns>
public FieldDescriptor FindFieldByName(String name) => File.DescriptorPool.FindSymbol<FieldDescriptor>(FullName + "." + name);
/// <summary>
/// Finds a field by field number.
/// </summary>
/// <param name="number">The field number within this message type.</param>
/// <returns>The field's descriptor, or null if not found.</returns>
public FieldDescriptor FindFieldByNumber(int number) => File.DescriptorPool.FindFieldByNumber(this, number);
/// <summary>
/// Finds a nested descriptor by name. The is valid for fields, nested
/// message types, oneofs and enums.
/// </summary>
/// <param name="name">The unqualified name of the descriptor, e.g. "Foo"</param>
/// <returns>The descriptor, or null if not found.</returns>
public T FindDescriptor<T>(string name) where T : class, IDescriptor =>
File.DescriptorPool.FindSymbol<T>(FullName + "." + name);
/// <summary>
/// The (possibly empty) set of custom options for this message.
/// </summary>
[Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")]
public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
/// <summary>
/// The <c>MessageOptions</c>, defined in <c>descriptor.proto</c>.
/// If the options message is not present (i.e. there are no options), <c>null</c> is returned.
/// Custom options can be retrieved as extensions of the returned message.
/// NOTE: A defensive copy is created each time this property is retrieved.
/// </summary>
public MessageOptions GetOptions() => Proto.Options?.Clone();
/// <summary>
/// Gets a single value message option for this descriptor
/// </summary>
[Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public T GetOption<T>(Extension<MessageOptions, T> extension)
{
var value = Proto.Options.GetExtension(extension);
return value is IDeepCloneable<T> ? (value as IDeepCloneable<T>).Clone() : value;
}
/// <summary>
/// Gets a repeated value message option for this descriptor
/// </summary>
[Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public Collections.RepeatedField<T> GetOption<T>(RepeatedExtension<MessageOptions, T> extension)
{
return Proto.Options.GetExtension(extension).Clone();
}
/// <summary>
/// Looks up and cross-links all fields and nested types.
/// </summary>
internal void CrossLink()
{
foreach (MessageDescriptor message in NestedTypes)
{
message.CrossLink();
}
foreach (FieldDescriptor field in fieldsInDeclarationOrder)
{
field.CrossLink();
}
foreach (OneofDescriptor oneof in Oneofs)
{
oneof.CrossLink();
}
Extensions.CrossLink();
}
/// <summary>
/// A collection to simplify retrieving the field accessor for a particular field.
/// </summary>
public sealed class FieldCollection
{
private readonly MessageDescriptor messageDescriptor;
internal FieldCollection(MessageDescriptor messageDescriptor)
{
this.messageDescriptor = messageDescriptor;
}
/// <value>
/// Returns the fields in the message as an immutable list, in the order in which they
/// are declared in the source .proto file.
/// </value>
public IList<FieldDescriptor> InDeclarationOrder() => messageDescriptor.fieldsInDeclarationOrder;
/// <value>
/// Returns the fields in the message as an immutable list, in ascending field number
/// order. Field numbers need not be contiguous, so there is no direct mapping from the
/// index in the list to the field number; to retrieve a field by field number, it is better
/// to use the <see cref="FieldCollection"/> indexer.
/// </value>
public IList<FieldDescriptor> InFieldNumberOrder() => messageDescriptor.fieldsInNumberOrder;
// TODO: consider making this public in the future. (Being conservative for now...)
/// <value>
/// Returns a read-only dictionary mapping the field names in this message as they're available
/// in the JSON representation to the field descriptors. For example, a field <c>foo_bar</c>
/// in the message would result two entries, one with a key <c>fooBar</c> and one with a key
/// <c>foo_bar</c>, both referring to the same field.
/// </value>
internal IDictionary<string, FieldDescriptor> ByJsonName() => messageDescriptor.jsonFieldMap;
/// <summary>
/// Retrieves the descriptor for the field with the given number.
/// </summary>
/// <param name="number">Number of the field to retrieve the descriptor for</param>
/// <returns>The accessor for the given field</returns>
/// <exception cref="KeyNotFoundException">The message descriptor does not contain a field
/// with the given number</exception>
public FieldDescriptor this[int number]
{
get
{
var fieldDescriptor = messageDescriptor.FindFieldByNumber(number);
if (fieldDescriptor == null)
{
throw new KeyNotFoundException("No such field number");
}
return fieldDescriptor;
}
}
/// <summary>
/// Retrieves the descriptor for the field with the given name.
/// </summary>
/// <param name="name">Name of the field to retrieve the descriptor for</param>
/// <returns>The descriptor for the given field</returns>
/// <exception cref="KeyNotFoundException">The message descriptor does not contain a field
/// with the given name</exception>
public FieldDescriptor this[string name]
{
get
{
var fieldDescriptor = messageDescriptor.FindFieldByName(name);
if (fieldDescriptor == null)
{
throw new KeyNotFoundException("No such field name");
}
return fieldDescriptor;
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Cab.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Compression
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Management;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>AddFile</i> (<b>Required: </b>NewFile, CabFile, CabExePath, ExtractExePath, NewFileDestination)</para>
/// <para><i>Create</i> (<b>Required: </b>PathToCab or FilesToCab, CabFile, ExePath. <b>Optional: </b>PreservePaths, StripPrefixes, Recursive)</para>
/// <para><i>Extract</i> (<b>Required: </b>CabFile, ExtractExePath, ExtractTo <b>Optional:</b> ExtractFile)</para>
/// <para><b>Compatible with:</b></para>
/// <para>Microsoft (R) Cabinet Tool (cabarc.exe) - Version 5.2.3790.0</para>
/// <para>Microsoft (R) CAB File Extract Utility (extrac32.exe)- Version 5.2.3790.0</para>
/// <para><b>Remote Execution Support:</b> No</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="3.5" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <ItemGroup>
/// <!-- Create a collection of files to CAB -->
/// <Files Include="C:\ddd\**\*"/>
/// </ItemGroup>
/// <!-- Create the CAB using the File collection and preserve the paths whilst stripping a prefix -->
/// <MSBuild.ExtensionPack.Compression.Cab TaskAction="Create" FilesToCab="@(Files)" CabExePath="D:\BuildTools\CabArc.Exe" CabFile="C:\newcabbyitem.cab" PreservePaths="true" StripPrefixes="ddd\"/>
/// <!-- Create the same CAB but this time based on the Path. Note that Recursive is required -->
/// <MSBuild.ExtensionPack.Compression.Cab TaskAction="Create" PathToCab="C:\ddd" CabExePath="D:\BuildTools\CabArc.Exe" CabFile="C:\newcabbypath.cab" PreservePaths="true" StripPrefixes="ddd\" Recursive="true"/>
/// <!-- Add a file to the CAB -->
/// <MSBuild.ExtensionPack.Compression.Cab TaskAction="AddFile" NewFile="c:\New Text Document.txt" CabExePath="D:\BuildTools\CabArc.Exe" ExtractExePath="D:\BuildTools\Extrac32.EXE" CabFile="C:\newcabbyitem.cab" NewFileDestination="\Any Path"/>
/// <!-- Extract a CAB-->
/// <MSBuild.ExtensionPack.Compression.Cab TaskAction="Extract" ExtractTo="c:\a111" ExtractExePath="D:\BuildTools\Extrac32.EXE" CabFile="C:\newcabbyitem.cab"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
[HelpUrl("http://www.msbuildextensionpack.com/help/3.5.12.0/html/f7724cf2-0498-92d8-ba0f-26ca4772d8ee.htm")]
public class Cab : BaseTask
{
private const string AddFileTaskAction = "AddFile";
private const string CreateTaskAction = "Create";
private const string ExtractTaskAction = "Extract";
private string extractFile = "/E";
[DropdownValue(AddFileTaskAction)]
[DropdownValue(CreateTaskAction)]
[DropdownValue(ExtractTaskAction)]
public override string TaskAction
{
get { return base.TaskAction; }
set { base.TaskAction = value; }
}
/// <summary>
/// Sets the path to extract to
/// </summary>
[TaskAction(ExtractTaskAction, true)]
public ITaskItem ExtractTo { get; set; }
/// <summary>
/// Sets the CAB file. Required.
/// </summary>
[Required]
[TaskAction(AddFileTaskAction, true)]
[TaskAction(CreateTaskAction, true)]
[TaskAction(ExtractTaskAction, true)]
public ITaskItem CabFile { get; set; }
/// <summary>
/// Sets the path to cab
/// </summary>
[TaskAction(CreateTaskAction, false)]
public ITaskItem PathToCab { get; set; }
/// <summary>
/// Sets whether to add files and folders recursively if PathToCab is specified.
/// </summary>
[TaskAction(CreateTaskAction, false)]
public bool Recursive { get; set; }
/// <summary>
/// Sets the files to cab
/// </summary>
[TaskAction(CreateTaskAction, false)]
public ITaskItem[] FilesToCab { get; set; }
/// <summary>
/// Sets the path to CabArc.Exe
/// </summary>
[TaskAction(AddFileTaskAction, true)]
public ITaskItem CabExePath { get; set; }
/// <summary>
/// Sets the path to extrac32.exe
/// </summary>
[TaskAction(AddFileTaskAction, true)]
[TaskAction(ExtractTaskAction, true)]
public ITaskItem ExtractExePath { get; set; }
/// <summary>
/// Sets the files to extract. Default is /E, which is all.
/// </summary>
[TaskAction(ExtractTaskAction, false)]
public string ExtractFile
{
get { return this.extractFile; }
set { this.extractFile = value; }
}
/// <summary>
/// Sets a value indicating whether [preserve paths]
/// </summary>
[TaskAction(CreateTaskAction, false)]
public bool PreservePaths { get; set; }
/// <summary>
/// Sets the prefixes to strip. Delimit with ';'
/// </summary>
[TaskAction(CreateTaskAction, false)]
public string StripPrefixes { get; set; }
/// <summary>
/// Sets the new file to add to the Cab File
/// </summary>
[TaskAction(AddFileTaskAction, true)]
public ITaskItem NewFile { get; set; }
/// <summary>
/// Sets the path to add the file to
/// </summary>
[TaskAction(AddFileTaskAction, true)]
public string NewFileDestination { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
if (!this.TargetingLocalMachine())
{
return;
}
// Resolve TaskAction
switch (this.TaskAction)
{
case "Create":
this.Create();
break;
case "Extract":
this.Extract();
break;
case "AddFile":
this.AddFile();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
/// <summary>
/// Adds the file.
/// </summary>
private void AddFile()
{
// Validation
if (!this.ValidateExtract())
{
return;
}
if (!System.IO.File.Exists(this.NewFile.GetMetadata("FullPath")))
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "New File not found: {0}", this.NewFile.GetMetadata("FullPath")));
return;
}
FileInfo f = new FileInfo(this.NewFile.GetMetadata("FullPath"));
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Adding File: {0} to Cab: {1}", this.NewFile.GetMetadata("FullPath"), this.CabFile.GetMetadata("FullPath")));
string tempFolderName = System.Guid.NewGuid() + "\\";
DirectoryInfo dirInfo = new DirectoryInfo(Path.Combine(Path.GetTempPath(), tempFolderName));
Directory.CreateDirectory(dirInfo.FullName);
if (dirInfo.Exists)
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Created: {0}", dirInfo.FullName));
}
else
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "Failed to create temp folder: {0}", dirInfo.FullName));
return;
}
// configure the process we need to run
using (Process cabProcess = new Process())
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Extracting Cab: {0}", this.CabFile.GetMetadata("FullPath")));
cabProcess.StartInfo.FileName = this.ExtractExePath.GetMetadata("FullPath");
cabProcess.StartInfo.UseShellExecute = true;
cabProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"/Y /L ""{0}"" ""{1}"" ""{2}""", dirInfo.FullName, this.CabFile.GetMetadata("FullPath"), "/E");
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Calling {0} with {1}", this.ExtractExePath.GetMetadata("FullPath"), cabProcess.StartInfo.Arguments));
cabProcess.Start();
cabProcess.WaitForExit();
}
Directory.CreateDirectory(dirInfo.FullName + "\\" + this.NewFileDestination);
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Copying new File: {0} to {1}", this.NewFile, dirInfo.FullName + "\\" + this.NewFileDestination + "\\" + f.Name));
System.IO.File.Copy(this.NewFile.GetMetadata("FullPath"), dirInfo.FullName + this.NewFileDestination + @"\" + f.Name, true);
using (Process cabProcess = new Process())
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Creating Cab: {0}", this.CabFile.GetMetadata("FullPath")));
cabProcess.StartInfo.FileName = this.CabExePath.GetMetadata("FullPath");
cabProcess.StartInfo.UseShellExecute = false;
cabProcess.StartInfo.RedirectStandardOutput = true;
StringBuilder options = new StringBuilder();
options.Append("-r -p");
options.AppendFormat(" -P \"{0}\"\\", dirInfo.FullName.Remove(dirInfo.FullName.Length - 1).Replace(@"C:\", string.Empty));
cabProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"{0} N ""{1}"" {2}", options, this.CabFile.GetMetadata("FullPath"), "\"" + dirInfo.FullName + "*.*\"" + " ");
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Calling {0} with {1}", this.CabExePath.GetMetadata("FullPath"), cabProcess.StartInfo.Arguments));
// start the process
cabProcess.Start();
// Read any messages from CABARC...and log them
string output = cabProcess.StandardOutput.ReadToEnd();
cabProcess.WaitForExit();
if (output.Contains("Completed successfully"))
{
this.LogTaskMessage(output);
}
else
{
this.Log.LogError(output);
}
}
string dirObject = string.Format(CultureInfo.CurrentCulture, "win32_Directory.Name='{0}'", dirInfo.FullName.Remove(dirInfo.FullName.Length - 1));
using (ManagementObject mdir = new ManagementObject(dirObject))
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Deleting Temp Folder: {0}", dirObject));
mdir.Get();
ManagementBaseObject outParams = mdir.InvokeMethod("Delete", null, null);
// ReturnValue should be 0, else failure
if (outParams != null)
{
if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value, CultureInfo.CurrentCulture) != 0)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Directory deletion error: ReturnValue: {0}", outParams.Properties["ReturnValue"].Value));
return;
}
}
else
{
this.Log.LogError("The ManagementObject call to invoke Delete returned null.");
return;
}
}
}
/// <summary>
/// Extracts this instance.
/// </summary>
private void Extract()
{
// Validation
if (this.ValidateExtract() == false)
{
return;
}
if (this.ExtractTo == null)
{
this.Log.LogError("ExtractTo required.");
return;
}
// configure the process we need to run
using (Process cabProcess = new Process())
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Extracting Cab: {0}", this.CabFile.GetMetadata("FullPath")));
cabProcess.StartInfo.FileName = this.ExtractExePath.GetMetadata("FullPath");
cabProcess.StartInfo.UseShellExecute = true;
cabProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"/Y /L ""{0}"" ""{1}"" ""{2}""", this.ExtractTo.GetMetadata("FullPath"), this.CabFile.GetMetadata("FullPath"), this.ExtractFile);
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Calling {0} with {1}", this.ExtractExePath.GetMetadata("FullPath"), cabProcess.StartInfo.Arguments));
cabProcess.Start();
cabProcess.WaitForExit();
}
}
/// <summary>
/// Validates the extract.
/// </summary>
/// <returns>bool</returns>
private bool ValidateExtract()
{
// Validation
if (System.IO.File.Exists(this.CabFile.GetMetadata("FullPath")) == false)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "CAB file not found: {0}", this.CabFile.GetMetadata("FullPath")));
return false;
}
if (this.ExtractExePath == null)
{
if (System.IO.File.Exists(Environment.SystemDirectory + "extrac32.exe"))
{
this.ExtractExePath = new TaskItem();
this.ExtractExePath.SetMetadata("FullPath", Environment.SystemDirectory + "extrac32.exe");
}
else
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Executable not found: {0}", this.ExtractExePath.GetMetadata("FullPath")));
return false;
}
}
else
{
if (System.IO.File.Exists(this.ExtractExePath.GetMetadata("FullPath")) == false)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Executable not found: {0}", this.ExtractExePath.GetMetadata("FullPath")));
return false;
}
}
return true;
}
/// <summary>
/// Creates this instance.
/// </summary>
private void Create()
{
// Validation
if (System.IO.File.Exists(this.CabExePath.GetMetadata("FullPath")) == false)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Executable not found: {0}", this.CabExePath.GetMetadata("FullPath")));
return;
}
using (Process cabProcess = new Process())
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Cab: {0}", this.CabFile.GetMetadata("FullPath")));
cabProcess.StartInfo.FileName = this.CabExePath.GetMetadata("FullPath");
cabProcess.StartInfo.UseShellExecute = false;
cabProcess.StartInfo.RedirectStandardOutput = true;
StringBuilder options = new StringBuilder();
if (this.PreservePaths)
{
options.Append("-p");
}
if (this.PathToCab != null && this.Recursive)
{
options.Append(" -r ");
}
// Could be more than one prefix to strip...
if (string.IsNullOrEmpty(this.StripPrefixes) == false)
{
string[] prefixes = this.StripPrefixes.Split(';');
foreach (string prefix in prefixes)
{
options.AppendFormat(" -P {0}", prefix);
}
}
string files = string.Empty;
if ((this.FilesToCab == null || this.FilesToCab.Length == 0) && this.PathToCab == null)
{
Log.LogError("FilesToCab or PathToCab must be supplied");
return;
}
if (this.PathToCab != null)
{
files = this.PathToCab.GetMetadata("FullPath");
if (!files.EndsWith(@"\*", StringComparison.OrdinalIgnoreCase))
{
files += @"\*";
}
}
else
{
foreach (ITaskItem file in this.FilesToCab)
{
files += "\"" + file.ItemSpec + "\"" + " ";
}
}
cabProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"{0} N ""{1}"" {2}", options, this.CabFile.GetMetadata("FullPath"), files);
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Calling {0} with {1}", this.CabExePath.GetMetadata("FullPath"), cabProcess.StartInfo.Arguments));
// start the process
cabProcess.Start();
// Read any messages from CABARC...and log them
string output = cabProcess.StandardOutput.ReadToEnd();
cabProcess.WaitForExit();
if (output.Contains("Completed successfully"))
{
this.LogTaskMessage(MessageImportance.Low, output);
}
else
{
this.Log.LogError(output);
}
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
using Object = System.Object;
namespace Framework.Editor
{
public class ParameterBindView
{
private static float BIND_ENUM_WIDTH = 64;
private float BIND_ENTRY_HEIGHT => EditorGUIUtility.singleLineHeight + 4;
private int DATASET_ASSET_PICKER_WINDOW_ID;
private int DATASET_RUNTIME_PICKER_WINDOW_ID;
private UnityEditorInternal.ReorderableList ListDrawer;
private List<Framework.Parameter> Parameters;
private IParameterBinder Binder;
private IDataSetProvider Provider;
private UnityEngine.Object EditorTarget;
public UnityEditorInternal.ReorderableList GetList()
{
return ListDrawer;
}
public float GetHeight()
{
return IsValid() ? ListDrawer.GetHeight() + 1 : 0;
}
public void DoList(Rect position)
{
if (IsValid()) ListDrawer.DoList(position);
}
public bool IsValid()
{
bool isOk = true;
isOk &= Parameters != null;
isOk &= Provider != null;
isOk &= Binder != null;
isOk &= EditorTarget != null;
return isOk;
}
public bool Initialize(List<Framework.Parameter> parameters, BindingContext context, UnityEngine.Object target)
{
Parameters = parameters;
Provider = context.Provider;
Binder = context.Binder;
EditorTarget = target;
var isOk = IsValid();
if (isOk && ListDrawer == null)
{
ListDrawer = new UnityEditorInternal.ReorderableList
(
Parameters,
typeof(Framework.Parameter),
false,
true,
false,
false
);
ListDrawer.drawHeaderCallback += rect =>
{
var oldColor = GUI.color;
GUI.color = Color.white;
GUI.Label(rect, "Parameter Bindings", EditorStyles.whiteLabel);
GUI.color = oldColor;
};
ListDrawer.drawElementBackgroundCallback += (rect, index, active, focused) => { };
ListDrawer.elementHeight = BIND_ENTRY_HEIGHT;
ListDrawer.showDefaultBackground = false;
ListDrawer.drawElementCallback += OnDrawBinding;
}
return isOk;
}
private void OnDrawBinding(Rect rect, int index, bool active, bool focused)
{
EditorGUI.BeginDisabledGroup(Application.isPlaying);
{
var oldColor = GUI.color;
GUI.color = Color.Lerp(Color.white, new Color(1, 1, 1, 0), 0.65f);
GUI.Box(rect, GUIContent.none);
GUI.color = Color.white;
var param = Parameters[index];
var oldRect = rect;
rect = EditorGUI.PrefixLabel(rect, new GUIContent(param.Name), SpaceEditorStyles.InvisibleText);
var labelRect = oldRect;
labelRect.width = rect.x - oldRect.x;
EditorGUI.SelectableLabel(labelRect, param.Name, EditorStyles.whiteMiniLabel);
{
rect.width -= BIND_ENUM_WIDTH;
var binding = Binder.GetSyncList(Parameters)?.FirstOrDefault(b => b.Param.ParameterId == param.Id);
if (binding != null)
{
switch (binding.Type)
{
case BindingType.Unbound:
EditorGUI.HelpBox(rect, "UNBOUND", MessageType.Warning);
break;
case BindingType.Value:
HandleBindValue(rect, binding);
break;
case BindingType.LocalProperty:
HandleBindProperty(rect, binding);
break;
case BindingType.DataSetVariable:
HandleBindDataSet(rect, binding);
break;
}
rect.x += rect.width;
rect.y += 3;
rect.width = BIND_ENUM_WIDTH;
var newType = (BindingType) EditorGUI.EnumPopup(rect, GUIContent.none, binding.Type);
if (binding.Type != newType)
{
OnChangeBindingType(binding, Binder, newType);
}
}
}
GUI.color = oldColor;
}
EditorGUI.EndDisabledGroup();
}
void OnChangeBindingType(ParamBinding binding, IParameterBinder binder, BindingType type)
{
binding.SetBindingType(type, Provider);
}
void HandleBindValue(Rect rect, ParamBinding binding)
{
if (binding == null)
return;
var fieldRect = rect;
fieldRect.y += 2;
fieldRect.height = EditorGUIUtility.singleLineHeight;
VariantUtils.DrawParameter(fieldRect, binding.DefaultValue, false);
}
void HandleBindDataSet(Rect rect, ParamBinding binding)
{
if (binding == null)
return;
var buttonRect = rect;
buttonRect.y += 2;
buttonRect.height = EditorGUIUtility.singleLineHeight;
buttonRect.width *= 0.5f;
if (Event.current.commandName == "ObjectSelectorUpdated")
{
if (EditorGUIUtility.GetObjectPickerControlID() == DATASET_RUNTIME_PICKER_WINDOW_ID)
{
GUI.changed = true;
var go = EditorGUIUtility.GetObjectPickerObject() as GameObject;
if (go != null)
binding.Context = go.GetComponent<DataSetInstance>();
DATASET_RUNTIME_PICKER_WINDOW_ID = -1;
}
else if (EditorGUIUtility.GetObjectPickerControlID() == DATASET_ASSET_PICKER_WINDOW_ID)
{
GUI.changed = true;
binding.Context = EditorGUIUtility.GetObjectPickerObject();
DATASET_ASSET_PICKER_WINDOW_ID = -1;
}
}
// Button to invoke menu
// local
// --
// Pick runtime...
// Pick asset...
if (EditorGUI.DropdownButton(buttonRect, new GUIContent(binding?.ContextAsDataSet?.ToString()), FocusType.Passive, EditorStyles.objectField))
{
GenericMenu pickDataset = new GenericMenu();
pickDataset.AddItem(new GUIContent("local (from parametrized object IProvider)"), false, () =>
{
GUI.changed = true;
});
pickDataset.AddSeparator(string.Empty);
pickDataset.AddItem(new GUIContent("Pick runtime..."), false, () =>
{
DATASET_RUNTIME_PICKER_WINDOW_ID = GUIUtility.GetControlID(FocusType.Passive) + 200;
EditorGUIUtility.ShowObjectPicker<DataSetInstance>
(
null, true, string.Empty,
DATASET_RUNTIME_PICKER_WINDOW_ID
);
});
pickDataset.AddItem(new GUIContent("Pick asset..."), false, () =>
{
DATASET_ASSET_PICKER_WINDOW_ID = GUIUtility.GetControlID(FocusType.Passive) + 100;
EditorGUIUtility.ShowObjectPicker<DataSet>
(
null, false, string.Empty,
DATASET_ASSET_PICKER_WINDOW_ID
);
});
pickDataset.DropDown(buttonRect);
}
buttonRect.x += buttonRect.width;
EditorGUI.BeginDisabledGroup(binding.ContextAsDataSet == null);
{
// Button to invoke menu
// go to DataSet...
// --
// list of vars of matching type
EditorGUI.Popup(buttonRect, 0, new[]
{
"SomeVar",
}, GUI.skin.button);
}
EditorGUI.EndDisabledGroup();
}
void HandleBindProperty(Rect rect, ParamBinding binding)
{
if (binding == null)
return;
var objectRect = rect;
objectRect.y += 2;
objectRect.height = EditorGUIUtility.singleLineHeight;
objectRect.width *= 0.5f;
EditorGUI.ObjectField(objectRect, null, typeof(UnityEngine.Object), true);
objectRect.x += objectRect.width;
// Button to invoke menu
// local
// --
// Pick runtime...
// Pick asset...
objectRect.y += 2;
EditorGUI.Popup(objectRect, 0, new[]
{
"Component >",
"Some Var",
"Some Prop",
}, SpaceEditorStyles.LightObjectField);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace LazerTagHostLibrary
{
public class Player : ScoredObject
{
private readonly HostGun _hostGun;
public RandomId TaggerId { get; set; }
public bool Confirmed = false;
public bool Dropped = false;
public bool TagSummaryReceived = false;
public TeamPlayerId TeamPlayerId { get; set; }
public Team Team { get; set; }
public int TagsTaken = 0;
public TimeSpan SurviveTime { get; set; }
public bool Survived { get; set; }
public bool[] TeamTagReportsExpected = {false, false, false};
public bool[] TeamTagReportsReceived = {false, false, false};
private int[] _taggedPlayerCounts = new int[TeamPlayerId.MaximumPlayerNumber];
public int[] TaggedPlayerCounts
{
get { return _taggedPlayerCounts; }
set { _taggedPlayerCounts = value; }
}
private int[] _taggedByPlayerCounts = new int[TeamPlayerId.MaximumPlayerNumber];
public int[] TaggedByPlayerCounts
{
get { return _taggedByPlayerCounts; }
set { _taggedByPlayerCounts = value; }
}
public TimeSpan ZoneTime;
// TODO: Remove this and handle it in the UI layer
public string Name { get; set; }
public string DisplayName
{
get
{
return string.IsNullOrWhiteSpace(Name) ? NameAndNumber : Name;
}
}
public string NameAndNumber
{
get
{
var isTeamGame = _hostGun.GameDefinition.IsTeamGame;
if (string.IsNullOrWhiteSpace(Name)) return TeamPlayerId.ToStringFull(isTeamGame);
var teamPlayerId = TeamPlayerId.ToString(isTeamGame);
return string.Format("{0} ({1})", Name, teamPlayerId);
}
}
public Player(HostGun hostGun, byte taggerId)
{
_hostGun = hostGun;
TaggerId = taggerId;
Survived = false;
}
public bool AllTagReportsReceived()
{
if (Dropped) return true;
if (!TagSummaryReceived) return false;
for (var i = 0; i < 3; i++)
{
if (TeamTagReportsExpected[i] && !TeamTagReportsReceived[i]) return false;
}
return true;
}
}
public class PlayerCollection : ICollection<Player>
{
private readonly List<Player> _players = new List<Player>();
public void CalculateRanks()
{
ScoredObject.CalculateRanks(this);
}
public Player Player(TeamPlayerId teamPlayerId)
{
try
{
return _players.FirstOrDefault(player => player.TeamPlayerId == teamPlayerId);
}
catch (InvalidOperationException)
{
return null;
}
}
public IEnumerator<Player> GetEnumerator()
{
return _players.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(Player item)
{
_players.Add(item);
}
public void Clear()
{
_players.Clear();
}
public bool Contains(Player item)
{
return (_players.Contains(item));
}
public void CopyTo(Player[] array, int arrayIndex)
{
_players.CopyTo(array, arrayIndex);
}
public bool Remove(Player item)
{
return _players.Remove(item);
}
public bool Remove(TeamPlayerId teamPlayerId)
{
return _players.Remove(Player(teamPlayerId));
}
public int Count
{
get { return _players.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
}
public struct TeamPlayerId
: IEquatable<TeamPlayerId>
{
public TeamPlayerId(int playerNumber)
: this()
{
PlayerNumber = playerNumber;
}
public TeamPlayerId(int teamNumber, int playerNumber)
: this()
{
PlayerNumber = PlayerFromTeamAndTeamPlayer(teamNumber, playerNumber);
}
public const int MaximumPlayerNumber = 24;
public int PlayerNumber { get; set; }
public int TeamNumber
{
get { return PlayerNumber == 0 ? 0 : (((PlayerNumber - 1) & 0x1f) >> 3) + 1; }
set { PlayerNumber = PlayerFromTeamAndTeamPlayer(value, TeamPlayerNumber); }
}
public int TeamPlayerNumber
{
get { return PlayerNumber == 0 ? 0 : ((PlayerNumber - 1) & 0x7) + 1; }
set { PlayerNumber = PlayerFromTeamAndTeamPlayer(TeamNumber, value); }
}
public UInt16 Packed23
{
get { return (byte) (PlayerNumber == 0 ? 0 : ((TeamNumber & 0x3) << 3) | ((TeamPlayerNumber - 1) & 0x7)); }
set
{
var teamNumber = (value >> 3) & 0x3;
var teamPlayerNumber = (value & 0x7) + 1;
PlayerNumber = PlayerFromTeamAndTeamPlayer(teamNumber, teamPlayerNumber);
}
}
public UInt16 Packed34
{
get { return (UInt16) (PlayerNumber == 0 ? 0 : (Packed44 & 0x7f)); }
set
{
var teamNumber = (value >> 4) & 0x7;
var teamPlayerNumber = (value & 0xf) + 1;
PlayerNumber = PlayerFromTeamAndTeamPlayer(teamNumber, teamPlayerNumber);
}
}
public UInt16 Packed44
{
get { return (byte) (PlayerNumber == 0 ? 0 : (((TeamNumber & 0xf) << 4) | ((TeamPlayerNumber - 1) & 0xf))); }
set
{
var teamNumber = (value >> 4) & 0xf;
var teamPlayerNumber = (value & 0xf) + 1;
PlayerNumber = PlayerFromTeamAndTeamPlayer(teamNumber, teamPlayerNumber);
}
}
public static TeamPlayerId FromPacked23(UInt16 value)
{
return new TeamPlayerId {Packed23 = value};
}
public static TeamPlayerId FromPacked34(UInt16 value)
{
return new TeamPlayerId {Packed34 = value};
}
public static TeamPlayerId FromPacked44(UInt16 value)
{
return new TeamPlayerId {Packed44 = value};
}
private static int PlayerFromTeamAndTeamPlayer(int teamNumber, int teamPlayerNumber)
{
if (teamNumber == 0 || teamPlayerNumber == 0) return 0;
return (((teamNumber & 0x3) - 1) << 3) + (((teamPlayerNumber - 1) & 0x7) + 1);
}
public static bool operator ==(TeamPlayerId first, TeamPlayerId second)
{
return first.PlayerNumber == second.PlayerNumber;
}
public static bool operator !=(TeamPlayerId first, TeamPlayerId second)
{
return !(first == second);
}
public bool Equals(TeamPlayerId other)
{
return this == other;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is TeamPlayerId && Equals((TeamPlayerId) obj);
}
public override int GetHashCode()
{
return PlayerNumber.GetHashCode();
}
public override string ToString()
{
return ToString(false);
}
public string ToString(bool teamGame)
{
if (teamGame)
{
return string.Format("T{0}:P{1}", TeamNumber, TeamPlayerNumber);
}
return PlayerNumber.ToString(CultureInfo.InvariantCulture);
}
public string ToStringFull(bool teamGame)
{
if (teamGame)
{
return string.Format("Team {0}, Player {1}", TeamNumber, TeamPlayerNumber);
}
return string.Format("Player {0}", PlayerNumber);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using InstructionEditor.Gui;
using FlatRedBall;
using InstructionEditor.Collections;
using EditorObjects;
using FlatRedBall.Instructions;
using FlatRedBall.Input;
using FlatRedBall.Gui;
using Microsoft.Xna.Framework.Graphics;
using FlatRedBall.ManagedSpriteGroups;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;
using FlatRedBall.Graphics.Model;
using ToolTemplate;
using FlatRedBall.Graphics;
using FlatRedBall.Content;
using FlatRedBall.IO;
using FlatRedBall.Content.AnimationChain;
using FlatRedBall.Utilities;
using FlatRedBall.Instructions.ScriptedAnimations;
namespace InstructionEditor
{
#region XML Docs
/// <summary>
/// Stores all data that the tool will edit.
/// </summary>
/// <remarks>
/// Examples include Scenes, Polygon Lists, PositionedModel Lists, or any other
/// custom data that you may edit.
/// </remarks>
#endregion
public static class EditorData
{
#region Fields
private static EditorLogic mEditorLogic = new EditorLogic();
public const string ContentManagerName = "Tool ContentManager";
static Scene mBlockingScene;
static Scene mInactiveScene;
static List<string> mAllSpriteMembersWatching = new List<string>();
static List<string> mAllSpriteFrameMembersWatching = new List<string>();
static List<string> mAllPositionedModelMembersWatching = new List<string>();
static List<string> mAllTextMembersWatching = new List<string>();
static List<string> mCurrentSpriteMembersWatching = new List<string>();
static List<string> mCurrentSpriteFrameMembersWatching = new List<string>();
static List<string> mCurrentPositionedModelMembersWatching = new List<string>();
static List<string> mCurrentTextMembersWatching = new List<string>();
static List<string> mSavedMembers = new List<string>();
static Camera mSceneCamera = new Camera(ContentManagerName);
static EditorObjects.CameraBounds mCameraBounds;
public static SpriteList ActiveSprites; // one way array, as the Sprites will be removed from the SpriteManager often when rewinding
public static FormationArray formationArray;
public static Sprite currentKeyframeSprite;
//public static Instruction currentKeyframe;
public static InstructionPlayer instructionPlayer;
public static int groupNumber = 0;
static RectangleSelector rectangleSelector;
static List<AnimationSequence> mGlobalInstructionSets;
static Dictionary<INameable, InstructionSet> mObjectInstructionSets = new Dictionary<INameable, InstructionSet>();
static EditorOptions mEditorOptions = new EditorOptions();
#endregion
#region Properties
public static List<string> AllPositionedModelMembersWatching
{
get { return mAllPositionedModelMembersWatching; }
}
public static List<string> AllSpriteFrameMembersWatching
{
get { return mAllSpriteFrameMembersWatching; }
}
public static List<string> AllSpriteMembersWatching
{
get { return mAllSpriteMembersWatching; }
}
public static List<string> AllTextMembersWatching
{
get { return mAllTextMembersWatching; }
}
public static Scene BlockingScene
{
get { return mBlockingScene; }
set
{
// Clear out the old blocking scene
mBlockingScene.RemoveFromManagers();
mBlockingScene.Clear();
mBlockingScene = value;
mBlockingScene.AddToManagers();
}
}
public static List<string> CurrentPositionedModelMembersWatching
{
get { return mCurrentPositionedModelMembersWatching; }
}
public static List<string> CurrentSpriteFrameMembersWatching
{
get { return mCurrentSpriteFrameMembersWatching; }
}
public static List<string> CurrentSpriteMembersWatching
{
get { return mCurrentSpriteMembersWatching; }
}
public static List<string> CurrentTextMembersWatching
{
get { return mCurrentTextMembersWatching; }
}
public static EditorLogic EditorLogic
{
get { return mEditorLogic; }
}
public static EditorOptions EditorOptions
{
get { return mEditorOptions; }
}
public static Scene InactiveScene
{
get { return mInactiveScene; }
set { mInactiveScene = value; }
}
public static List<AnimationSequence> GlobalInstructionSets
{
get { return mGlobalInstructionSets; }
set { mGlobalInstructionSets = value; }
}
public static Dictionary<INameable, InstructionSet> ObjectInstructionSets
{
get { return mObjectInstructionSets; }
}
public static Camera SceneCamera
{
get { return mSceneCamera; }
}
#endregion
#region Methods
#region Initialization Methods
static EditorData()
{
// Force the UI to be created
mEditorLogic = new EditorLogic();
mGlobalInstructionSets = new List<AnimationSequence>();
SpriteManager.Camera.Z = 40.0f;
mCameraBounds = new CameraBounds(mSceneCamera);
mBlockingScene = new Scene();
#region create the spriteArrays, InstructionGroupArray, and SpriteGridArray
ActiveSprites = new SpriteList();
formationArray = new FormationArray();
#endregion
// Add the properties that are going to be watched for InstructionSets
CreateMembersWatching();
instructionPlayer = new InstructionPlayer();
//= SpriteManager.AddSprite("genGfx/targetBox.bmp", sprMan.AddLayer());
// currentSpriteMarker.fade = 150;
// currentSpriteMarker.visible = false;
rectangleSelector = new RectangleSelector();
}
private static void CreateMembersWatching()
{
#region Sprite members watching
mAllSpriteMembersWatching.Add("X");
mAllSpriteMembersWatching.Add("Y");
mAllSpriteMembersWatching.Add("Z");
mAllSpriteMembersWatching.Add("RelativeX");
mAllSpriteMembersWatching.Add("RelativeY");
mAllSpriteMembersWatching.Add("RelativeZ");
mAllSpriteMembersWatching.Add("ScaleX");
mAllSpriteMembersWatching.Add("ScaleY");
mAllSpriteMembersWatching.Add("RotationX");
mAllSpriteMembersWatching.Add("RotationY");
mAllSpriteMembersWatching.Add("RotationZ");
mAllSpriteMembersWatching.Add("RelativeRotationX");
mAllSpriteMembersWatching.Add("RelativeRotationY");
mAllSpriteMembersWatching.Add("RelativeRotationZ");
mAllSpriteMembersWatching.Add("ColorOperation");
mAllSpriteMembersWatching.Add("Alpha");
mAllSpriteMembersWatching.Add("Red");
mAllSpriteMembersWatching.Add("Green");
mAllSpriteMembersWatching.Add("Blue");
mAllSpriteMembersWatching.Add("Visible");
mAllSpriteMembersWatching.Add("CurrentChainName");
mAllSpriteMembersWatching.Add("Animate");
mAllSpriteMembersWatching.Add("AnimationSpeed");
#endregion
#region SpriteFrame members watching
mAllSpriteFrameMembersWatching.Add("X");
mAllSpriteFrameMembersWatching.Add("Y");
mAllSpriteFrameMembersWatching.Add("Z");
mAllSpriteFrameMembersWatching.Add("RelativeX");
mAllSpriteFrameMembersWatching.Add("RelativeY");
mAllSpriteFrameMembersWatching.Add("RelativeZ");
mAllSpriteFrameMembersWatching.Add("ScaleX");
mAllSpriteFrameMembersWatching.Add("ScaleY");
mAllSpriteFrameMembersWatching.Add("RotationX");
mAllSpriteFrameMembersWatching.Add("RotationY");
mAllSpriteFrameMembersWatching.Add("RotationZ");
mAllSpriteFrameMembersWatching.Add("RelativeRotationX");
mAllSpriteFrameMembersWatching.Add("RelativeRotationY");
mAllSpriteFrameMembersWatching.Add("RelativeRotationZ");
mAllSpriteFrameMembersWatching.Add("ColorOperation");
mAllSpriteFrameMembersWatching.Add("Alpha");
mAllSpriteFrameMembersWatching.Add("Red");
mAllSpriteFrameMembersWatching.Add("Green");
mAllSpriteFrameMembersWatching.Add("Blue");
mAllSpriteFrameMembersWatching.Add("Visible");
#endregion
#region PositionedModel members watching
mAllPositionedModelMembersWatching.Add("X");
mAllPositionedModelMembersWatching.Add("Y");
mAllPositionedModelMembersWatching.Add("Z");
mAllPositionedModelMembersWatching.Add("RelativeX");
mAllPositionedModelMembersWatching.Add("RelativeY");
mAllPositionedModelMembersWatching.Add("RelativeZ");
mAllPositionedModelMembersWatching.Add("ScaleX");
mAllPositionedModelMembersWatching.Add("ScaleY");
mAllPositionedModelMembersWatching.Add("ScaleZ");
mAllPositionedModelMembersWatching.Add("RotationX");
mAllPositionedModelMembersWatching.Add("RotationY");
mAllPositionedModelMembersWatching.Add("RotationZ");
mAllPositionedModelMembersWatching.Add("RelativeRotationX");
mAllPositionedModelMembersWatching.Add("RelativeRotationY");
mAllPositionedModelMembersWatching.Add("RelativeRotationZ");
mAllPositionedModelMembersWatching.Add("Visible");
mAllPositionedModelMembersWatching.Add("Animate");
mAllPositionedModelMembersWatching.Add("CurrentAnimation");
#endregion
#region Text members watching
mAllTextMembersWatching.Add("X");
mAllTextMembersWatching.Add("Y");
mAllTextMembersWatching.Add("Z");
mAllTextMembersWatching.Add("RelativeX");
mAllTextMembersWatching.Add("RelativeY");
mAllTextMembersWatching.Add("RelativeZ");
mAllTextMembersWatching.Add("RotationX");
mAllTextMembersWatching.Add("RotationY");
mAllTextMembersWatching.Add("RotationZ");
mAllTextMembersWatching.Add("RelativeRotationX");
mAllTextMembersWatching.Add("RelativeRotationY");
mAllTextMembersWatching.Add("RelativeRotationZ");
mAllTextMembersWatching.Add("ColorOperation");
mAllTextMembersWatching.Add("Alpha");
mAllTextMembersWatching.Add("Red");
mAllTextMembersWatching.Add("Green");
mAllTextMembersWatching.Add("Blue");
mAllTextMembersWatching.Add("Visible");
mAllTextMembersWatching.Add("DisplayText");
#endregion
}
#endregion
#region Public Methods
public static void Update()
{
mEditorLogic.Update();
MouseShortcuts();
instructionPlayer.Activity();
UpdateUI();
UpdateObjectInstructionSets();// this might get expensive. Profile if problems occur
ManageSpriteGrids();
}
public static void AdjustMovementPath()
{
// this is called either when Key.I is released or when releasing the mouse button when I is down
//if(oldSpritePosition != null)
//{
// float differenceX = mEditorLogic.CurrentSprites[0].X - oldSpritePosition.X;
// float differenceY = mEditorLogic.CurrentSprites[0].Y - oldSpritePosition.Y;
// float differenceZ = mEditorLogic.CurrentSprites[0].Z - oldSpritePosition.Z;
// foreach (Sprite s in mEditorLogic.CurrentSprites)
// {
// foreach(PositionInstruction i in ((IESprite)s).positionInstructions)
// {
// i.X += differenceX;
// i.Y += differenceY;
// i.Z += differenceZ;
// }
// }
// oldSpritePosition = null;
//}
}
static List<string> mEmptyList = new List<string>();
public static void AddInstructionsToList(InstructionList instructionList, double timeToExecute)
{
AddInstructionsToList(instructionList, timeToExecute, mEmptyList);
}
public static void AddInstructionsToList(InstructionList instructionList, double timeToExecute, List<string> membersToIgnore)
{
if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.All)
{
#region Loop through all Sprites and create instructions for them
foreach (Sprite sprite in BlockingScene.Sprites)
{
InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, sprite);
}
#endregion
#region Loop through all SpriteFrames and create instructions for them
foreach (SpriteFrame spriteFrame in BlockingScene.SpriteFrames)
{
InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, spriteFrame);
}
#endregion
#region Loop through all PositionedModels and create Instructions for them
foreach (PositionedModel positionedModel in mBlockingScene.PositionedModels)
{
InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, positionedModel);
}
#endregion
#region Loop through all Texts and create Instructions for them
foreach (Text text in BlockingScene.Texts)
{
InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, text);
}
#endregion
}
else if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.Current)
{
if (EditorData.EditorLogic.CurrentSprites.Count != 0)
{
InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore,
EditorData.EditorLogic.CurrentSprites[0]);
}
else if (EditorData.EditorLogic.CurrentSpriteFrames.Count != 0)
{
InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore,
EditorData.EditorLogic.CurrentSpriteFrames[0]);
}
else if (EditorData.EditorLogic.CurrentPositionedModels.Count != 0)
{
InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore,
EditorData.EditorLogic.CurrentPositionedModels[0]);
}
else if (EditorData.EditorLogic.CurrentTexts.Count != 0)
{
InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore,
EditorData.EditorLogic.CurrentTexts[0]);
}
}
}
public static void AddSprite(string textureOrAnimationFile)
{
Sprite newSprite = null;
if (FileManager.GetExtension(textureOrAnimationFile) == "achx")
{
AnimationChainListSave achs = AnimationChainListSave.FromFile(textureOrAnimationFile);
newSprite = SpriteManager.AddSprite(
achs.ToAnimationChainList(ContentManagerName));
mBlockingScene.Sprites.Add(newSprite);
newSprite.Name = FileManager.RemovePath(FileManager.RemoveExtension(textureOrAnimationFile));
}
else
{
newSprite = SpriteManager.AddSprite(textureOrAnimationFile, ContentManagerName);
mBlockingScene.Sprites.Add(newSprite);
newSprite.Name = FileManager.RemovePath(FileManager.RemoveExtension(textureOrAnimationFile));
}
SetNewlyCreatedSpriteProperties(newSprite);
}
public static void AddText()
{
Text text = TextManager.AddText("Text");
mBlockingScene.Texts.Add(text);
text.Name = "Text";
StringFunctions.MakeNameUnique<Text>(text, mBlockingScene.Texts);
}
#region XML Docs
/// <summary>
/// Exports the code that can be executed instead of the global instruction set
/// </summary>
/// <returns>The string containing the source code.</returns>
#endregion
public static string GetStringForInstructions()
{
StringBuilder stringBuilder = new StringBuilder();
InstructionList temporaryInstructionList = new InstructionList();
#region Create an array of doubles for times
//stringBuilder.AppendLine("static double[][] KeyframeTimes = new double[][]{");
//foreach (InstructionSet instructionSet in EditorData.GlobalInstructionSets)
//{
// for (int keyframeListIndex = 0; keyframeListIndex < instructionSet.Count; keyframeListIndex++)
// {
// KeyframeList keyframeList = mGlobalInstructionSet[keyframeListIndex];
// stringBuilder.AppendLine("\tnew double[]{");
// for (int i = 0; i < keyframeList.Count; i++)
// {
// if (i == keyframeList.Count - 1)
// {
// stringBuilder.AppendLine("\t\t" + keyframeList[i][0].TimeToExecute);
// }
// else
// {
// stringBuilder.AppendLine("\t\t" + keyframeList[i][0].TimeToExecute + ",");
// }
// }
// if (keyframeListIndex == mGlobalInstructionSet.Count - 1)
// {
// stringBuilder.AppendLine("\t}");
// }
// else
// {
// stringBuilder.AppendLine("\t},");
// }
// }
//}
#endregion
stringBuilder.AppendLine("};");
stringBuilder.AppendLine();
stringBuilder.AppendLine();
stringBuilder.AppendLine();
stringBuilder.AppendLine("public void SetCurrentFrame()");
stringBuilder.AppendLine("{");
stringBuilder.AppendLine("\tswitch( mCurrentAnimation )");
stringBuilder.AppendLine("\t{");
//for(int keyframeIndex = 0; keyframeIndex < mGlobalInstructionSet.Count; keyframeIndex++)
//{
// KeyframeList keyframeList = mGlobalInstructionSet[keyframeIndex];
// stringBuilder.AppendLine("\t\tcase " + keyframeIndex + ":");
// stringBuilder.AppendLine("\t\tswitch( mCurrentKeyframe )");
// stringBuilder.AppendLine("\t\t{");
// for(int i= 0; i < keyframeList.Count; i++)
// {
// temporaryInstructionList.Clear();
// temporaryInstructionList.AddRange( keyframeList[i] );
// temporaryInstructionList.AddRange( mGlobalInstructionSet[keyframeIndex].CreateVelocityListAtIndex(i) );
// stringBuilder.AppendLine("\t\t\tcase " + i + ":");
// foreach (GenericInstruction instruction in temporaryInstructionList)
// {
// #region Get the name of the object and stuff it in objectName
// string objectName = "object";
// if(instruction.Target is Sprite)
// {
// int index = mBlockingScene.Sprites.IndexOf(instruction.Target as Sprite);
// objectName = "mSprites[" + index + "].";
// }
// if (instruction.Target is SpriteFrame)
// {
// int index = mBlockingScene.SpriteFrames.IndexOf(instruction.Target as SpriteFrame);
// objectName = "mSpriteFrames[" + index + "].";
// }
// if (instruction.Target is Text)
// {
// int index = mBlockingScene.Texts.IndexOf(instruction.Target as Text);
// objectName = "mTexts[" + index + "].";
// }
// if (instruction.Target is PositionedModel)
// {
// int index = mBlockingScene.PositionedModels.IndexOf(instruction.Target as PositionedModel);
// objectName = "mPositionedModels[" + index + "].";
// }
// #endregion
// string memberValueAsString = instruction.MemberValueAsString;
// if (instruction.MemberValueAsObject is float)
// {
// memberValueAsString += "f";
// }
// else if (instruction.MemberValueAsObject != null && instruction.MemberValueAsObject.GetType().IsEnum)
// {
// memberValueAsString =
// instruction.MemberValueAsObject.GetType().FullName + "." + memberValueAsString;
// }
// stringBuilder.AppendLine("\t\t\t\t" + objectName + instruction.Member + " = " +
// memberValueAsString + ";");
// }
// stringBuilder.AppendLine("\t\t\t\tbreak;");
// }
// stringBuilder.AppendLine("\t\t}");
// stringBuilder.AppendLine("\t\tbreak;");
//}
stringBuilder.AppendLine("\t}");
stringBuilder.AppendLine("}");
return stringBuilder.ToString();
}
public static bool MouseControlOverKeyframes()
{
if (mEditorLogic.CurrentSprites.Count == 0) return false;
//if(GuiManager.CursorObjectGrabbed != null &&
// GuiManager.CursorObjectGrabbed is Sprite && ((Sprite)(GuiManager.CursorObjectGrabbed)).type == "positionKeyframe")
// GuiData.propertyWindow.UpdateKeyframeValues();
#region find which keyframe the cursor is over giving the currentKeyframe more importance
Sprite tempSpriteOver = null;
if (currentKeyframeSprite != null && GuiManager.Cursor.IsOn(currentKeyframeSprite))
{
// not sure what this does, will probably get replaced
// tempSpriteOver = ((IESprite)mEditorLogic.CurrentSprites[0]).movementPath.positionInstructions[((IESprite)mEditorLogic.CurrentSprites[0]).positionInstructions.IndexOf(currentKeyframe)];
}
else
{
//foreach (Sprite s in ((IESprite)mEditorLogic.CurrentSprites[0]).movementPath.positionInstructions)
//{
// if (GuiManager.Cursor.IsOn(s))
// {
// tempSpriteOver = s;
// break;
// }
//}
}
#endregion
#region primaryPush - grabbing and setting a currentKeyframe
if (GuiManager.Cursor.PrimaryPush || GuiManager.Cursor.SecondaryPush)
{
GuiManager.Cursor.SetObjectRelativePosition(currentKeyframeSprite);
GuiManager.Cursor.ObjectGrabbed = currentKeyframeSprite;
}
return (tempSpriteOver != null);
#endregion
}
public static void MouseShortcuts()
{
Cursor cursor = GuiManager.Cursor;
if (cursor.WindowOver != null || GuiManager.DominantWindowActive)
{
return;
}
EditorObjects.CameraMethods.MouseCameraControl(SpriteManager.Camera);
/*
else if(mouseButtons[1] != 0x00 && mouseButtons[2] != 0x00)
{
GuiManager.CursorStaticPosition = true;
GuiData.timeLineWindow.timeLine.CurrentValue += GuiManager.CursorXVelocity * GuiData.timeLineWindow.timeLine.valueWidth / GuiData.timeLineWindow.timeLine.ScaleX;
// GuiData.timeLineWindow.currentTimeTextBox.Text = GuiData.timeLineWindow.timeLine.currentValue.ToString();
GuiData.timeLineWindow.timeLine.CallOnGUIChange();
}
*/
/* // no idea what this is.
*
if ((mouseButtons[2] != 0 && mouse.ButtonReleased(FlatRedBall.Input.Mouse.MouseButtons.RightButton)) ||
(mouseButtons[1] != 0 && mouse.ButtonReleased(FlatRedBall.Input.Mouse.MouseButtons.MiddleButton)) ||
(inpMan.MouseClick(1) && inpMan.MouseClick(2) ))
{
GuiManager.CursorstaticPosition = false;
}
*/
}
public static void SaveActiveScene(string fileName)
{
SpriteEditorScene sceneSave = SpriteEditorScene.FromScene(mBlockingScene);
sceneSave.Save(fileName);
mBlockingScene.Name = fileName;
}
public static void SetTime(double timeToSet)
{
if (mEditorLogic.CurrentKeyframeList != null &&
InputManager.Keyboard.KeyDown(Keys.H) == false // H holds the layout so the user can change time without moving things.
)
{
mEditorLogic.CurrentKeyframeList.SetState(timeToSet, false);
}
//if(currentSprites.Count != 0)
// GuiData.propertyWindow.UpdateSpriteValues();
}
public static void SpriteGrabbedLogic()
{
// this method will move the sprite grabbed. This includes both keyrames and active sprites.
if (GuiManager.Cursor.ObjectGrabbed == null) return;
Sprite sprite = GuiManager.Cursor.ObjectGrabbed as Sprite;
#region move button is pressed
if (GuiData.ToolsWindow.MoveButton.IsPressed)
{
if (GuiManager.Cursor.PrimaryDown)
{
Vector3 positionBeforeMouseMove = sprite.Position;
float x = 0;
float y = 0;
GuiManager.Cursor.GetCursorPositionForSprite(ref x, ref y, sprite.Z);
if (mEditorLogic.CurrentSprites.Contains(sprite))
{ // dragging a current Sprite, so loop through all current Sprites and move them appropriately
foreach (Sprite s in mEditorLogic.CurrentSprites)
{
//MoveSpriteBy(s as IESprite, x - positionBeforeMouseMove.X,
// y - positionBeforeMouseMove.Y,
// 0);
}
}
}
else if (GuiManager.Cursor.SecondaryDown)
{
GuiManager.Cursor.StaticPosition = true;
sprite.Z += GuiManager.Cursor.YVelocity;
}
if (GuiManager.Cursor.SecondaryClick)
GuiManager.Cursor.StaticPosition = false;
}
#endregion
}
#endregion
#region Private Methods
static void ManageSpriteGrids()
{
if (mInactiveScene != null)
{
foreach (SpriteGrid spriteGrid in mInactiveScene.SpriteGrids)
{
spriteGrid.Manage();
}
}
if (mBlockingScene != null)
{
foreach (SpriteGrid spriteGrid in mBlockingScene.SpriteGrids)
{
spriteGrid.Manage();
}
}
}
static void SetNewlyCreatedSpriteProperties(Sprite newSprite)
{
StringFunctions.MakeNameUnique<Sprite>(newSprite, mBlockingScene.Sprites);
newSprite.X = SpriteManager.Camera.X;
newSprite.Y = SpriteManager.Camera.Y;
if (SpriteManager.Camera.Orthogonal && newSprite.Texture != null)
{
newSprite.ScaleX = newSprite.Texture.Width / 2.0f;
newSprite.ScaleY = newSprite.Texture.Height / 2.0f;
}
}
static List<Sprite> sSpritesToRemove = new List<Sprite>();
static List<Text> sTextsToRemove = new List<Text>();
static void UpdateObjectInstructionSets()
{
#region Sprites
foreach (Sprite sprite in mBlockingScene.Sprites)
{
if (mObjectInstructionSets.ContainsKey(sprite) == false)
{
mObjectInstructionSets.Add(sprite, new InstructionSet());
}
}
sSpritesToRemove.Clear();
// Use a temporary list to store off the Sprites that should be removed.
foreach (KeyValuePair<INameable, InstructionSet> kvp in mObjectInstructionSets)
{
if (kvp.Key is Sprite && mBlockingScene.Sprites.Contains((kvp.Key as Sprite)) == false)
{
sSpritesToRemove.Add(kvp.Key as Sprite);
}
}
for (int i = 0; i < sSpritesToRemove.Count; i++)
{
mObjectInstructionSets.Remove(sSpritesToRemove[i]);
}
#endregion
#region Texts
foreach (Text text in mBlockingScene.Texts)
{
if (mObjectInstructionSets.ContainsKey(text) == false)
{
mObjectInstructionSets.Add(text, new InstructionSet());
}
}
// Use a temporary list to store off the Texts that should be removed.
sTextsToRemove.Clear();
foreach (KeyValuePair<INameable, InstructionSet> kvp in mObjectInstructionSets)
{
if (kvp.Key is Text && mBlockingScene.Texts.Contains((kvp.Key as Text)) == false)
{
sTextsToRemove.Add(kvp.Key as Text);
}
}
for (int i = 0; i < sTextsToRemove.Count; i++)
{
mObjectInstructionSets.Remove(sTextsToRemove[i]);
}
#endregion
}
static void UpdateUI()
{
GuiData.Update();
mCameraBounds.UpdateBounds(0);
}
#endregion
#endregion
}
}
| |
#region License Header
// /*******************************************************************************
// * Open Behavioral Health Information Technology Architecture (OBHITA.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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ******************************************************************************/
#endregion
namespace ProCenter.Domain.PatientModule
{
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Pillar.Common.InversionOfControl;
using Pillar.Common.Utility;
using Pillar.Domain.Primitives;
using Pillar.FluentRuleEngine;
using ProCenter.Common;
using ProCenter.Common.Extension;
using ProCenter.Domain.CommonModule;
using ProCenter.Domain.PatientModule.Event;
using ProCenter.Domain.SecurityModule;
using ProCenter.Primitive;
#endregion
/// <summary>Patient class.</summary>
public class Patient : AggregateRootBase
{
#region Static Fields
private static Dictionary<string, PropertyInfo> _propertyCache;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="Patient" /> class.
/// </summary>
public Patient ()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Patient" /> class.
/// </summary>
/// <param name="orgaizationKey">Organization Key.</param>
/// <param name="name">The name.</param>
/// <param name="dateOfBirth">The date of birth.</param>
/// <param name="gender">The gender.</param>
/// <param name="email">The email.</param>
internal Patient ( Guid orgaizationKey, PersonName name, DateTime? dateOfBirth, Gender gender, Email email )
{
Check.IsNotNull ( orgaizationKey, () => OrganizationKey );
Check.IsNotNull ( name, () => Name );
Check.IsNotNull ( dateOfBirth, () => DateOfBirth );
Check.IsNotNull ( gender, () => Gender );
Key = CombGuid.NewCombGuid ();
var patientUniqueIdentifierGenerator = IoC.CurrentContainer.Resolve<IPatientUniqueIdentifierGenerator> ();
var uniqueIdentifier = patientUniqueIdentifierGenerator.GenerateUniqueIdentifier ( Key, name.LastName, gender, dateOfBirth.Value );
Email = email;
RaiseEvent ( new PatientCreatedEvent ( Key, Version, orgaizationKey, name, dateOfBirth, gender, uniqueIdentifier ) );
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the date of birth.
/// </summary>
/// <value>
/// The date of birth.
/// </value>
public DateTime? DateOfBirth { get; protected set; }
/// <summary>
/// Gets or sets the email.
/// </summary>
/// <value>
/// The email.
/// </value>
public Email Email { get; protected set; }
/// <summary>
/// Gets or sets the ethnicity.
/// </summary>
/// <value>
/// The ethnicity.
/// </value>
public Ethnicity Ethnicity { get; protected set; }
/// <summary>
/// Gets or sets the gender.
/// </summary>
/// <value>
/// The gender.
/// </value>
public Gender Gender { get; protected set; }
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public PersonName Name { get; protected set; }
/// <summary>
/// Gets or sets the organization key.
/// </summary>
/// <value>
/// The organization key.
/// </value>
public Guid OrganizationKey { get; protected set; }
/// <summary>
/// Gets or sets the religion.
/// </summary>
/// <value>
/// The religion.
/// </value>
public Religion Religion { get; protected set; }
/// <summary>
/// Gets or sets the unique identifier.
/// </summary>
/// <value>
/// The unique identifier.
/// </value>
public string UniqueIdentifier { get; protected set; }
#endregion
#region Public Methods and Operators
/// <summary>
/// Revises the date of birth.
/// </summary>
/// <param name="dateOfBirth">The date of birth.</param>
public virtual void ReviseDateOfBirth ( DateTime? dateOfBirth )
{
var patientChangedEvent = new PatientChangedEvent ( Key, Version, p => p.DateOfBirth, dateOfBirth );
new RuleEngineExecutor<Patient> ( this )
.ForCallingMethodRuleSet ()
.WithContext ( patientChangedEvent )
.Execute ( () => RaiseEvent ( patientChangedEvent ) );
}
/// <summary>
/// Revises the email.
/// </summary>
/// <param name="email">The email.</param>
public virtual void ReviseEmail ( Email email )
{
var patientChangedEvent = new PatientChangedEvent(Key, Version, p => p.Email, email);
new RuleEngineExecutor<Patient>(this)
.ForCallingMethodRuleSet()
.WithContext(patientChangedEvent)
.Execute(() => RaiseEvent(patientChangedEvent));
}
/// <summary>
/// Revises the ethnicity.
/// </summary>
/// <param name="ethnicity">The ethnicity.</param>
public virtual void ReviseEthnicity ( Ethnicity ethnicity )
{
Check.IsNotNull ( ethnicity, () => Ethnicity );
RaiseEvent ( new PatientChangedEvent ( Key, Version, p => p.Ethnicity, ethnicity ) );
}
/// <summary>
/// Revises the gender.
/// </summary>
/// <param name="gender">The gender.</param>
public virtual void ReviseGender ( Gender gender )
{
Check.IsNotNull ( gender, () => Gender );
RaiseEvent ( new PatientChangedEvent ( Key, Version, p => p.Gender, gender ) );
}
/// <summary>
/// Revises the name.
/// </summary>
/// <param name="name">The name.</param>
public virtual void ReviseName ( PersonName name )
{
Check.IsNotNull ( name, () => Name );
RaiseEvent ( new PatientChangedEvent ( Key, Version, p => p.Name, name ) );
}
/// <summary>
/// Revises the religion.
/// </summary>
/// <param name="religion">The religion.</param>
public virtual void ReviseReligion ( Religion religion )
{
Check.IsNotNull ( religion, () => Religion );
RaiseEvent ( new PatientChangedEvent ( Key, Version, p => p.Religion, religion ) );
}
/// <summary>Validates the information.</summary>
/// <param name="systemAccount">The system account.</param>
/// <param name="patientIdentifier">The patient identifier.</param>
/// <param name="dateOfBirth">The date of birth.</param>
/// <returns>A <see cref="ValidationStatus"/>.</returns>
public ValidationStatus ValidateInfo ( SystemAccount systemAccount, string patientIdentifier, DateTime dateOfBirth )
{
if ( string.Equals ( patientIdentifier, UniqueIdentifier ) && DateOfBirth.Value == dateOfBirth )
{
systemAccount.Validate ();
UserContext.Current.RefreshValidationAttempts ();
return ValidationStatus.Valid;
}
if ( UserContext.Current.ValidationAttempts >= 3 )
{
systemAccount.TemporaryLock ();
return ValidationStatus.Locked;
}
UserContext.Current.FailedValidationAttempt ();
return ValidationStatus.AttemptFailed;
}
#endregion
#region Methods
private void Apply ( PatientCreatedEvent patientCreatedEvent )
{
OrganizationKey = patientCreatedEvent.OrganizationKey;
Name = patientCreatedEvent.Name;
DateOfBirth = patientCreatedEvent.DateOfBirth;
Gender = patientCreatedEvent.Gender;
UniqueIdentifier = patientCreatedEvent.UniqueIdentifier;
}
private void Apply ( PatientChangedEvent patientChangedEvent )
{
var propertyName = patientChangedEvent.Property;
var value = patientChangedEvent.Value;
if ( _propertyCache == null )
{
_propertyCache =
GetType ()
.GetProperties (
BindingFlags.Public | BindingFlags.Instance |
BindingFlags.FlattenHierarchy )
.ToDictionary ( pi => pi.Name );
}
var property = _propertyCache.ContainsKey ( propertyName ) ? _propertyCache[propertyName] : null;
if ( property == null )
{
throw new InvalidOperationException ( string.Format ( "Invalid property name {0}", propertyName ) );
}
if ( value != null && !property.PropertyType.IsInstanceOfType ( value ) )
{
var convertToType = property.PropertyType.GetConvertToType ();
value = Convert.ChangeType ( value, convertToType );
}
property.SetValue ( this, value );
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using System.Globalization;
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public class XmlWriterDelegator
#else
internal class XmlWriterDelegator
#endif
{
protected XmlWriter writer;
protected XmlDictionaryWriter dictionaryWriter;
internal int depth;
private int _prefixes;
public XmlWriterDelegator(XmlWriter writer)
{
XmlObjectSerializer.CheckNull(writer, "writer");
this.writer = writer;
this.dictionaryWriter = writer as XmlDictionaryWriter;
}
internal XmlWriter Writer
{
get { return writer; }
}
internal void Flush()
{
writer.Flush();
}
internal string LookupPrefix(string ns)
{
return writer.LookupPrefix(ns);
}
private void WriteEndAttribute()
{
writer.WriteEndAttribute();
}
#if USE_REFEMIT
public void WriteEndElement()
#else
internal void WriteEndElement()
#endif
{
writer.WriteEndElement();
depth--;
}
internal void WriteRaw(char[] buffer, int index, int count)
{
writer.WriteRaw(buffer, index, count);
}
internal void WriteRaw(string data)
{
writer.WriteRaw(data);
}
internal void WriteXmlnsAttribute(XmlDictionaryString ns)
{
if (dictionaryWriter != null)
{
if (ns != null)
dictionaryWriter.WriteXmlnsAttribute(null, ns);
}
else
WriteXmlnsAttribute(ns.Value);
}
internal void WriteXmlnsAttribute(string ns)
{
if (ns != null)
{
if (ns.Length == 0)
writer.WriteAttributeString("xmlns", String.Empty, null, ns);
else
{
if (dictionaryWriter != null)
dictionaryWriter.WriteXmlnsAttribute(null, ns);
else
{
string prefix = writer.LookupPrefix(ns);
if (prefix == null)
{
prefix = String.Format(CultureInfo.InvariantCulture, "d{0}p{1}", depth, _prefixes);
_prefixes++;
writer.WriteAttributeString("xmlns", prefix, null, ns);
}
}
}
}
}
internal void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
{
if (dictionaryWriter != null)
{
dictionaryWriter.WriteXmlnsAttribute(prefix, ns);
}
else
{
writer.WriteAttributeString("xmlns", prefix, null, ns.Value);
}
}
private void WriteStartAttribute(string prefix, string localName, string ns)
{
writer.WriteStartAttribute(prefix, localName, ns);
}
private void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartAttribute(prefix, localName, namespaceUri);
else
writer.WriteStartAttribute(prefix,
(localName == null ? null : localName.Value),
(namespaceUri == null ? null : namespaceUri.Value));
}
internal void WriteAttributeString(string prefix, string localName, string ns, string value)
{
WriteStartAttribute(prefix, localName, ns);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
private void WriteAttributeStringValue(string value)
{
writer.WriteValue(value);
}
internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
private void WriteAttributeStringValue(XmlDictionaryString value)
{
if (dictionaryWriter == null)
writer.WriteString(value.Value);
else
dictionaryWriter.WriteString(value);
}
internal void WriteAttributeInt(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, int value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeIntValue(value);
WriteEndAttribute();
}
private void WriteAttributeIntValue(int value)
{
writer.WriteValue(value);
}
internal void WriteAttributeBool(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, bool value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeBoolValue(value);
WriteEndAttribute();
}
private void WriteAttributeBoolValue(bool value)
{
writer.WriteValue(value);
}
internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string name, string ns)
{
WriteXmlnsAttribute(ns);
WriteStartAttribute(attrPrefix, attrName, attrNs);
WriteAttributeQualifiedNameValue(name, ns);
WriteEndAttribute();
}
private void WriteAttributeQualifiedNameValue(string name, string ns)
{
writer.WriteQualifiedName(name, ns);
}
internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteXmlnsAttribute(ns);
WriteStartAttribute(attrPrefix, attrName, attrNs);
WriteAttributeQualifiedNameValue(name, ns);
WriteEndAttribute();
}
private void WriteAttributeQualifiedNameValue(XmlDictionaryString name, XmlDictionaryString ns)
{
if (dictionaryWriter == null)
writer.WriteQualifiedName(name.Value, ns.Value);
else
dictionaryWriter.WriteQualifiedName(name, ns);
}
internal void WriteStartElement(string localName, string ns)
{
WriteStartElement(null, localName, ns);
}
internal virtual void WriteStartElement(string prefix, string localName, string ns)
{
writer.WriteStartElement(prefix, localName, ns);
depth++;
_prefixes = 1;
}
#if USE_REFEMIT
public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
#else
internal void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
#endif
{
WriteStartElement(null, localName, namespaceUri);
}
internal void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartElement(prefix, localName, namespaceUri);
else
writer.WriteStartElement(prefix, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value));
depth++;
_prefixes = 1;
}
internal void WriteStartElementPrimitive(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartElement(null, localName, namespaceUri);
else
writer.WriteStartElement(null, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value));
}
internal void WriteEndElementPrimitive()
{
writer.WriteEndElement();
}
internal WriteState WriteState
{
get { return writer.WriteState; }
}
internal string XmlLang
{
get { return writer.XmlLang; }
}
internal XmlSpace XmlSpace
{
get { return writer.XmlSpace; }
}
#if USE_REFEMIT
public void WriteNamespaceDecl(XmlDictionaryString ns)
#else
internal void WriteNamespaceDecl(XmlDictionaryString ns)
#endif
{
WriteXmlnsAttribute(ns);
}
private Exception CreateInvalidPrimitiveTypeException(Type type)
{
return new InvalidDataContractException(SR.Format(SR.InvalidPrimitiveType, DataContract.GetClrTypeFullName(type)));
}
internal void WriteAnyType(object value)
{
WriteAnyType(value, value.GetType());
}
internal void WriteAnyType(object value, Type valueType)
{
bool handled = true;
switch (valueType.GetTypeCode())
{
case TypeCode.Boolean:
WriteBoolean((bool)value);
break;
case TypeCode.Char:
WriteChar((char)value);
break;
case TypeCode.Byte:
WriteUnsignedByte((byte)value);
break;
case TypeCode.Int16:
WriteShort((short)value);
break;
case TypeCode.Int32:
WriteInt((int)value);
break;
case TypeCode.Int64:
WriteLong((long)value);
break;
case TypeCode.Single:
WriteFloat((float)value);
break;
case TypeCode.Double:
WriteDouble((double)value);
break;
case TypeCode.Decimal:
WriteDecimal((decimal)value);
break;
case TypeCode.DateTime:
WriteDateTime((DateTime)value);
break;
case TypeCode.String:
WriteString((string)value);
break;
case TypeCode.SByte:
WriteSignedByte((sbyte)value);
break;
case TypeCode.UInt16:
WriteUnsignedShort((ushort)value);
break;
case TypeCode.UInt32:
WriteUnsignedInt((uint)value);
break;
case TypeCode.UInt64:
WriteUnsignedLong((ulong)value);
break;
case TypeCode.Empty:
case TypeCode.Object:
default:
if (valueType == Globals.TypeOfByteArray)
WriteBase64((byte[])value);
else if (valueType == Globals.TypeOfObject)
{
//Write Nothing
}
else if (valueType == Globals.TypeOfTimeSpan)
WriteTimeSpan((TimeSpan)value);
else if (valueType == Globals.TypeOfGuid)
WriteGuid((Guid)value);
else if (valueType == Globals.TypeOfUri)
WriteUri((Uri)value);
else if (valueType == Globals.TypeOfXmlQualifiedName)
WriteQName((XmlQualifiedName)value);
else
handled = false;
break;
}
if (!handled)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType));
}
internal void WriteString(string value)
{
writer.WriteValue(value);
}
internal virtual void WriteBoolean(bool value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteBoolean(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDateTime(DateTime value)
{
WriteString(XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind));
}
#if USE_REFEMIT
public void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteDateTime(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDecimal(decimal value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteDecimal(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDouble(double value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteDouble(value);
WriteEndElementPrimitive();
}
internal virtual void WriteInt(int value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteInt(value);
WriteEndElementPrimitive();
}
internal virtual void WriteLong(long value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteLong(value);
WriteEndElementPrimitive();
}
internal virtual void WriteFloat(float value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteFloat(value);
WriteEndElementPrimitive();
}
private const int CharChunkSize = 76;
private const int ByteChunkSize = CharChunkSize / 4 * 3;
internal virtual void WriteBase64(byte[] bytes)
{
if (bytes == null)
return;
writer.WriteBase64(bytes, 0, bytes.Length);
}
internal virtual void WriteShort(short value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteShort(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedByte(byte value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedByte(value);
WriteEndElementPrimitive();
}
internal virtual void WriteSignedByte(sbyte value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteSignedByte(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedInt(uint value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedInt(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedLong(ulong value)
{
writer.WriteRaw(XmlConvert.ToString(value));
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedLong(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedShort(ushort value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedShort(value);
WriteEndElementPrimitive();
}
internal virtual void WriteChar(char value)
{
writer.WriteValue((int)value);
}
#if USE_REFEMIT
public void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteChar(value);
WriteEndElementPrimitive();
}
internal void WriteTimeSpan(TimeSpan value)
{
writer.WriteRaw(XmlConvert.ToString(value));
}
#if USE_REFEMIT
public void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteTimeSpan(value);
WriteEndElementPrimitive();
}
internal void WriteGuid(Guid value)
{
writer.WriteRaw(value.ToString());
}
#if USE_REFEMIT
public void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteGuid(value);
WriteEndElementPrimitive();
}
internal void WriteUri(Uri value)
{
writer.WriteString(value.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped));
}
internal virtual void WriteQName(XmlQualifiedName value)
{
if (value != XmlQualifiedName.Empty)
{
WriteXmlnsAttribute(value.Namespace);
WriteQualifiedName(value.Name, value.Namespace);
}
}
internal void WriteQualifiedName(string localName, string ns)
{
writer.WriteQualifiedName(localName, ns);
}
internal void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString ns)
{
if (dictionaryWriter == null)
writer.WriteQualifiedName(localName.Value, ns.Value);
else
dictionaryWriter.WriteQualifiedName(localName, ns);
}
#if USE_REFEMIT
public void WriteBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteBoolean(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDateTime(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDecimal(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteInt(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteLong(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteFloat(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDouble(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.SimplifyTypeNames;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.SimplifyTypeNames
{
public partial class SimplifyTypeNamesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
#region "Fix all occurrences tests"
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInDocument()
{
var fixAllActionId = SimplifyTypeNamesCodeFixProvider.GetCodeActionId(IDEDiagnosticIds.SimplifyNamesDiagnosticId, "System.Int32");
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
{|FixAllInDocument:System.Int32|} i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
await TestAsync(input, expected, compareTokens: false, options: PreferIntrinsicTypeEverywhere, fixAllActionEquivalenceKey: fixAllActionId);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInProject()
{
var fixAllActionId = SimplifyTypeNamesCodeFixProvider.GetCodeActionId(IDEDiagnosticIds.SimplifyNamesDiagnosticId, "System.Int32");
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
{|FixAllInProject:System.Int32|} i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
await TestAsync(input, expected, compareTokens: false, options: PreferIntrinsicTypeEverywhere, fixAllActionEquivalenceKey: fixAllActionId);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution()
{
var fixAllActionId = SimplifyTypeNamesCodeFixProvider.GetCodeActionId(IDEDiagnosticIds.SimplifyNamesDiagnosticId, "System.Int32");
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
{|FixAllInSolution:System.Int32|} i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
await TestAsync(input, expected, compareTokens: false, options:PreferIntrinsicTypeEverywhere, fixAllActionEquivalenceKey: fixAllActionId);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution_RemoveThis()
{
var fixAllActionId = SimplifyTypeNamesCodeFixProvider.GetCodeActionId(IDEDiagnosticIds.RemoveQualificationDiagnosticId, null);
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class ProgramA
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = {|FixAllInSolution:this.x|};
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class ProgramA2
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB2
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class ProgramA3
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB3
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class ProgramA
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x;
System.Int16 s1 = y;
System.Int32 i2 = z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x2;
System.Int16 s1 = y2;
System.Int32 i2 = z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class ProgramA2
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x;
System.Int16 s1 = y;
System.Int32 i2 = z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB2
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x2;
System.Int16 s1 = y2;
System.Int32 i2 = z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class ProgramA3
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x;
System.Int16 s1 = y;
System.Int32 i2 = z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB3
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x2;
System.Int16 s1 = y2;
System.Int32 i2 = z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
await TestAsync(input, expected, compareTokens: false, fixAllActionEquivalenceKey: fixAllActionId);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution_SimplifyMemberAccess()
{
var fixAllActionId = SimplifyTypeNamesCodeFixProvider.GetCodeActionId(IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId, "System.Console");
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class ProgramA
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
{|FixAllInSolution:System.Console.Write|}(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class ProgramA2
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB2
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class ProgramA3
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB3
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class ProgramA
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class ProgramA2
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB2
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class ProgramA3
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB3
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
await TestAsync(input, expected, compareTokens: false, fixAllActionEquivalenceKey: fixAllActionId);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution_RemoveMemberAccessQualification()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
int Property { get; set; }
int OtherProperty { get; set; }
void M()
{
{|FixAllInSolution:this.Property|} = 1;
var x = this.OtherProperty;
}
}
</Document>
<Document>
using System;
class D
{
string StringProperty { get; set; }
int field;
void N()
{
this.StringProperty = string.Empty;
this.field = 0; // ensure qualification isn't removed
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
int Property { get; set; }
int OtherProperty { get; set; }
void M()
{
Property = 1;
var x = OtherProperty;
}
}
</Document>
<Document>
using System;
class D
{
string StringProperty { get; set; }
int field;
void N()
{
StringProperty = string.Empty;
this.field = 0; // ensure qualification isn't removed
}
}
</Document>
</Project>
</Workspace>";
var options = OptionsSet(
Tuple.Create((IOption)CodeStyleOptions.QualifyPropertyAccess, false, NotificationOption.Suggestion),
Tuple.Create((IOption)CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Suggestion));
await TestAsync(
initialMarkup: input,
expectedMarkup: expected,
options: options,
compareTokens: false,
fixAllActionEquivalenceKey: CSharpFeaturesResources.Remove_this_qualification);
}
#endregion
}
}
| |
/*
* Created by SharpDevelop.
* User: Anthony
* Date: 5/16/2007
* Time: 12:56 AM
*
*/
using System;
using System.Threading;
using LibHid;
namespace LibUSBLauncher
{
/// <summary>
/// Description of RocketLauncher.
/// </summary>
public class RocketBabyLauncher : USBLauncher
{
#region Private Data
private int _dataSize = 9;
private byte[] _data;
private int _firingTimes;
private bool _primeAfterFire;
protected static int _productId = 0x0701;
protected static int _vendorId = 0x0A81;
private Thread _workerThread = null;
private System.Timers.Timer _requestStatusTimer = new System.Timers.Timer(100);
private int _lastRead1;
private int _lastRead2;
#endregion
#region Constants
/// <summary>
/// These are the hex values that achieve specific known results for the DreamCheeky
/// USB Rocket Launcher
/// </summary>
private struct WriteConstants
{
public const int STOP = 0x20;
public const int UP = 0x02;
public const int DOWN = 0x01;
public const int LEFT = 0x04;
//public const int UP_LEFT = 0x05;
//public const int DOWN_LEFT = 0x06;
public const int RIGHT = 0x08;
//public const int UP_RIGHT = 0x09;
public const int FIRE = 0x10;
//public const int DOWN_RIGHT = 0x0A;
//public const int SLOW_LEFT =0x07;
//public const int SLOW_RIGHT = 0x0B;
//public const int SLOW_UP = 0x0D;
//public const int SLOW_DOWN = 0x0E;
//public const int FIRE_LEFT = 0x14;
//public const int FIRE_RIGHT = 0x18;
//public const int FIRE_UP_LEFT = 0x15;
//public const int FIRE_UP_RIGHT = 0x19;
//public const int FIRE_DOWN_RIGHT = 0x1A;
public const int REQUEST_STATUS = 0x40;
//public const int REQUEST_TYPE = 0x21;
//public const int REQUEST_VAL = 0x0000200;
}
/// <summary>
/// Known status codes that are returned from a bulkread to the DreamCheeky USB
/// Rocket Launcher
/// </summary>
private struct ReadConstants
{
public const int FULL_LEFT = 0x4; //in second byte
public const int FULL_RIGHT = 0x8; //in second byte
public const int FULL_DOWN = 0x40; //in first byte
public const int FULL_UP = 0x80; //in first byte
public const int PRIME_DONE = 0x80; //in second byte
public const int FULL_LEFT_PRIME_DONE = 0x84; //in second byte
public const int FULL_RIGHT_PRIME_DONE = 0x88; //in second byte
}
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="usb"></param>
public RocketBabyLauncher(UsbHidPort port) : base(port)
{
_data = new byte[_dataSize];
Port.VendorId = VendorId;
Port.ProductId = ProductId;
Port.CheckDevicePresent();
if (Port.SpecifiedDevice != null)
{
Port.SpecifiedDevice.DataRecieved += new LibHid.DataRecievedEventHandler(onDataReceived);
_requestStatusTimer.AutoReset = true;
_requestStatusTimer.Enabled = true;
_requestStatusTimer.Elapsed += new System.Timers.ElapsedEventHandler(_requestStatusTimer_Elapsed);
}
}
void _requestStatusTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.PerformCustomCommand(WriteConstants.REQUEST_STATUS);
}
#endregion
#region Properties
/// <summary>
/// Returns the productId in integer form.
/// </summary>
/// <example>Call ProductId.ToString("X") to get Hex equivalent</example>
public static int ProductId
{
get { return _productId; }
}
/// <summary>
/// Returns the vendor id in integer form
/// </summary>
/// <example>Call ProductId.ToString("X") to get Hex equivalent</example>
public static int VendorId
{
get { return _vendorId; }
}
/// <summary>
/// Tells the launcher whether or not it should prime the air tank after fire.
/// </summary>
public bool PrimeAfterFire
{
get { return _primeAfterFire; }
set { _primeAfterFire = value; }
}
#endregion
#region Public Overridden Methods
/// <summary>
/// Sends a hexidecimal value to the rocket launcher to achieve an action
/// </summary>
/// <param name="command">The hex constant of the command you wish to achieve</param>
/// <returns>True if successful, false if not</returns>
/// <example>mLauncher.PerformCustomCommand(RocketLauncher.WriteConstants.FIRE)</example>
public override bool PerformCustomCommand(int command)
{
//if(!Enabled)
// return false;
byte[] data = new byte[_dataSize];
data[1] = (byte)command;
//if(command != _command)
//{
Port.SpecifiedDevice.SendData(data);
//}
//_command = command;
return true;
}
/// <summary>
/// Moves the launcher up
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool MoveUp()
{
//if(_verticalStatus == Status.FullUp)
// return Stop();
return PerformCustomCommand(WriteConstants.UP);
}
/// <summary>
/// Move the launcher down.
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool MoveDown()
{
//if(_verticalStatus == Status.FullDown)
// return Stop();
return PerformCustomCommand(WriteConstants.DOWN);
}
/// <summary>
/// Move the launcher left.
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool MoveLeft()
{
//if(_horizontalStatus == Status.FullLeft)
// return Stop();
//if(Slow)
// return PerformCustomCommand(WriteConstants.SLOW_LEFT);
//else if(FireWhileMoving)
// return PerformCustomCommand(WriteConstants.FIRE_LEFT);
//else
return PerformCustomCommand(WriteConstants.LEFT);
}
/// <summary>
/// Moves the launcher right.
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool MoveRight()
{
//if(_horizontalStatus == Status.FullRight)
// return Stop();
//if(Slow)
// return PerformCustomCommand(WriteConstants.SLOW_RIGHT);
//else if(FireWhileMoving)
// return PerformCustomCommand(WriteConstants.FIRE_RIGHT);
//else
return PerformCustomCommand(WriteConstants.RIGHT);
}
/// <summary>
/// Moves the launcher up and left simultaneously
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool MoveUpLeft()
{
///if(_horizontalStatus == Status.FullLeft)
// return MoveUp();
//if(_verticalStatus == Status.FullUp)
// return MoveLeft();
return false;
//return PerformCustomCommand(FireWhileMoving ? WriteConstants.FIRE_UP_LEFT : WriteConstants.UP_LEFT);
}
/// <summary>
/// Moves the launcher up and right simultaneously
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool MoveUpRight()
{
//if(_horizontalStatus == Status.FullRight)
// return MoveUp();
//if(_verticalStatus == Status.FullUp)
// return MoveRight();
return false;
//return PerformCustomCommand(FireWhileMoving ? WriteConstants.FIRE_UP_RIGHT : WriteConstants.UP_RIGHT);
}
/// <summary>
/// Move the launcher down and left simultaneously
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool MoveDownLeft()
{
//if(_horizontalStatus == Status.FullLeft)
// return MoveDown();
//if(_verticalStatus == Status.FullDown)
// return MoveLeft();
return false;
//return PerformCustomCommand(WriteConstants.DOWN_LEFT);
}
/// <summary>
/// Move the launcher down and right simultaneously
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool MoveDownRight()
{
//if(_horizontalStatus == Status.FullRight)
// return MoveDown();
//if(_verticalStatus == Status.FullDown)
// return MoveRight();
return false;
//return PerformCustomCommand(FireWhileMoving ? WriteConstants.FIRE_DOWN_RIGHT : WriteConstants.DOWN_RIGHT);
}
/// <summary>
/// Fires the launcher once
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool Fire()
{
return Fire(1);
}
/// <summary>
/// Fire the launcher more than once
/// </summary>
/// <param name="times">number of times to fire</param>
/// <returns>True if successful, false if not</returns>
public override bool Fire(int times)
{
_firingTimes = times;
if(_workerThread != null)
{
if(_workerThread.ThreadState == ThreadState.Running)
_workerThread.Abort();
_workerThread = null;
Thread.Sleep(500);
}
_workerThread = new Thread(new ThreadStart(fireHelper));
_workerThread.Start();
return true;
}
/// <summary>
/// Sends the kill command to stop whatever command is currently operating
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool Stop()
{
return PerformCustomCommand(WriteConstants.STOP);
}
/// <summary>
/// Overloads ToString just to provide something to know which kind of launcher
/// we have
/// </summary>
/// <returns>A description of the device</returns>
public override string ToString()
{
return "RocketBaby USB Rocket Launcher";
}
/// <summary>
/// Reads the status bytes off of the device, and updates
/// the objects enumerated horizontal, vertical, and firing
/// Status property to some meaningful value
/// </summary>
/// <returns>True if successful, false if not</returns>
public override bool UpdateStatus()
{
int b1 = _data[0];
int b2 = _data[1];
Log.Instance.Out(b1.ToString("X") + "\t" + b2.ToString("X"));
switch(b1)
{
case 0x00:
_verticalStatus = Status.Normal;
break;
case ReadConstants.FULL_DOWN:
_verticalStatus = Status.FullDown;
break;
case ReadConstants.FULL_UP:
_verticalStatus = Status.FullUp;
break;
default:
_verticalStatus = Status.Unknown;
Log.Instance.Out("Unknown Data in First Reading Byte: " + b1.ToString("X"));
break;
}
switch(b2)
{
case 0x00:
_horizontalStatus = Status.Normal;
_firingStatus = Status.DoneFiring;
break;
case ReadConstants.FULL_LEFT:
if(_lastRead2 == ReadConstants.FULL_LEFT_PRIME_DONE)
_firingStatus = Status.DoneFiring;
_horizontalStatus = Status.FullLeft;
break;
case ReadConstants.FULL_RIGHT:
if(_lastRead2 == ReadConstants.FULL_RIGHT_PRIME_DONE)
_firingStatus = Status.DoneFiring;
_horizontalStatus = Status.FullRight;
break;
case ReadConstants.PRIME_DONE:
if(_firingStatus == Status.DonePriming)
_horizontalStatus = Status.Normal;
_firingStatus = Status.DonePriming;
break;
case ReadConstants.FULL_LEFT_PRIME_DONE:
_horizontalStatus = Status.FullLeft;
_firingStatus = Status.DonePriming;
break;
case ReadConstants.FULL_RIGHT_PRIME_DONE:
_horizontalStatus = Status.FullRight;
_firingStatus = Status.DonePriming;
break;
default:
_horizontalStatus = Status.Unknown;
Log.Instance.Out("Unknown Data in Second Reading Byte: " + b2.ToString("X"));
break;
}
switch(_command)
{
case WriteConstants.UP:
if(_verticalStatus == Status.FullUp) Stop();
break;
case WriteConstants.DOWN:
if(_verticalStatus == Status.FullDown) Stop();
break;
case WriteConstants.LEFT:
if(_horizontalStatus == Status.FullLeft) Stop();
break;
case WriteConstants.RIGHT:
if(_horizontalStatus == Status.FullRight) Stop();
break;
///case WriteConstants.UP_LEFT:
// if(_horizontalStatus == Status.FullLeft) MoveUp();
// else if(_verticalStatus == Status.FullUp) MoveLeft();
// break;
//case WriteConstants.UP_RIGHT:
// if(_horizontalStatus == Status.FullRight) MoveUp();
// else if(_verticalStatus == Status.FullUp) MoveRight();
// break;
//case WriteConstants.DOWN_LEFT:
// if(_horizontalStatus == Status.FullLeft) MoveDown();
// else if(_verticalStatus == Status.FullDown) MoveLeft();
// break;
//case WriteConstants.DOWN_RIGHT:
// if(_horizontalStatus == Status.FullRight) MoveDown();
// else if(_verticalStatus == Status.FullDown) MoveRight();
// break;
}
_lastRead1 = b1;
_lastRead2 = b2;
return true;
}
/// <summary>
/// Attempts to fill the air tank as much as possible without firing
/// </summary>
/// <returns>True if successful, false if not, but not always reliable since its threaded</returns>
public bool Prime()
{
if(_workerThread != null)
{
if(_workerThread.ThreadState == ThreadState.Running)
_workerThread.Abort();
_workerThread = null;
Thread.Sleep(500);
}
_workerThread = new Thread(new ThreadStart(primeHelper));
_workerThread.Start();
return true;
}
//TODO: Implement!
/// <summary>
/// Not yet implemented, but will one day calibrate the device to
/// its absolute center position
/// </summary>
/// <returns>false, not yet implemented</returns>
public override bool Center()
{
return false;
}
/// <summary>
/// Closes the connection and related threads to the launcher
/// </summary>
public override void Close()
{
if(_workerThread != null)
{
_workerThread.Abort();
_workerThread = null;
}
base.Close();
}
/// <summary>
/// Suspends timers and threads related to the launcher
/// </summary>
public override void Pause()
{
base.Pause();
if(_workerThread != null && _workerThread.ThreadState == ThreadState.Running)
_workerThread.Suspend();
}
/// <summary>
/// Starts back suspended timers and threads related to the launcher
/// </summary>
public override void Continue()
{
base.Continue();
if(_workerThread != null && _workerThread.ThreadState == ThreadState.Suspended)
_workerThread.Start();
}
#endregion
#region Private Methods
/// <summary>
/// A helper method call on by a Thread so that we can return interactivity to the user
/// </summary>
private void fireHelper()
{
for(int i = 0; i<_firingTimes; i++)
{
primeHelper();
PerformCustomCommand(WriteConstants.FIRE);
while(true)
{
if(_firingStatus == Status.DoneFiring)
{
Stop();
Thread.Sleep(500);
if(PrimeAfterFire)
primeHelper();
return;
}
}
}
}
/// <summary>
/// A helper method called by a thread to prime the air tank so we can
/// return interactivity to the user
/// </summary>
private void primeHelper()
{
if(_firingStatus == Status.DonePriming)
return;
PerformCustomCommand(WriteConstants.FIRE);
while(true)
{
if(_firingStatus == Status.DonePriming)
{
Stop();
return;
}
}
}
#endregion
private void onDataReceived(object sender, LibHid.DataRecievedEventArgs e)
{
_data = e.data;
this.UpdateStatus();
}
}
}
| |
using Content.Client.UserInterface.Controls;
using Content.Client.UserInterface.Stylesheets;
using Content.Client.Utility;
using Robust.Client.Graphics.Drawing;
using Robust.Client.Interfaces;
using Robust.Client.Interfaces.UserInterface;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.Interfaces.Network;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using static Content.Client.StaticIoC;
namespace Content.Client.State
{
public class LauncherConnecting : Robust.Client.State.State
{
[Dependency] private readonly IUserInterfaceManager _userInterfaceManager = default!;
[Dependency] private readonly IStylesheetManager _stylesheetManager = default!;
[Dependency] private readonly IClientNetManager _clientNetManager = default!;
[Dependency] private readonly IGameController _gameController = default!;
[Dependency] private readonly IBaseClient _baseClient = default!;
private Control _control;
private Label _connectStatus;
private Control _connectingStatus;
private Control _connectFail;
private Label _connectFailReason;
private Control _disconnected;
public override void Startup()
{
var panelTex = ResC.GetTexture("/Textures/Interface/Nano/button.svg.96dpi.png");
var back = new StyleBoxTexture
{
Texture = panelTex,
Modulate = new Color(32, 32, 48),
};
back.SetPatchMargin(StyleBox.Margin.All, 10);
Button exitButton;
Button reconnectButton;
Button retryButton;
var address = _gameController.LaunchState.Ss14Address ?? _gameController.LaunchState.ConnectAddress;
_control = new Control
{
Stylesheet = _stylesheetManager.SheetSpace,
Children =
{
new PanelContainer
{
PanelOverride = back
},
new VBoxContainer
{
SeparationOverride = 0,
CustomMinimumSize = (300, 200),
Children =
{
new HBoxContainer
{
Children =
{
new MarginContainer
{
MarginLeftOverride = 8,
Children =
{
new Label
{
Text = Loc.GetString("Space Station 14"),
StyleClasses = {StyleBase.StyleClassLabelHeading},
VAlign = Label.VAlignMode.Center
},
}
},
(exitButton = new Button
{
Text = Loc.GetString("Exit"),
SizeFlagsHorizontal = Control.SizeFlags.ShrinkEnd | Control.SizeFlags.Expand
}),
}
},
// Line
new HighDivider(),
new MarginContainer
{
SizeFlagsVertical = Control.SizeFlags.FillExpand,
MarginLeftOverride = 4,
MarginRightOverride = 4,
MarginTopOverride = 4,
Children =
{
new VBoxContainer
{
SeparationOverride = 0,
Children =
{
new Control
{
SizeFlagsVertical = Control.SizeFlags.FillExpand,
Children =
{
(_connectingStatus = new VBoxContainer
{
SeparationOverride = 0,
Children =
{
new Label
{
Text = Loc.GetString("Connecting to server..."),
Align = Label.AlignMode.Center,
},
(_connectStatus = new Label
{
StyleClasses = {StyleBase.StyleClassLabelSubText},
Align = Label.AlignMode.Center,
}),
}
}),
(_connectFail = new VBoxContainer
{
Visible = false,
SeparationOverride = 0,
Children =
{
(_connectFailReason = new Label
{
Align = Label.AlignMode.Center
}),
(retryButton = new Button
{
Text = "Retry",
SizeFlagsHorizontal = Control.SizeFlags.ShrinkCenter,
SizeFlagsVertical =
Control.SizeFlags.Expand |
Control.SizeFlags.ShrinkEnd
})
}
}),
(_disconnected = new VBoxContainer
{
SeparationOverride = 0,
Children =
{
new Label
{
Text = "Disconnected from server:",
Align = Label.AlignMode.Center
},
new Label
{
Text = _baseClient.LastDisconnectReason,
Align = Label.AlignMode.Center
},
(reconnectButton = new Button
{
Text = "Reconnect",
SizeFlagsHorizontal = Control.SizeFlags.ShrinkCenter,
SizeFlagsVertical =
Control.SizeFlags.Expand |
Control.SizeFlags.ShrinkEnd
})
}
})
}
},
// Padding.
new Control {CustomMinimumSize = (0, 8)},
new Label
{
Text = address,
StyleClasses = {StyleBase.StyleClassLabelSubText},
SizeFlagsHorizontal = Control.SizeFlags.ShrinkCenter,
}
}
},
}
},
// Line
new PanelContainer
{
PanelOverride = new StyleBoxFlat
{
BackgroundColor = Color.FromHex("#444"),
ContentMarginTopOverride = 2
},
},
new MarginContainer
{
MarginLeftOverride = 12,
MarginRightOverride = 4,
Children =
{
new HBoxContainer
{
SizeFlagsVertical = Control.SizeFlags.ShrinkEnd,
Children =
{
new Label
{
Text = Loc.GetString("Don't die!"),
StyleClasses = {StyleBase.StyleClassLabelSubText}
},
new Label
{
Text = "ver 0.1",
SizeFlagsHorizontal =
Control.SizeFlags.Expand | Control.SizeFlags.ShrinkEnd,
StyleClasses = {StyleBase.StyleClassLabelSubText}
}
}
}
}
},
}
},
}
};
_userInterfaceManager.StateRoot.AddChild(_control);
LayoutContainer.SetAnchorPreset(_control, LayoutContainer.LayoutPreset.Center);
LayoutContainer.SetGrowHorizontal(_control, LayoutContainer.GrowDirection.Both);
LayoutContainer.SetGrowVertical(_control, LayoutContainer.GrowDirection.Both);
exitButton.OnPressed += args =>
{
_gameController.Shutdown("Exit button pressed");
};
void Retry(BaseButton.ButtonEventArgs args)
{
_baseClient.ConnectToServer(_gameController.LaunchState.ConnectEndpoint);
SetActivePage(Page.Connecting);
}
reconnectButton.OnPressed += Retry;
retryButton.OnPressed += Retry;
_clientNetManager.ConnectFailed += (sender, args) =>
{
_connectFailReason.Text = Loc.GetString("Failed to connect to server:\n{0}", args.Reason);
SetActivePage(Page.ConnectFailed);
};
_clientNetManager.ClientConnectStateChanged += ConnectStateChanged;
SetActivePage(Page.Connecting);
ConnectStateChanged(_clientNetManager.ClientConnectState);
}
private void ConnectStateChanged(ClientConnectionState state)
{
_connectStatus.Text = Loc.GetString(state switch
{
ClientConnectionState.NotConnecting => "You should not be seeing this",
ClientConnectionState.ResolvingHost => "Resolving server address...",
ClientConnectionState.EstablishingConnection => "Establishing initial connection...",
ClientConnectionState.Handshake => "Doing handshake...",
ClientConnectionState.Connected => "Synchronizing game state...",
_ => state.ToString()
});
}
public override void Shutdown()
{
_control.Dispose();
}
public void SetDisconnected()
{
SetActivePage(Page.Disconnected);
}
private void SetActivePage(Page page)
{
_connectingStatus.Visible = page == Page.Connecting;
_connectFail.Visible = page == Page.ConnectFailed;
_disconnected.Visible = page == Page.Disconnected;
}
private enum Page
{
Connecting,
ConnectFailed,
Disconnected,
}
}
}
| |
using System;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Web.UI;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix;
using GuruComponents.Netrix.WebEditing;
namespace GuruComponents.Netrix.TableDesigner
{
/// <summary>
/// This class builds a complete description of the current table with information
/// about the cells, merge / split conditions. It contains methods to check the
/// number of cells per row and per columns and some helper properties.
/// </summary>
public class TableLayoutInfo : ITableLayoutInfo
{
internal struct CellCoordinate
{
internal int x;
internal int y;
internal int w;
internal int h;
internal int r;
internal int b;
internal int row;
internal int col;
internal bool GetHit(int XHit, int YHit, int XLeftTolerance, int XRightTolerance, int YTopTolerance, int YBottomTolerance, ref int HitRow, ref int HitCol)
{
if ((x >= XHit - XLeftTolerance && x <= XHit + XRightTolerance)
&&
(y >= YHit - YTopTolerance && y <= YHit + YBottomTolerance))
{
HitRow = row;
HitCol = col;
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// The cell collection, Keys are cells, Values are <see cref="Pair"/> objects
/// containing row and col information.
/// </summary>
private IDictionary _cells;
/// <summary>
/// The list of rows, each contains a list of cells.
/// </summary>
private ArrayList _rows;
/// <summary>
/// The cell coordinates, used to check for mouse pointer selection much faster
/// </summary>
internal ArrayList CellCoordinates;
/// <summary>
/// The underlying table this object belongs to.
/// </summary>
private Interop.IHTMLTable _table;
/// <summary>
/// Gives access to the underlaying table structure
/// </summary>
public Interop.IHTMLTable Table
{
get
{
return this._table;
}
}
/// <summary>
/// Adds a cell to the specified row
/// </summary>
/// <param name="rowIndex"></param>
/// <param name="cell"></param>
public void AddCell(int rowIndex, Interop.IHTMLTableCell cell)
{
ArrayList currentRow;
int row;
int colSpan;
int colIndex;
int rowSpanCount;
ArrayList cellList;
currentRow = (ArrayList) this._rows[rowIndex];
row = 0;
while (row < currentRow.Count && currentRow[row] != null)
row++;
colSpan = 0;
while (colSpan < cell.colSpan)
{
colIndex = row + colSpan;
this.EnsureIndex(currentRow, colIndex);
currentRow[colIndex] = cell;
if (!(this._cells.Contains(cell)))
this._cells[cell] = new Pair(rowIndex, colIndex);
rowSpanCount = 1;
while (rowSpanCount < cell.rowSpan)
{
if (rowIndex + 1 >= this._rows.Count)
this._rows.Add(new ArrayList());
cellList = (ArrayList) this._rows[rowIndex + rowSpanCount];
this.EnsureIndex(cellList, colIndex);
cellList[colIndex] = cell;
if (!(this._cells.Contains(cell)))
this._cells[cell] = new Pair(rowIndex + rowSpanCount, colIndex);
rowSpanCount++;
}
colSpan++;
}
CellCoordinate cc = new CellCoordinate();
cc.row = (int) ((Pair) this._cells[cell]).First;
cc.col = (int) ((Pair) this._cells[cell]).Second;
cc.x = ((Interop.IHTMLElement) cell).GetOffsetLeft();
cc.y = ((Interop.IHTMLElement) cell).GetOffsetTop();
cc.w = ((Interop.IHTMLElement) cell).GetOffsetWidth();
cc.h = ((Interop.IHTMLElement) cell).GetOffsetHeight();
cc.r = cc.x + cc.w;
cc.b = cc.y + cc.h;
this.CellCoordinates.Add(cc);
}
/// <summary>
/// Creates the internal table layout from current table
/// </summary>
/// <param name="table"></param>
public TableLayoutInfo (Interop.IHTMLTable table)
{
this._table = table;
int i = table.rows.GetLength();
this._rows = new ArrayList (i);
for (int j = 0; j < i; j++)
{
this._rows.Add (new ArrayList ());
}
this._cells = new HybridDictionary();
this.CellCoordinates = new ArrayList();
}
/// <summary>
/// Enhances the current list with null elements to increase capacity
/// </summary>
/// <param name="list"></param>
/// <param name="index"></param>
private void EnsureIndex (ArrayList list, int index)
{
int i = index - (list.Count - 1);
for (int j = 0; j < i; j++)
{
list.Add (null);
}
}
/// <summary>
/// Retrieves the cell at given coordinates
/// </summary>
/// <param name="row">row index</param>
/// <param name="col">column index</param>
/// <returns>cell element</returns>
public Interop.IHTMLTableCell Item (int row, int col)
{
if ((row >= this._rows.Count) || (row < 0))
{
return null;
}
ArrayList arrayList = (ArrayList) this._rows[row];
if ((col >= arrayList.Count) || (col < 0))
{
return null;
}
return (Interop.IHTMLTableCell) arrayList[col];
}
/// <summary>
/// Total number of rows.
/// </summary>
/// <returns></returns>
public int GetRowNumber()
{
return this._rows.Count;
}
/// <summary>
/// Total number of cols in the given row.
/// </summary>
/// <param name="row">Row number to check</param>
/// <returns></returns>
public int GetColNumber(int row)
{
return ((ArrayList) this._rows[row]).Count;
}
/// <summary>
/// Returns the real cells of a specific row. This method behaves on the
/// real number of cells, which is sometimes smaller than the absolute number
/// due to rowspan attributes in previous rows.
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public HybridDictionary CellCollectionFromRow(int row)
{
HybridDictionary cells = new HybridDictionary();
foreach(Interop.IHTMLTableCell tc in this._cells.Keys)
{
if ((int)((Pair)this._cells[tc]).First == row)
{
cells.Add(tc, this._cells[tc]);
}
}
return cells;
}
/// <summary>
/// Returns the real cells of a specific column. This method behaves on the
/// real number of cells, which is sometimes smaller than the absolute number
/// due to colspan attributes in previous rows.
/// </summary>
/// <param name="col">Column from which the collection is retrieved.</param>
/// <returns></returns>
public HybridDictionary CellCollectionFromCol(int col)
{
HybridDictionary cells = new HybridDictionary();
foreach(Interop.IHTMLTableCell tc in this._cells.Keys)
{
if ((int)((Pair)this._cells[tc]).Second == col)
{
cells.Add(tc, this._cells[tc]);
}
}
return cells;
}
/// <summary>
/// Cell collection to be used elsewhere.
/// </summary>
public IDictionary Cells
{
get
{
return this._cells;
}
}
/// <summary>
/// Returns the coordinates of a given cell element
/// </summary>
/// <param name="cell">Cell element to check</param>
/// <param name="row">row index</param>
/// <param name="col">column index</param>
public void GetCellPoint (Interop.IHTMLTableCell cell, ref int row, ref int col)
{
Pair pair = (Pair) this._cells [cell];
if (pair != null)
{
row = (int) pair.First;
col = (int) pair.Second;
return;
}
row = -1;
col = -1;
return;
}
/// <summary>
/// Returns a string representation of the table
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb;
int currentRow;
ArrayList rowElements;
int r1;
int r2;
Interop.IHTMLElement el;
string content;
sb = new StringBuilder();
currentRow = 0;
while (currentRow < this._rows.Count)
{
rowElements = (ArrayList) this._rows[currentRow];
r1 = 0;
while (r1 < rowElements.Count)
{
sb.Append("----------");
r1++;
}
sb.Append(Environment.NewLine);
r2 = 0;
while (r2 < rowElements.Count)
{
el = (Interop.IHTMLElement) rowElements[r2];
if (el != null)
{
sb.Append("|");
content = el.GetInnerHTML();
if (content != null)
{
sb.Append(content.Substring(0, Math.Min(content.Length, 8)));
r2++;
continue;
}
sb.Append("empty");
}
else
sb.Append("| null ");
r2++;
}
sb.Append("|");
sb.Append(Environment.NewLine);
currentRow++;
}
return sb.ToString();
}
}
}
| |
using System;
using System.IO;
using UnityEngine;
public class FileUtils
{
// private const string CONFIG_DIRECTORY_NAME = "Resources/Configs";
public delegate void ConfigFileEntryParseCallback(string baseKey, string subKey, string val, object userData);
public static string PersistentDataPath
{
get
{
string PathURL = //Application.streamingAssetsPath;
#if UNITY_ANDROID
Application.streamingAssetsPath+"/";
#elif UNITY_IPHONE
Application.dataPath + "/Raw/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
"file://" + Application.dataPath + "/StreamingAssets/";
#else
string.Empty;
#endif
return PathURL;
}
}
public static string ConfigDataPath
{
get
{
return Application.dataPath+"/Configs/";
}
}
//-----------------------------------------------------------------
public static string GetPathUnderAssets(DirectoryInfo folder)
{
return FileUtils.GetPathUnderAssets(folder.FullName);
}
public static string GetPathUnderAssets(FileInfo fileInfo)
{
return FileUtils.GetPathUnderAssets(fileInfo.FullName);
}
public static string GetPathUnderAssets(string path)
{
string text = path.Replace("\\", "/");
int num = text.IndexOf("/Assets", 5);
return text.Remove(0, num + 8);
}
public static string GetFullPathOfAssets(string addPath)
{
return Application.dataPath+"/"+addPath;
}
public static string GetFullBundleTempPath(string underPath)
{
return GetFullPathOfAssets("Resources/Temp/"+underPath);
}
public static string GetFullResourcesPath(string underPath)
{
return GetFullPathOfAssets("Resources/"+underPath);
}
public static string GetPathUnderResources(string path)
{
string text = path.Replace("\\", "/");
int num = text.IndexOf("/Resources", 5);
return text.Remove(0, num + 11);
}
//----------------------------------------------------------------
public static string MakeMetaPathFromSourcePath(string path)
{
return string.Format("{0}.meta", path);
}
public static string MakeSourceAssetMetaPath(string path)
{
string path2 = FileUtils.GetPathUnderAssets(path);
return FileUtils.MakeMetaPathFromSourcePath(path2);
}
//----------------------------------------------------------------
public static string GameToSourceAssetPath(string path, string ext = "prefab")
{
return string.Format("{0}.{1}", path, ext);
}
public static string GameToSourceAssetName(string folder, string name, string ext = "prefab")
{
return string.Format("{0}/{1}.{2}", folder, name, ext);
}
//----------------------------------------------------------------
public static string SourceToGameAssetPath(string path)
{
int num = path.LastIndexOf('.');
return path.Substring(0, num);
}
public static string SourceToGameAssetName(string path)
{
int num = path.LastIndexOf('/');
int num2 = path.LastIndexOf('.');
return path.Substring(num + 1, num2);
}
//----------------------------------------------------------------
public static string GetAssetPath(string fileName)
{
return fileName;
}
//----------------------------------------------------------------
public static void GetLastFolderAndFileFromPath(string path, out string folderName, out string fileName)
{
folderName = null;
fileName = null;
if (string.IsNullOrEmpty(path))
{
return;
}
path = path.Replace("\\", "/");
int length = path.Length;
int num = path.LastIndexOf("/");
if (num < 0)
{
fileName = path;
return;
}
if (length == 1)
{
return;
}
if (num == length - 1)
{
folderName = path.Remove(length - 1, 1);
return;
}
int num2 = num + 1;
fileName = path.Substring(num2, length - num2);
if (num == 0)
{
return;
}
folderName = path.Substring(0, num);
int num3 = folderName.LastIndexOf("/");
if (num3 < 0)
{
return;
}
int num4 = num3 + 1;
folderName = folderName.Substring(num4, folderName.Length - num4);
}
//----------------------------------------------------------------
public static bool ParseConfigFile(string filePath, FileUtils.ConfigFileEntryParseCallback callback)
{
return FileUtils.ParseConfigFile(filePath, callback, null);
}
public static bool ParseConfigFile(string filePath, FileUtils.ConfigFileEntryParseCallback callback, object userData)
{
if (callback == null)
{
Debug.LogWarning("FileUtils.ParseConfigFile() - no callback given");
return false;
}
if (!File.Exists(filePath))
{
Debug.LogWarning(string.Format("FileUtils.ParseConfigFile() - file {0} does not exist", filePath));
return false;
}
int num = 1;
using (StreamReader streamReader = File.OpenText(filePath))
{
string baseKey = string.Empty;
while (streamReader.Peek() != -1)
{
string text = streamReader.ReadLine().Trim();
if (text.Length >= 1)
{
if (text.ToCharArray()[0] != ';')
{
if (text.ToCharArray()[0] == '[')
{
if (text.ToCharArray()[(text.Length - 1)] != ']')
{
Debug.LogWarning(string.Format("FileUtils.ParseConfigFile() - bad key name \"{0}\" on line {1} in file {2}", text, num, filePath));
}
else
{
baseKey = text.Substring(1, text.Length - 2);
}
}
else
{
if (!text.Contains("="))
{
Debug.LogWarning(string.Format("FileUtils.ParseConfigFile() - bad value pair \"{0}\" on line {1} in file {2}", text, num, filePath));
}
else
{
string[] array = text.Split(new char[]
{
'='
});
string subKey = array[0].Trim();
string text2 = array[1].Trim();
if (text2.ToCharArray()[0] == '"' && text2.ToCharArray()[(text2.Length - 1)] == '"')
{
text2 = text2.Substring(1, text2.Length - 2);
}
callback(baseKey, subKey, text2, userData);
}
}
}
}
}
}
return true;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// TaskOperations operations.
/// </summary>
public partial interface ITaskOperations
{
/// <summary>
/// Adds a task to the specified job.
/// </summary>
/// <param name='jobId'>
/// The ID of the job to which the task is to be added.
/// </param>
/// <param name='task'>
/// The task to be added.
/// </param>
/// <param name='taskAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<TaskAddHeaders>> AddWithHttpMessagesAsync(string jobId, TaskAddParameter task, TaskAddOptions taskAddOptions = default(TaskAddOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the tasks that are associated with the specified job.
/// </summary>
/// <remarks>
/// For multi-instance tasks, information such as affinityId,
/// executionInfo and nodeInfo refer to the primary task. Use the list
/// subtasks API to retrieve information about subtasks.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='taskListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudTask>,TaskListHeaders>> ListWithHttpMessagesAsync(string jobId, TaskListOptions taskListOptions = default(TaskListOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Adds a collection of tasks to the specified job.
/// </summary>
/// <remarks>
/// Note that each task must have a unique ID. The Batch service may
/// not return the results for each task in the same order the tasks
/// were submitted in this request. If the server times out or the
/// connection is closed during the request, the request may have been
/// partially or fully processed, or not at all. In such cases, the
/// user should re-issue the request. Note that it is up to the user to
/// correctly handle failures when re-issuing a request. For example,
/// you should use the same task ids during a retry so that if the
/// prior operation succeeded, the retry will not create extra tasks
/// unexpectedly.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job to which the task collection is to be added.
/// </param>
/// <param name='value'>
/// The collection of tasks to add.
/// </param>
/// <param name='taskAddCollectionOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<TaskAddCollectionResult,TaskAddCollectionHeaders>> AddCollectionWithHttpMessagesAsync(string jobId, System.Collections.Generic.IList<TaskAddParameter> value, TaskAddCollectionOptions taskAddCollectionOptions = default(TaskAddCollectionOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a task from the specified job.
/// </summary>
/// <remarks>
/// When a task is deleted, all of the files in its directory on the
/// compute node where it ran are also deleted (regardless of the
/// retention time). For multi-instance tasks, the delete task
/// operation applies synchronously to the primary task; subtasks and
/// their files are then deleted asynchronously in the background.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job from which to delete the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task to delete.
/// </param>
/// <param name='taskDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<TaskDeleteHeaders>> DeleteWithHttpMessagesAsync(string jobId, string taskId, TaskDeleteOptions taskDeleteOptions = default(TaskDeleteOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets information about the specified task.
/// </summary>
/// <remarks>
/// For multi-instance tasks, information such as affinityId,
/// executionInfo and nodeInfo refer to the primary task. Use the list
/// subtasks API to retrieve information about subtasks.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task to get information about.
/// </param>
/// <param name='taskGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CloudTask,TaskGetHeaders>> GetWithHttpMessagesAsync(string jobId, string taskId, TaskGetOptions taskGetOptions = default(TaskGetOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the properties of the specified task.
/// </summary>
/// <param name='jobId'>
/// The ID of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task to update.
/// </param>
/// <param name='constraints'>
/// Constraints that apply to this task. If omitted, the task is given
/// the default constraints.
/// </param>
/// <param name='taskUpdateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<TaskUpdateHeaders>> UpdateWithHttpMessagesAsync(string jobId, string taskId, TaskConstraints constraints = default(TaskConstraints), TaskUpdateOptions taskUpdateOptions = default(TaskUpdateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the subtasks that are associated with the specified
/// multi-instance task.
/// </summary>
/// <remarks>
/// If the task is not a multi-instance task then this returns an empty
/// collection.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='taskId'>
/// The ID of the task.
/// </param>
/// <param name='taskListSubtasksOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CloudTaskListSubtasksResult,TaskListSubtasksHeaders>> ListSubtasksWithHttpMessagesAsync(string jobId, string taskId, TaskListSubtasksOptions taskListSubtasksOptions = default(TaskListSubtasksOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Terminates the specified task.
/// </summary>
/// <remarks>
/// When the task has been terminated, it moves to the completed state.
/// For multi-instance tasks, the terminate task operation applies
/// synchronously to the primary task; subtasks are then terminated
/// asynchronously in the background.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task to terminate.
/// </param>
/// <param name='taskTerminateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<TaskTerminateHeaders>> TerminateWithHttpMessagesAsync(string jobId, string taskId, TaskTerminateOptions taskTerminateOptions = default(TaskTerminateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Reactivates the specified task.
/// </summary>
/// <remarks>
/// Reactivation makes a task eligible to be retried again up to its
/// maximum retry count. The task's state is changed to active. As the
/// task is no longer in the completed state, any previous exit code or
/// scheduling error is no longer available after reactivation. This
/// will fail for tasks that are not completed or that previously
/// completed successfully (with an exit code of 0). Additionally, this
/// will fail if the job has completed (or is terminating or deleting).
/// </remarks>
/// <param name='jobId'>
/// The ID of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task to reactivate.
/// </param>
/// <param name='taskReactivateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<TaskReactivateHeaders>> ReactivateWithHttpMessagesAsync(string jobId, string taskId, TaskReactivateOptions taskReactivateOptions = default(TaskReactivateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the tasks that are associated with the specified job.
/// </summary>
/// <remarks>
/// For multi-instance tasks, information such as affinityId,
/// executionInfo and nodeInfo refer to the primary task. Use the list
/// subtasks API to retrieve information about subtasks.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='taskListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudTask>,TaskListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, TaskListNextOptions taskListNextOptions = default(TaskListNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
/*
* Copyright 2015 Alastair Wyse (https://github.com/alastairwyse/ApplicationMetrics/)
*
* 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 StandardAbstraction;
namespace ApplicationMetrics.MetricLoggers
{
/// <summary>
/// Base class which supports buffering and storing of metric events, and provides a base framework for classes which log aggregates of metric events.
/// </summary>
/// <remarks>Derived classes must implement methods which log defined metric aggregates (e.g. LogCountOverTimeUnitAggregate()). These methods are called from a worker thread after dequeueing, totalling, and logging the base metric events.</remarks>
public abstract class MetricAggregateLogger : MetricLoggerStorer, IMetricAggregateLogger
{
// Containers for metric aggregates
/// <summary>Container for aggregates which represent the number of occurrences of a count metric within the specified time unit</summary>
protected List<MetricAggregateContainer<CountMetric>> countOverTimeUnitAggregateDefinitions;
/// <summary>Container for aggregates which represent the total of an amount metric per instance of a count metric.</summary>
protected List<MetricAggregateContainer<AmountMetric, CountMetric>> amountOverCountAggregateDefinitions;
/// <summary>Container for aggregates which represent the total of an amount metric within the specified time unit.</summary>
protected List<MetricAggregateContainer<AmountMetric>> amountOverTimeUnitAggregateDefinitions;
/// <summary>Container for aggregates which represent the total of an amount metric divided by the total of another amount metric.</summary>
protected List<MetricAggregateContainer<AmountMetric, AmountMetric>> amountOverAmountAggregateDefinitions;
/// <summary>Container for aggregates which represent the total of an interval metric per instance of a count metric.</summary>
protected List<MetricAggregateContainer<IntervalMetric, CountMetric>> intervalOverAmountAggregateDefinitions;
/// <summary>Container for aggregates which represent an interval metric as a fraction of the total runtime of the logger.</summary>
/// <remarks>Note that the TimeUnit member of the MetricAggregateContainer class is not used in this case.</remarks>
protected List<MetricAggregateContainer<IntervalMetric>> intervalOverTotalRunTimeAggregateDefinitions;
/// <summary>Object containing utility methods.</summary>
protected Utilities utilities;
/// <summary>
/// Initialises a new instance of the ApplicationMetrics.MetricLoggers.MetricAggregateLogger class.
/// </summary>
/// <param name="bufferProcessingStrategy">Object which implements a processing strategy for the buffers (queues).</param>
/// <param name="intervalMetricChecking">Specifies whether an exception should be thrown if the correct order of interval metric logging is not followed (e.g. End() method called before Begin()).</param>
protected MetricAggregateLogger(IBufferProcessingStrategy bufferProcessingStrategy, bool intervalMetricChecking)
: base(bufferProcessingStrategy, intervalMetricChecking)
{
InitialisePrivateMembers();
}
/// <summary>
/// Initialises a new instance of the ApplicationMetrics.MetricLoggers.MetricAggregateLogger class. Note this is an additional constructor to facilitate unit tests, and should not be used to instantiate the class under normal conditions.
/// </summary>
/// <param name="bufferProcessingStrategy">Object which implements a processing strategy for the buffers (queues).</param>
/// <param name="intervalMetricChecking">Specifies whether an exception should be thrown if the correct order of interval metric logging is not followed (e.g. End() method called before Begin()).</param>
/// <param name="dateTime">A test (mock) DateTime object.</param>
/// <param name="stopWatch">A test (mock) Stopwatch object.</param>
protected MetricAggregateLogger(IBufferProcessingStrategy bufferProcessingStrategy, bool intervalMetricChecking, IDateTime dateTime, IStopwatch stopWatch)
: base(bufferProcessingStrategy, intervalMetricChecking, dateTime, stopWatch)
{
InitialisePrivateMembers();
}
/// <summary>
/// Starts the buffer processing (e.g. if the implementation of the buffer processing strategy uses a worker thread, this method starts the worker thread).
/// </summary>
/// <remarks>Although this method has been deprecated in base classes, in the case of MetricAggregateLogger this Start() method should be called (rather than the Start() on the IBufferProcessingStrategy implementation) as it performs additional initialization specific to MetricAggregateLogger.</remarks>
public override void Start()
{
base.Start();
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:ApplicationMetrics.MetricLoggers.IMetricAggregateLogger.DefineMetricAggregate(ApplicationMetrics.CountMetric,ApplicationMetrics.TimeUnit,System.String,System.String)"]/*'/>
public virtual void DefineMetricAggregate(CountMetric countMetric, TimeUnit timeUnit, string name, string description)
{
CheckDuplicateAggregateName(name);
countOverTimeUnitAggregateDefinitions.Add(new MetricAggregateContainer<CountMetric>(countMetric, timeUnit, name, description));
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:ApplicationMetrics.MetricLoggers.IMetricAggregateLogger.DefineMetricAggregate(ApplicationMetrics.AmountMetric,ApplicationMetrics.CountMetric,System.String,System.String)"]/*'/>
public virtual void DefineMetricAggregate(AmountMetric amountMetric, CountMetric countMetric, string name, string description)
{
CheckDuplicateAggregateName(name);
amountOverCountAggregateDefinitions.Add(new MetricAggregateContainer<AmountMetric, CountMetric>(amountMetric, countMetric, name, description));
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:ApplicationMetrics.MetricLoggers.IMetricAggregateLogger.DefineMetricAggregate(ApplicationMetrics.AmountMetric,ApplicationMetrics.TimeUnit,System.String,System.String)"]/*'/>
public virtual void DefineMetricAggregate(AmountMetric amountMetric, TimeUnit timeUnit, string name, string description)
{
CheckDuplicateAggregateName(name);
amountOverTimeUnitAggregateDefinitions.Add(new MetricAggregateContainer<AmountMetric>(amountMetric, timeUnit, name, description));
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:ApplicationMetrics.MetricLoggers.IMetricAggregateLogger.DefineMetricAggregate(ApplicationMetrics.AmountMetric,ApplicationMetrics.AmountMetric,System.String,System.String)"]/*'/>
public virtual void DefineMetricAggregate(AmountMetric numeratorAmountMetric, AmountMetric denominatorAmountMetric, string name, string description)
{
CheckDuplicateAggregateName(name);
amountOverAmountAggregateDefinitions.Add(new MetricAggregateContainer<AmountMetric, AmountMetric>(numeratorAmountMetric, denominatorAmountMetric, name, description));
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:ApplicationMetrics.MetricLoggers.IMetricAggregateLogger.DefineMetricAggregate(ApplicationMetrics.IntervalMetric,ApplicationMetrics.CountMetric,System.String,System.String)"]/*'/>
public virtual void DefineMetricAggregate(IntervalMetric intervalMetric, CountMetric countMetric, string name, string description)
{
CheckDuplicateAggregateName(name);
intervalOverAmountAggregateDefinitions.Add(new MetricAggregateContainer<IntervalMetric, CountMetric>(intervalMetric, countMetric, name, description));
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:ApplicationMetrics.MetricLoggers.IMetricAggregateLogger.DefineMetricAggregate(ApplicationMetrics.IntervalMetric,System.String,System.String)"]/*'/>
public virtual void DefineMetricAggregate(IntervalMetric intervalMetric, string name, string description)
{
CheckDuplicateAggregateName(name);
intervalOverTotalRunTimeAggregateDefinitions.Add(new MetricAggregateContainer<IntervalMetric>(intervalMetric, TimeUnit.Second, name, description));
}
#region Abstract Methods
/// <summary>
/// Logs a metric aggregate representing the number of occurrences of a count metric within the specified time unit.
/// </summary>
/// <param name="metricAggregate">The metric aggregate to log.</param>
/// <param name="totalInstances">The number of occurrences of the count metric.</param>
/// <param name="totalElapsedTimeUnits">The total elapsed time units.</param>
protected abstract void LogCountOverTimeUnitAggregate(MetricAggregateContainer<CountMetric> metricAggregate, Int64 totalInstances, Int64 totalElapsedTimeUnits);
/// <summary>
/// Logs a metric aggregate representing the total of an amount metric per occurrence of a count metric.
/// </summary>
/// <param name="metricAggregate">The metric aggregate to log.</param>
/// <param name="totalAmount">The total of the amount metric.</param>
/// <param name="totalInstances">The number of occurrences of the count metric.</param>
protected abstract void LogAmountOverCountAggregate(MetricAggregateContainer<AmountMetric, CountMetric> metricAggregate, Int64 totalAmount, Int64 totalInstances);
/// <summary>
/// Logs a metric aggregate respresenting the total of an amount metric within the specified time unit.
/// </summary>
/// <param name="metricAggregate">The metric aggregate to log.</param>
/// <param name="totalAmount">The total of the amount metric.</param>
/// <param name="totalElapsedTimeUnits">The total elapsed time units.</param>
protected abstract void LogAmountOverTimeUnitAggregate(MetricAggregateContainer<AmountMetric> metricAggregate, Int64 totalAmount, Int64 totalElapsedTimeUnits);
/// <summary>
/// Logs a metric aggregate representing the total of an amount metric divided by the total of another amount metric.
/// </summary>
/// <param name="metricAggregate">The metric aggregate to log.</param>
/// <param name="numeratorTotal">The total of the numerator amount metric.</param>
/// <param name="denominatorTotal">The total of the denominator amount metric.</param>
protected abstract void LogAmountOverAmountAggregate(MetricAggregateContainer<AmountMetric, AmountMetric> metricAggregate, Int64 numeratorTotal, Int64 denominatorTotal);
/// <summary>
/// Logs a metric aggregate representing the total of an interval metric per occurrence of a count metric.
/// </summary>
/// <param name="metricAggregate">The metric aggregate to log.</param>
/// <param name="totalInterval">The total of the interval metric.</param>
/// <param name="totalInstances">The number of occurrences of the count metric.</param>
protected abstract void LogIntervalOverCountAggregate(MetricAggregateContainer<IntervalMetric, CountMetric> metricAggregate, Int64 totalInterval, Int64 totalInstances);
/// <summary>
/// Logs a metric aggregate representing the total of an interval metric as a fraction of the total runtime of the logger.
/// </summary>
/// <param name="metricAggregate">The metric aggregate to log.</param>
/// <param name="totalInterval">The total of the interval metric.</param>
/// <param name="totalRunTime">The total run time of the logger since starting in milliseconds.</param>
protected abstract void LogIntervalOverTotalRunTimeAggregate(MetricAggregateContainer<IntervalMetric> metricAggregate, Int64 totalInterval, Int64 totalRunTime);
#endregion
#region Base Class Method Implementations
/// <summary>
/// Dequeues and logs metric events stored in the internal buffer, and logs any defined metric aggregates.
/// </summary>
protected override void DequeueAndProcessMetricEvents()
{
base.DequeueAndProcessMetricEvents();
LogCountOverTimeUnitAggregates();
LogAmountOverCountAggregates();
LogAmountOverTimeUnitAggregates();
LogAmountOverAmountAggregates();
LogIntervalOverCountMetricAggregates();
LogIntervalOverTotalRunTimeAggregates();
}
#endregion
#region Private/Protected Methods
/// <summary>
/// Initialises private members of the class.
/// </summary>
private void InitialisePrivateMembers()
{
countOverTimeUnitAggregateDefinitions = new List<MetricAggregateContainer<CountMetric>>();
amountOverCountAggregateDefinitions = new List<MetricAggregateContainer<AmountMetric, CountMetric>>();
amountOverTimeUnitAggregateDefinitions = new List<MetricAggregateContainer<AmountMetric>>();
amountOverAmountAggregateDefinitions = new List<MetricAggregateContainer<AmountMetric, AmountMetric>>();
intervalOverAmountAggregateDefinitions = new List<MetricAggregateContainer<IntervalMetric, CountMetric>>();
intervalOverTotalRunTimeAggregateDefinitions = new List<MetricAggregateContainer<IntervalMetric>>();
utilities = new Utilities();
}
/// <summary>
/// Calculates and logs the value of all defined metric aggregates representing the number of occurrences of a count metric within the specified time unit.
/// </summary>
private void LogCountOverTimeUnitAggregates()
{
foreach (MetricAggregateContainer<CountMetric> currentAggregate in countOverTimeUnitAggregateDefinitions)
{
// Calculate the value
Int64 totalInstances;
if (countMetricTotals.ContainsKey(currentAggregate.NumeratorMetricType) == true)
{
totalInstances = countMetricTotals[currentAggregate.NumeratorMetricType].TotalCount;
}
else
{
totalInstances = 0;
}
// Convert the number of elapsed milliseconds since starting to the time unit specified in the aggregate
double totalElapsedTimeUnits = stopWatch.ElapsedMilliseconds / utilities.ConvertTimeUnitToMilliSeconds(currentAggregate.DenominatorTimeUnit);
LogCountOverTimeUnitAggregate(currentAggregate, totalInstances, Convert.ToInt64(totalElapsedTimeUnits));
}
}
/// <summary>
/// Calculates and logs the value of all defined metric aggregates representing the total of an amount metric per occurrence of a count metric.
/// </summary>
private void LogAmountOverCountAggregates()
{
foreach (MetricAggregateContainer<AmountMetric, CountMetric> currentAggregate in amountOverCountAggregateDefinitions)
{
Int64 totalAmount;
if (amountMetricTotals.ContainsKey(currentAggregate.NumeratorMetricType) == true)
{
totalAmount = amountMetricTotals[currentAggregate.NumeratorMetricType].Total;
}
else
{
totalAmount = 0;
}
Int64 totalInstances;
if (countMetricTotals.ContainsKey(currentAggregate.DenominatorMetricType) == true)
{
totalInstances = countMetricTotals[currentAggregate.DenominatorMetricType].TotalCount;
}
else
{
totalInstances = 0;
}
LogAmountOverCountAggregate(currentAggregate, totalAmount, totalInstances);
}
}
/// <summary>
/// Calculates and logs the value of all defined metric aggregates representing the total of an amount metric within the specified time unit.
/// </summary>
private void LogAmountOverTimeUnitAggregates()
{
foreach (MetricAggregateContainer<AmountMetric> currentAggregate in amountOverTimeUnitAggregateDefinitions)
{
// Calculate the total
Int64 totalAmount;
if (amountMetricTotals.ContainsKey(currentAggregate.NumeratorMetricType) == true)
{
totalAmount = amountMetricTotals[currentAggregate.NumeratorMetricType].Total;
}
else
{
totalAmount = 0;
}
// Convert the number of elapsed milliseconds since starting to the time unit specified in the aggregate
double totalElapsedTimeUnits = stopWatch.ElapsedMilliseconds / utilities.ConvertTimeUnitToMilliSeconds(currentAggregate.DenominatorTimeUnit);
LogAmountOverTimeUnitAggregate(currentAggregate, totalAmount, Convert.ToInt64(totalElapsedTimeUnits));
}
}
/// <summary>
/// Calculates and logs the value of all defined metric aggregates representing the total of an amount metric divided by the total of another amount metric.
/// </summary>
private void LogAmountOverAmountAggregates()
{
foreach (MetricAggregateContainer<AmountMetric, AmountMetric> currentAggregate in amountOverAmountAggregateDefinitions)
{
Int64 numeratorTotal;
if (amountMetricTotals.ContainsKey(currentAggregate.NumeratorMetricType) == true)
{
numeratorTotal = amountMetricTotals[currentAggregate.NumeratorMetricType].Total;
}
else
{
numeratorTotal = 0;
}
Int64 denominatorTotal;
if (amountMetricTotals.ContainsKey(currentAggregate.DenominatorMetricType) == true)
{
denominatorTotal = amountMetricTotals[currentAggregate.DenominatorMetricType].Total;
}
else
{
denominatorTotal = 0;
}
LogAmountOverAmountAggregate(currentAggregate, numeratorTotal, denominatorTotal);
}
}
/// <summary>
/// Calculates and logs the value of all defined metric aggregates representing the total of an interval metric per occurrence of a count metric.
/// </summary>
private void LogIntervalOverCountMetricAggregates()
{
foreach (MetricAggregateContainer<IntervalMetric, CountMetric> currentAggregate in intervalOverAmountAggregateDefinitions)
{
Int64 totalInterval;
if (intervalMetricTotals.ContainsKey(currentAggregate.NumeratorMetricType) == true)
{
totalInterval = intervalMetricTotals[currentAggregate.NumeratorMetricType].Total;
}
else
{
totalInterval = 0;
}
Int64 totalInstances;
if (countMetricTotals.ContainsKey(currentAggregate.DenominatorMetricType) == true)
{
totalInstances = countMetricTotals[currentAggregate.DenominatorMetricType].TotalCount;
}
else
{
totalInstances = 0;
}
LogIntervalOverCountAggregate(currentAggregate, totalInterval, totalInstances);
}
}
/// <summary>
/// Calculates and logs the value of all defined metric aggregates representing the total of an interval metric as a fraction of the total runtime of the logger.
/// </summary>
private void LogIntervalOverTotalRunTimeAggregates()
{
foreach (MetricAggregateContainer<IntervalMetric> currentAggregate in intervalOverTotalRunTimeAggregateDefinitions)
{
Int64 totalInterval;
if (intervalMetricTotals.ContainsKey(currentAggregate.NumeratorMetricType) == true)
{
totalInterval = intervalMetricTotals[currentAggregate.NumeratorMetricType].Total;
}
else
{
totalInterval = 0;
}
LogIntervalOverTotalRunTimeAggregate(currentAggregate, totalInterval, stopWatch.ElapsedMilliseconds);
}
}
/// <summary>
/// Checks all aggregate containers for an existing defined aggregate with the specified name, and throws an exception if an existing aggregate is found.
/// </summary>
/// <param name="name">The aggregate name to check for.</param>
private void CheckDuplicateAggregateName(string name)
{
bool exists = false;
foreach (MetricAggregateContainer<CountMetric> currentAggregate in countOverTimeUnitAggregateDefinitions)
{
if (currentAggregate.Name == name)
{
exists = true;
}
}
foreach (MetricAggregateContainer<AmountMetric, CountMetric> currentAggregate in amountOverCountAggregateDefinitions)
{
if (currentAggregate.Name == name)
{
exists = true;
}
}
foreach (MetricAggregateContainer<AmountMetric> currentAggregate in amountOverTimeUnitAggregateDefinitions)
{
if (currentAggregate.Name == name)
{
exists = true;
}
}
foreach (MetricAggregateContainer<AmountMetric, AmountMetric> currentAggregate in amountOverAmountAggregateDefinitions)
{
if (currentAggregate.Name == name)
{
exists = true;
}
}
foreach (MetricAggregateContainer<IntervalMetric, CountMetric> currentAggregate in intervalOverAmountAggregateDefinitions)
{
if (currentAggregate.Name == name)
{
exists = true;
}
}
foreach (MetricAggregateContainer<IntervalMetric> currentAggregate in intervalOverTotalRunTimeAggregateDefinitions)
{
if (currentAggregate.Name == name)
{
exists = true;
}
}
if (exists == true)
{
throw new Exception("Metric aggregate with name '" + name + "' has already been defined.");
}
}
#endregion
#region Nested Classes
/// <summary>
/// Base class for metric aggregate containers containing common properties.
/// </summary>
/// <typeparam name="TNumerator">The type representing the numerator of the aggregate.</typeparam>
protected class MetricAggregateContainerBase<TNumerator>
{
/// <summary>The metric representing the numerator of the aggregate.</summary>
protected TNumerator numeratorMetric;
/// <summary>The name of the metric aggregate.</summary>
protected string name;
/// <summary>A description of the metric aggregate, explaining what it measures and/or represents.</summary>
protected string description;
/// <summary>
/// The type of the numerator of the metric aggregate.
/// </summary>
public Type NumeratorMetricType
{
get
{
return numeratorMetric.GetType();
}
}
/// <summary>
/// The name of the metric aggregate.
/// </summary>
public string Name
{
get
{
return name;
}
}
/// <summary>
/// A description of the metric aggregate, explaining what it measures and/or represents.
/// </summary>
public string Description
{
get
{
return description;
}
}
/// <summary>
/// Initialises a new instance of the ApplicationMetrics.MetricAggregateLogger+MetricAggregateContainerBase class.
/// </summary>
/// <param name="numeratorMetric">The metric which is the numerator of the aggregate.</param>
/// <param name="name">The name of the metric aggregate.</param>
/// <param name="description">A description of the metric aggregate, explaining what it measures and/or represents.</param>
protected MetricAggregateContainerBase(TNumerator numeratorMetric, string name, string description)
{
this.numeratorMetric = numeratorMetric;
if (name.Trim() != "")
{
this.name = name;
}
else
{
throw new ArgumentException("Argument 'name' cannot be blank.", "name");
}
if (description.Trim() != "")
{
this.description = description;
}
else
{
throw new ArgumentException("Argument 'description' cannot be blank.", "description");
}
}
}
/// <summary>
/// Container class which stores definitions of aggregates of metrics.
/// </summary>
/// <typeparam name="TNumerator">The type of the numerator of the metric aggregate.</typeparam>
/// <typeparam name="TDenominator">The type of the denominator of the metric aggregate.</typeparam>
protected class MetricAggregateContainer<TNumerator, TDenominator> : MetricAggregateContainerBase<TNumerator>
{
/// <summary>The metric representing the denominator of the aggregate.</summary>
protected TDenominator denominatorMetric;
/// <summary>
/// The type of the denominator of the metric aggregate.
/// </summary>
public Type DenominatorMetricType
{
get
{
return denominatorMetric.GetType();
}
}
/// <summary>
/// Initialises a new instance of the ApplicationMetrics.MetricAggregateLogger+MetricAggregateContainer class.
/// </summary>
/// <param name="numeratorMetric">The metric which is the numerator of the aggregate.</param>
/// <param name="denominatorMetric">The metric which is the denominator of the aggregate.</param>
/// <param name="name">The name of the metric aggregate.</param>
/// <param name="description">A description of the metric aggregate, explaining what it measures and/or represents.</param>
public MetricAggregateContainer(TNumerator numeratorMetric, TDenominator denominatorMetric, string name, string description)
: base(numeratorMetric, name, description)
{
this.denominatorMetric = denominatorMetric;
}
}
/// <summary>
/// Container class which stores definitions of aggregates of metrics where the denominator of the metric is a unit of time.
/// </summary>
/// <typeparam name="TNumerator">The type of the numerator of the metric aggregate.</typeparam>
protected class MetricAggregateContainer<TNumerator> : MetricAggregateContainerBase<TNumerator>
{
/// <summary>The time unit representing the denominator of the metric aggregate.</summary>
protected TimeUnit timeUnit;
/// <summary>
/// The time unit representing the denominator of the metric aggregate.
/// </summary>
public TimeUnit DenominatorTimeUnit
{
get
{
return timeUnit;
}
}
/// <summary>
/// Initialises a new instance of the ApplicationMetrics.MetricLoggers.MetricAggregateLogger+MetricAggregateContainer class.
/// </summary>
/// <param name="numeratorMetric">The metric which is the numerator of the aggregate.</param>
/// <param name="timeUnit">The time unit representing the denominator of the metric aggregate.</param>
/// <param name="name">The name of the metric aggregate.</param>
/// <param name="description">A description of the metric aggregate, explaining what it measures and/or represents.</param>
public MetricAggregateContainer(TNumerator numeratorMetric, TimeUnit timeUnit, string name, string description)
: base(numeratorMetric, name, description)
{
this.timeUnit = timeUnit;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Permissions {
using System.Security;
using System;
using SecurityElement = System.Security.SecurityElement;
using System.Security.Util;
using System.IO;
using System.Globalization;
using System.Diagnostics.Contracts;
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum EnvironmentPermissionAccess
{
NoAccess = 0x00,
Read = 0x01,
Write = 0x02,
AllAccess = 0x03,
}
[Serializable]
internal class EnvironmentStringExpressionSet : StringExpressionSet
{
public EnvironmentStringExpressionSet()
: base( true, null, false )
{
}
public EnvironmentStringExpressionSet( String str )
: base( true, str, false )
{
}
protected override StringExpressionSet CreateNewEmpty()
{
return new EnvironmentStringExpressionSet();
}
protected override bool StringSubsetString( String left, String right, bool ignoreCase )
{
return (ignoreCase?(String.Compare( left, right, StringComparison.OrdinalIgnoreCase) == 0):
(String.Compare( left, right, StringComparison.Ordinal) == 0));
}
protected override String ProcessWholeString( String str )
{
return str;
}
protected override String ProcessSingleString( String str )
{
return str;
}
[SecuritySafeCritical]
public override string ToString()
{
// SafeCritical: we're not storing path information in the strings, so exposing them out is fine ...
// they're just the same strings that came in to the .ctor.
return base.UnsafeToString();
}
}
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
sealed public class EnvironmentPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
{
private StringExpressionSet m_read;
private StringExpressionSet m_write;
private bool m_unrestricted;
public EnvironmentPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
m_unrestricted = true;
else if (state == PermissionState.None)
m_unrestricted = false;
else
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
public EnvironmentPermission( EnvironmentPermissionAccess flag, String pathList )
{
SetPathList( flag, pathList );
}
public void SetPathList( EnvironmentPermissionAccess flag, String pathList )
{
VerifyFlag( flag );
m_unrestricted = false;
if ((flag & EnvironmentPermissionAccess.Read) != 0)
m_read = null;
if ((flag & EnvironmentPermissionAccess.Write) != 0)
m_write = null;
AddPathList( flag, pathList );
}
[System.Security.SecuritySafeCritical] // auto-generated
public void AddPathList( EnvironmentPermissionAccess flag, String pathList )
{
VerifyFlag( flag );
if (FlagIsSet( flag, EnvironmentPermissionAccess.Read ))
{
if (m_read == null)
m_read = new EnvironmentStringExpressionSet();
m_read.AddExpressions( pathList );
}
if (FlagIsSet( flag, EnvironmentPermissionAccess.Write ))
{
if (m_write == null)
m_write = new EnvironmentStringExpressionSet();
m_write.AddExpressions( pathList );
}
}
public String GetPathList( EnvironmentPermissionAccess flag )
{
VerifyFlag( flag );
ExclusiveFlag( flag );
if (FlagIsSet( flag, EnvironmentPermissionAccess.Read ))
{
if (m_read == null)
{
return "";
}
return m_read.ToString();
}
if (FlagIsSet( flag, EnvironmentPermissionAccess.Write ))
{
if (m_write == null)
{
return "";
}
return m_write.ToString();
}
/* not reached */
return "";
}
private void VerifyFlag( EnvironmentPermissionAccess flag )
{
if ((flag & ~EnvironmentPermissionAccess.AllAccess) != 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag));
Contract.EndContractBlock();
}
private void ExclusiveFlag( EnvironmentPermissionAccess flag )
{
if (flag == EnvironmentPermissionAccess.NoAccess)
{
throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
}
if (((int)flag & ((int)flag-1)) != 0)
{
throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
}
Contract.EndContractBlock();
}
private bool FlagIsSet( EnvironmentPermissionAccess flag, EnvironmentPermissionAccess question )
{
return (flag & question) != 0;
}
private bool IsEmpty()
{
return (!m_unrestricted &&
(this.m_read == null || this.m_read.IsEmpty()) &&
(this.m_write == null || this.m_write.IsEmpty()));
}
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public bool IsUnrestricted()
{
return m_unrestricted;
}
//------------------------------------------------------
//
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
[System.Security.SecuritySafeCritical] // auto-generated
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
{
return this.IsEmpty();
}
try
{
EnvironmentPermission operand = (EnvironmentPermission)target;
if (operand.IsUnrestricted())
return true;
else if (this.IsUnrestricted())
return false;
else
return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) &&
(this.m_write == null || this.m_write.IsSubsetOf( operand.m_write )));
}
catch (InvalidCastException)
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override IPermission Intersect(IPermission target)
{
if (target == null)
{
return null;
}
else if (!VerifyType(target))
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
else if (this.IsUnrestricted())
{
return target.Copy();
}
EnvironmentPermission operand = (EnvironmentPermission)target;
if (operand.IsUnrestricted())
{
return this.Copy();
}
StringExpressionSet intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read );
StringExpressionSet intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write );
if ((intersectRead == null || intersectRead.IsEmpty()) &&
(intersectWrite == null || intersectWrite.IsEmpty()))
{
return null;
}
EnvironmentPermission intersectPermission = new EnvironmentPermission(PermissionState.None);
intersectPermission.m_unrestricted = false;
intersectPermission.m_read = intersectRead;
intersectPermission.m_write = intersectWrite;
return intersectPermission;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override IPermission Union(IPermission other)
{
if (other == null)
{
return this.Copy();
}
else if (!VerifyType(other))
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
EnvironmentPermission operand = (EnvironmentPermission)other;
if (this.IsUnrestricted() || operand.IsUnrestricted())
{
return new EnvironmentPermission( PermissionState.Unrestricted );
}
StringExpressionSet unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read );
StringExpressionSet unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write );
if ((unionRead == null || unionRead.IsEmpty()) &&
(unionWrite == null || unionWrite.IsEmpty()))
{
return null;
}
EnvironmentPermission unionPermission = new EnvironmentPermission(PermissionState.None);
unionPermission.m_unrestricted = false;
unionPermission.m_read = unionRead;
unionPermission.m_write = unionWrite;
return unionPermission;
}
public override IPermission Copy()
{
EnvironmentPermission copy = new EnvironmentPermission(PermissionState.None);
if (this.m_unrestricted)
{
copy.m_unrestricted = true;
}
else
{
copy.m_unrestricted = false;
if (this.m_read != null)
{
copy.m_read = this.m_read.Copy();
}
if (this.m_write != null)
{
copy.m_write = this.m_write.Copy();
}
}
return copy;
}
#if FEATURE_CAS_POLICY
public override SecurityElement ToXml()
{
SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.EnvironmentPermission" );
if (!IsUnrestricted())
{
if (this.m_read != null && !this.m_read.IsEmpty())
{
esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) );
}
if (this.m_write != null && !this.m_write.IsEmpty())
{
esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) );
}
}
else
{
esd.AddAttribute( "Unrestricted", "true" );
}
return esd;
}
public override void FromXml(SecurityElement esd)
{
CodeAccessPermission.ValidateElement( esd, this );
String et;
if (XMLUtil.IsUnrestricted(esd))
{
m_unrestricted = true;
return;
}
m_unrestricted = false;
m_read = null;
m_write = null;
et = esd.Attribute( "Read" );
if (et != null)
{
m_read = new EnvironmentStringExpressionSet( et );
}
et = esd.Attribute( "Write" );
if (et != null)
{
m_write = new EnvironmentStringExpressionSet( et );
}
}
#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
return EnvironmentPermission.GetTokenIndex();
}
internal static int GetTokenIndex()
{
return BuiltInPermissionIndex.EnvironmentPermissionIndex;
}
}
}
| |
//
// Bugzz - Multi GUI Desktop Bugzilla Client
//
// 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.
//
// Copyright (c) 2008 Novell, Inc.
//
// Authors:
// Andreia Gaita (avidigal@novell.com)
// Marek Habersack (mhabersack@novell.com)
//
using System;
using SGC=System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using C5;
using Bugzz;
using Bugzz.Network;
using HtmlAgilityPack;
namespace Bugzz.Bugzilla
{
internal class Bugzilla
{
bool initialDataLoaded;
string targetVersion;
LoginData loginData;
Regex rdfRegexp = new Regex ("^\\s*<\\?xml.*\\?>\\s*(.|\\n)*<RDF", RegexOptions.Compiled);
Regex xmlRegexp = new Regex ("<\\?xml.*\\?>", RegexOptions.Compiled);
Regex htmlRegexp = new Regex ("<html(.|\\n)*>", RegexOptions.Compiled);
#if FALLBACK
public HashBag <IInitialValue> Classifications;
public HashBag <IInitialValue> Products;
public HashBag <IInitialValue> Components;
public HashBag <IInitialValue> FoundInVersion;
public HashBag <IInitialValue> FixedInMilestone;
public HashBag <IInitialValue> Status;
public HashBag <IInitialValue> Resolution;
public HashBag <IInitialValue> Severity;
public HashBag <IInitialValue> Priority;
public HashBag <IInitialValue> Hardware;
public HashBag <IInitialValue> OS;
#else
public HashBag <IInitialValue> Classifications { get; private set; }
public HashBag <IInitialValue> Products {get; private set; }
public HashBag <IInitialValue> Components {get; private set; }
public HashBag <IInitialValue> FoundInVersion {get; private set; }
public HashBag <IInitialValue> FixedInMilestone { get; private set; }
public HashBag <IInitialValue> Status { get; private set; }
public HashBag <IInitialValue> Resolution { get; private set; }
public HashBag <IInitialValue> Severity { get; private set; }
public HashBag <IInitialValue> Priority { get; private set; }
public HashBag <IInitialValue> Hardware { get; private set; }
public HashBag <IInitialValue> OS { get; private set; }
#endif
string baseUrl;
public string BaseUrl
{
get { return baseUrl; }
set
{
baseUrl = value;
if (WebIO == null) {
if (dataManager == null)
dataManager = new DataManager (targetVersion);
WebIO = new WebIO (baseUrl, loginData, dataManager);
} else
WebIO.BaseUrl = new Uri (baseUrl);
}
}
#if FALLBACK
public WebIO WebIO;
#else
public WebIO WebIO {get; private set; }
#endif
private DataManager dataManager;
public Bugzilla (LoginData loginData)
: this (null, loginData, null)
{
}
public Bugzilla (string baseUrl, LoginData loginData)
: this (baseUrl, loginData, null)
{
}
public Bugzilla (string baseUrl, LoginData loginData, string targetVersion)
{
this.targetVersion = targetVersion;
this.baseUrl = baseUrl;
this.dataManager = new DataManager (targetVersion);
this.loginData = loginData;
WebIO = new WebIO (baseUrl, loginData, dataManager);
Classifications = new HashBag <IInitialValue> ();
Products = new HashBag <IInitialValue> ();
Components = new HashBag <IInitialValue> ();
FoundInVersion = new HashBag <IInitialValue> ();
FixedInMilestone = new HashBag <IInitialValue> ();
Status = new HashBag <IInitialValue> ();
Resolution = new HashBag <IInitialValue> ();
Severity = new HashBag <IInitialValue> ();
Priority = new HashBag <IInitialValue> ();
Hardware = new HashBag <IInitialValue> ();
OS = new HashBag <IInitialValue> ();
}
public void Refresh ()
{
LoadInitialData ();
}
public Bug CreateBug (Query q)
{
VersionData bvd = dataManager.VersionData;
string queryUrl = bvd.GetUrl ("post_bug");
if (String.IsNullOrEmpty (queryUrl))
throw new BugzillaException ("Cannot create bug - no URL given.");
string formName = bvd.GetFormName ("changeform");
if (String.IsNullOrEmpty (formName))
throw new BugzillaException ("Cannot create bug - no form name given.");
q.SetUrl (queryUrl);
string response = WebIO.PostDocument (q.ToString (), "html", htmlRegexp);
if (String.IsNullOrEmpty (response))
throw new BugzillaException ("Bug not created.");
HtmlDocument doc = new HtmlDocument ();
try {
doc.LoadHtml (response);
} catch (Exception ex) {
throw new BugzillaException ("Failed to parse the response document.", ex);
}
HtmlNode node = doc.DocumentNode.SelectSingleNode ("//form[@name='" + formName + "']");
HtmlNode id;
if (node != null)
id = node.SelectSingleNode ("//input[@type='hidden' and @name='id' and string-length (@value) > 0]");
else
id = null;
if (id == null)
throw new BugzillaException ("Unable to determine created bug number - no form found.");
Bug ret = new Bug ();
ret.ID = id.Attributes ["value"].Value;
return ret;
}
public SGC.Dictionary <string, Bug> GetBugList (Query q)
{
VersionData bvd = dataManager.VersionData;
string queryUrl = bvd.GetUrl ("buglist");
if (String.IsNullOrEmpty (queryUrl))
throw new BugzillaException ("Cannot retrieve bug list - no URL given.");
q.SetUrl (queryUrl);
q.AddQueryData ("ctype", "rdf");
string query = WebIO.GetDocument (q.ToString (), "rdf", rdfRegexp);
if (String.IsNullOrEmpty (query))
throw new BugzillaException ("No valid response retrieved.");
ResponseParser rp = new ResponseParser (query);
return rp.Bugs;
}
public SGC.Dictionary <string, Bug> GetBugs (Query q)
{
VersionData bvd = dataManager.VersionData;
string queryUrl = bvd.GetUrl ("show_bug");
if (String.IsNullOrEmpty (queryUrl))
throw new BugzillaException ("Cannot show bugs - no URL given.");
q.SetUrl (queryUrl);
q.AddQueryData ("ctype", "xml");
string query = WebIO.GetDocument (q.ToString (), "xml", xmlRegexp);
if (String.IsNullOrEmpty (query))
throw new BugzillaException ("No valid response retrieved.");
ResponseParser rp = new ResponseParser (query);
return rp.Bugs;
}
void LoadInitialData ()
{
if (initialDataLoaded)
return;
VersionData bvd = dataManager.VersionData;
string queryUrl = bvd.GetUrl ("initial");
if (String.IsNullOrEmpty (queryUrl))
throw new BugzillaException ("Cannot retrieve initial data - no URL given.");
string query = WebIO.GetDocument (queryUrl, "html", htmlRegexp);
if (String.IsNullOrEmpty (query))
throw new BugzillaException ("No document returned by server for initial data.");
HtmlDocument doc = new HtmlDocument ();
try {
doc.LoadHtml (query);
} catch (Exception ex) {
throw new BugzillaException ("Failed to parse the response document.", ex);
}
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes ("//select[string-length (@id) > 0]");
if (nodes == null || nodes.Count == 0)
throw new BugzillaException ("No initial data found.");
// Load the "toplevel" values - that is, all possible values for all
// the 5 Product Information selects.
string canonicalName, id;
foreach (HtmlNode node in nodes) {
id = node.Attributes ["id"].Value;
canonicalName = bvd.HasInitialVariable (id);
if (canonicalName == null)
continue;
StoreSelectValues (node, canonicalName);
}
initialDataLoaded = true;
}
void StoreSelectValues (HtmlNode selectNode, string canonicalName)
{
HtmlNodeCollection nodes = selectNode.SelectNodes ("./option");
switch (canonicalName) {
case "classification":
StoreValues <Classification> (Classifications, nodes);
break;
case "product":
StoreValues <Product> (Products, nodes);
break;
case "component":
StoreValues <Component> (Components, nodes);
break;
case "version":
StoreValues <FoundInVersion> (FoundInVersion, nodes);
break;
case "target_milestone":
StoreValues <FixedInMilestone> (FixedInMilestone, nodes);
break;
case "bug_status":
StoreValues <Status> (Status, nodes);
break;
case "resolution":
StoreValues <Resolution> (Resolution, nodes);
break;
case "bug_severity":
StoreValues <Severity> (Severity, nodes);
break;
case "priority":
StoreValues <Priority> (Priority, nodes);
break;
case "rep_platform":
StoreValues <Hardware> (Hardware, nodes);
break;
case "op_sys":
StoreValues <OS> (OS, nodes);
break;
}
}
void StoreValues <T> (HashBag <IInitialValue> bag, HtmlNodeCollection nodes) where T:InitialValue,new()
{
HtmlAttributeCollection attrs;
HtmlAttribute value;
string label;
T newItem;
foreach (HtmlNode node in nodes) {
attrs = node.Attributes;
if (attrs != null)
value = attrs ["value"];
else
value = null;
label = node.InnerText.Trim ();
newItem = new T ();
newItem.Set (label, value != null ? value.Value : label);
bag.Add (newItem);
}
}
}
}
| |
// 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.Collections.Specialized;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Threading;
using osu.Game.Extensions;
using osu.Game.Graphics.Cursor;
using osu.Game.Input.Bindings;
using osu.Game.Online.Rooms;
using osuTK;
namespace osu.Game.Screens.OnlinePlay.Lounge.Components
{
public class RoomsContainer : CompositeDrawable, IKeyBindingHandler<GlobalAction>
{
public readonly Bindable<Room> SelectedRoom = new Bindable<Room>();
public readonly Bindable<FilterCriteria> Filter = new Bindable<FilterCriteria>();
public IReadOnlyList<DrawableRoom> Rooms => roomFlow.FlowingChildren.Cast<DrawableRoom>().ToArray();
private readonly IBindableList<Room> rooms = new BindableList<Room>();
private readonly FillFlowContainer<DrawableLoungeRoom> roomFlow;
[Resolved]
private IRoomManager roomManager { get; set; }
[Resolved(CanBeNull = true)]
private LoungeSubScreen loungeSubScreen { get; set; }
// handle deselection
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;
public RoomsContainer()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
// account for the fact we are in a scroll container and want a bit of spacing from the scroll bar.
Padding = new MarginPadding { Right = 5 };
InternalChild = new OsuContextMenuContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Child = roomFlow = new FillFlowContainer<DrawableLoungeRoom>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(10),
}
};
}
protected override void LoadComplete()
{
rooms.CollectionChanged += roomsChanged;
roomManager.RoomsUpdated += updateSorting;
rooms.BindTo(roomManager.Rooms);
Filter?.BindValueChanged(criteria => applyFilterCriteria(criteria.NewValue), true);
}
private void applyFilterCriteria(FilterCriteria criteria)
{
roomFlow.Children.ForEach(r =>
{
if (criteria == null)
r.MatchingFilter = true;
else
{
bool matchingFilter = true;
matchingFilter &= r.Room.Playlist.Count == 0 || criteria.Ruleset == null || r.Room.Playlist.Any(i => i.Ruleset.Value.Equals(criteria.Ruleset));
if (!string.IsNullOrEmpty(criteria.SearchString))
matchingFilter &= r.FilterTerms.Any(term => term.Contains(criteria.SearchString, StringComparison.InvariantCultureIgnoreCase));
r.MatchingFilter = matchingFilter;
}
});
}
private void roomsChanged(object sender, NotifyCollectionChangedEventArgs args)
{
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
addRooms(args.NewItems.Cast<Room>());
break;
case NotifyCollectionChangedAction.Remove:
removeRooms(args.OldItems.Cast<Room>());
break;
}
}
private void addRooms(IEnumerable<Room> rooms)
{
foreach (var room in rooms)
roomFlow.Add(new DrawableLoungeRoom(room) { SelectedRoom = { BindTarget = SelectedRoom } });
applyFilterCriteria(Filter?.Value);
}
private void removeRooms(IEnumerable<Room> rooms)
{
foreach (var r in rooms)
{
roomFlow.RemoveAll(d => d.Room == r);
// selection may have a lease due to being in a sub screen.
if (!SelectedRoom.Disabled)
SelectedRoom.Value = null;
}
}
private void updateSorting()
{
foreach (var room in roomFlow)
roomFlow.SetLayoutPosition(room, -(room.Room.RoomID.Value ?? 0));
}
protected override bool OnClick(ClickEvent e)
{
if (!SelectedRoom.Disabled)
SelectedRoom.Value = null;
return base.OnClick(e);
}
#region Key selection logic (shared with BeatmapCarousel)
public bool OnPressed(KeyBindingPressEvent<GlobalAction> e)
{
switch (e.Action)
{
case GlobalAction.SelectNext:
beginRepeatSelection(() => selectNext(1), e.Action);
return true;
case GlobalAction.SelectPrevious:
beginRepeatSelection(() => selectNext(-1), e.Action);
return true;
}
return false;
}
public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e)
{
switch (e.Action)
{
case GlobalAction.SelectNext:
case GlobalAction.SelectPrevious:
endRepeatSelection(e.Action);
break;
}
}
private ScheduledDelegate repeatDelegate;
private object lastRepeatSource;
/// <summary>
/// Begin repeating the specified selection action.
/// </summary>
/// <param name="action">The action to perform.</param>
/// <param name="source">The source of the action. Used in conjunction with <see cref="endRepeatSelection"/> to only cancel the correct action (most recently pressed key).</param>
private void beginRepeatSelection(Action action, object source)
{
endRepeatSelection();
lastRepeatSource = source;
repeatDelegate = this.BeginKeyRepeat(Scheduler, action);
}
private void endRepeatSelection(object source = null)
{
// only the most recent source should be able to cancel the current action.
if (source != null && !EqualityComparer<object>.Default.Equals(lastRepeatSource, source))
return;
repeatDelegate?.Cancel();
repeatDelegate = null;
lastRepeatSource = null;
}
private void selectNext(int direction)
{
if (SelectedRoom.Disabled)
return;
var visibleRooms = Rooms.AsEnumerable().Where(r => r.IsPresent);
Room room;
if (SelectedRoom.Value == null)
room = visibleRooms.FirstOrDefault()?.Room;
else
{
if (direction < 0)
visibleRooms = visibleRooms.Reverse();
room = visibleRooms.SkipWhile(r => r.Room != SelectedRoom.Value).Skip(1).FirstOrDefault()?.Room;
}
// we already have a valid selection only change selection if we still have a room to switch to.
if (room != null)
SelectedRoom.Value = room;
}
#endregion
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (roomManager != null)
roomManager.RoomsUpdated -= updateSorting;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.