context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace invisible.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 ClosedXML.Excel;
using NUnit.Framework;
using System;
namespace ClosedXML.Tests.Excel.CalcEngine
{
[TestFixture]
public class FunctionsTests
{
[SetUp]
public void Init()
{
// Make sure tests run on a deterministic culture
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
[Test]
public void Asc()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Asc(""Text"")");
Assert.AreEqual("Text", actual);
}
[Test]
public void Clean()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(String.Format(@"Clean(""A{0}B"")", Environment.NewLine));
Assert.AreEqual("AB", actual);
}
[Test]
public void Combin()
{
object actual1 = XLWorkbook.EvaluateExpr("Combin(200, 2)");
Assert.AreEqual(19900.0, actual1);
object actual2 = XLWorkbook.EvaluateExpr("Combin(20.1, 2.9)");
Assert.AreEqual(190.0, actual2);
}
[Test]
public void Degrees()
{
object actual1 = XLWorkbook.EvaluateExpr("Degrees(180)");
Assert.IsTrue(Math.PI - (double)actual1 < XLHelper.Epsilon);
}
[Test]
public void Dollar()
{
object actual = XLWorkbook.EvaluateExpr("Dollar(12345.123)");
Assert.AreEqual(TestHelper.CurrencySymbol + "12,345.12", actual);
actual = XLWorkbook.EvaluateExpr("Dollar(12345.123, 1)");
Assert.AreEqual(TestHelper.CurrencySymbol + "12,345.1", actual);
}
[Test]
public void Even()
{
object actual = XLWorkbook.EvaluateExpr("Even(3)");
Assert.AreEqual(4, actual);
actual = XLWorkbook.EvaluateExpr("Even(2)");
Assert.AreEqual(2, actual);
actual = XLWorkbook.EvaluateExpr("Even(-1)");
Assert.AreEqual(-2, actual);
actual = XLWorkbook.EvaluateExpr("Even(-2)");
Assert.AreEqual(-2, actual);
actual = XLWorkbook.EvaluateExpr("Even(0)");
Assert.AreEqual(0, actual);
actual = XLWorkbook.EvaluateExpr("Even(1.5)");
Assert.AreEqual(2, actual);
actual = XLWorkbook.EvaluateExpr("Even(2.01)");
Assert.AreEqual(4, actual);
}
[Test]
public void Exact()
{
Object actual;
actual = XLWorkbook.EvaluateExpr("Exact(\"A\", \"A\")");
Assert.AreEqual(true, actual);
actual = XLWorkbook.EvaluateExpr("Exact(\"A\", \"a\")");
Assert.AreEqual(false, actual);
}
[Test]
public void Fact()
{
object actual = XLWorkbook.EvaluateExpr("Fact(5.9)");
Assert.AreEqual(120.0, actual);
}
[Test]
public void FactDouble()
{
object actual1 = XLWorkbook.EvaluateExpr("FactDouble(6)");
Assert.AreEqual(48.0, actual1);
object actual2 = XLWorkbook.EvaluateExpr("FactDouble(7)");
Assert.AreEqual(105.0, actual2);
}
[Test]
public void Fixed()
{
Object actual;
actual = XLWorkbook.EvaluateExpr("Fixed(12345.123)");
Assert.AreEqual("12,345.12", actual);
actual = XLWorkbook.EvaluateExpr("Fixed(12345.123, 1)");
Assert.AreEqual("12,345.1", actual);
actual = XLWorkbook.EvaluateExpr("Fixed(12345.123, 1, TRUE)");
Assert.AreEqual("12345.1", actual);
}
[Test]
public void Formula_from_another_sheet()
{
var wb = new XLWorkbook();
IXLWorksheet ws1 = wb.AddWorksheet("ws1");
ws1.FirstCell().SetValue(1).CellRight().SetFormulaA1("A1 + 1");
IXLWorksheet ws2 = wb.AddWorksheet("ws2");
ws2.FirstCell().SetFormulaA1("ws1!B1 + 1");
object v = ws2.FirstCell().Value;
Assert.AreEqual(3.0, v);
}
[Test]
public void Gcd()
{
object actual = XLWorkbook.EvaluateExpr("Gcd(24, 36)");
Assert.AreEqual(12, actual);
object actual1 = XLWorkbook.EvaluateExpr("Gcd(5, 0)");
Assert.AreEqual(5, actual1);
object actual2 = XLWorkbook.EvaluateExpr("Gcd(0, 5)");
Assert.AreEqual(5, actual2);
object actual3 = XLWorkbook.EvaluateExpr("Gcd(240, 360, 30)");
Assert.AreEqual(30, actual3);
}
[Test]
public void Lcm()
{
object actual = XLWorkbook.EvaluateExpr("Lcm(24, 36)");
Assert.AreEqual(72, actual);
object actual1 = XLWorkbook.EvaluateExpr("Lcm(5, 0)");
Assert.AreEqual(0, actual1);
object actual2 = XLWorkbook.EvaluateExpr("Lcm(0, 5)");
Assert.AreEqual(0, actual2);
object actual3 = XLWorkbook.EvaluateExpr("Lcm(240, 360, 30)");
Assert.AreEqual(720, actual3);
}
[Test]
public void MDetem()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Cell("A1").SetValue(2).CellRight().SetValue(4);
ws.Cell("A2").SetValue(3).CellRight().SetValue(5);
Object actual;
ws.Cell("A5").FormulaA1 = "MDeterm(A1:B2)";
actual = ws.Cell("A5").Value;
Assert.IsTrue(XLHelper.AreEqual(-2.0, (double)actual));
ws.Cell("A6").FormulaA1 = "Sum(A5)";
actual = ws.Cell("A6").Value;
Assert.IsTrue(XLHelper.AreEqual(-2.0, (double)actual));
ws.Cell("A7").FormulaA1 = "Sum(MDeterm(A1:B2))";
actual = ws.Cell("A7").Value;
Assert.IsTrue(XLHelper.AreEqual(-2.0, (double)actual));
}
[Test]
public void MInverse()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Cell("A1").SetValue(1).CellRight().SetValue(2).CellRight().SetValue(1);
ws.Cell("A2").SetValue(3).CellRight().SetValue(4).CellRight().SetValue(-1);
ws.Cell("A3").SetValue(0).CellRight().SetValue(2).CellRight().SetValue(0);
Object actual;
ws.Cell("A5").FormulaA1 = "MInverse(A1:C3)";
actual = ws.Cell("A5").Value;
Assert.IsTrue(XLHelper.AreEqual(0.25, (double)actual));
ws.Cell("A6").FormulaA1 = "Sum(A5)";
actual = ws.Cell("A6").Value;
Assert.IsTrue(XLHelper.AreEqual(0.25, (double)actual));
ws.Cell("A7").FormulaA1 = "Sum(MInverse(A1:C3))";
actual = ws.Cell("A7").Value;
Assert.IsTrue(XLHelper.AreEqual(0.5, (double)actual));
}
[Test]
public void MMult()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Cell("A1").SetValue(2).CellRight().SetValue(4);
ws.Cell("A2").SetValue(3).CellRight().SetValue(5);
ws.Cell("A3").SetValue(2).CellRight().SetValue(4);
ws.Cell("A4").SetValue(3).CellRight().SetValue(5);
Object actual;
ws.Cell("A5").FormulaA1 = "MMult(A1:B2, A3:B4)";
actual = ws.Cell("A5").Value;
Assert.AreEqual(16.0, actual);
ws.Cell("A6").FormulaA1 = "Sum(A5)";
actual = ws.Cell("A6").Value;
Assert.AreEqual(16.0, actual);
ws.Cell("A7").FormulaA1 = "Sum(MMult(A1:B2, A3:B4))";
actual = ws.Cell("A7").Value;
Assert.AreEqual(102.0, actual);
}
[Test]
public void Mod()
{
object actual = XLWorkbook.EvaluateExpr("Mod(3, 2)");
Assert.AreEqual(1, actual);
object actual1 = XLWorkbook.EvaluateExpr("Mod(-3, 2)");
Assert.AreEqual(1, actual1);
object actual2 = XLWorkbook.EvaluateExpr("Mod(3, -2)");
Assert.AreEqual(-1, actual2);
object actual3 = XLWorkbook.EvaluateExpr("Mod(-3, -2)");
Assert.AreEqual(-1, actual3);
}
[Test]
public void Multinomial()
{
object actual = XLWorkbook.EvaluateExpr("Multinomial(2,3,4)");
Assert.AreEqual(1260.0, actual);
}
[Test]
public void Odd()
{
object actual = XLWorkbook.EvaluateExpr("Odd(1.5)");
Assert.AreEqual(3, actual);
object actual1 = XLWorkbook.EvaluateExpr("Odd(3)");
Assert.AreEqual(3, actual1);
object actual2 = XLWorkbook.EvaluateExpr("Odd(2)");
Assert.AreEqual(3, actual2);
object actual3 = XLWorkbook.EvaluateExpr("Odd(-1)");
Assert.AreEqual(-1, actual3);
object actual4 = XLWorkbook.EvaluateExpr("Odd(-2)");
Assert.AreEqual(-3, actual4);
actual = XLWorkbook.EvaluateExpr("Odd(0)");
Assert.AreEqual(1, actual);
}
[Test]
public void Product()
{
object actual = XLWorkbook.EvaluateExpr("Product(2,3,4)");
Assert.AreEqual(24.0, actual);
}
[Test]
public void Quotient()
{
object actual = XLWorkbook.EvaluateExpr("Quotient(5,2)");
Assert.AreEqual(2, actual);
actual = XLWorkbook.EvaluateExpr("Quotient(4.5,3.1)");
Assert.AreEqual(1, actual);
actual = XLWorkbook.EvaluateExpr("Quotient(-10,3)");
Assert.AreEqual(-3, actual);
}
[Test]
public void Radians()
{
object actual = XLWorkbook.EvaluateExpr("Radians(270)");
Assert.IsTrue(Math.Abs(4.71238898038469 - (double)actual) < XLHelper.Epsilon);
}
[Test]
public void Roman()
{
object actual = XLWorkbook.EvaluateExpr("Roman(3046, 1)");
Assert.AreEqual("MMMXLVI", actual);
actual = XLWorkbook.EvaluateExpr("Roman(270)");
Assert.AreEqual("CCLXX", actual);
actual = XLWorkbook.EvaluateExpr("Roman(3999, true)");
Assert.AreEqual("MMMCMXCIX", actual);
}
[Test]
public void Round()
{
object actual = XLWorkbook.EvaluateExpr("Round(2.15, 1)");
Assert.AreEqual(2.2, actual);
actual = XLWorkbook.EvaluateExpr("Round(2.149, 1)");
Assert.AreEqual(2.1, actual);
actual = XLWorkbook.EvaluateExpr("Round(-1.475, 2)");
Assert.AreEqual(-1.48, actual);
actual = XLWorkbook.EvaluateExpr("Round(21.5, -1)");
Assert.AreEqual(20.0, actual);
actual = XLWorkbook.EvaluateExpr("Round(626.3, -3)");
Assert.AreEqual(1000.0, actual);
actual = XLWorkbook.EvaluateExpr("Round(1.98, -1)");
Assert.AreEqual(0.0, actual);
actual = XLWorkbook.EvaluateExpr("Round(-50.55, -2)");
Assert.AreEqual(-100.0, actual);
actual = XLWorkbook.EvaluateExpr("ROUND(59 * 0.535, 2)"); // (59 * 0.535) = 31.565
Assert.AreEqual(31.57, actual);
actual = XLWorkbook.EvaluateExpr("ROUND(59 * -0.535, 2)"); // (59 * -0.535) = -31.565
Assert.AreEqual(-31.57, actual);
}
[Test]
public void RoundDown()
{
object actual = XLWorkbook.EvaluateExpr("RoundDown(3.2, 0)");
Assert.AreEqual(3.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundDown(76.9, 0)");
Assert.AreEqual(76.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundDown(3.14159, 3)");
Assert.AreEqual(3.141, actual);
actual = XLWorkbook.EvaluateExpr("RoundDown(-3.14159, 1)");
Assert.AreEqual(-3.1, actual);
actual = XLWorkbook.EvaluateExpr("RoundDown(31415.92654, -2)");
Assert.AreEqual(31400.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundDown(0, 3)");
Assert.AreEqual(0.0, actual);
}
[Test]
public void RoundUp()
{
object actual = XLWorkbook.EvaluateExpr("RoundUp(3.2, 0)");
Assert.AreEqual(4.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundUp(76.9, 0)");
Assert.AreEqual(77.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundUp(3.14159, 3)");
Assert.AreEqual(3.142, actual);
actual = XLWorkbook.EvaluateExpr("RoundUp(-3.14159, 1)");
Assert.AreEqual(-3.2, actual);
actual = XLWorkbook.EvaluateExpr("RoundUp(31415.92654, -2)");
Assert.AreEqual(31500.0, actual);
actual = XLWorkbook.EvaluateExpr("RoundUp(0, 3)");
Assert.AreEqual(0.0, actual);
}
[Test]
public void SeriesSum()
{
object actual = XLWorkbook.EvaluateExpr("SERIESSUM(2,3,4,5)");
Assert.AreEqual(40.0, actual);
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.Cell("A2").FormulaA1 = "PI()/4";
ws.Cell("A3").Value = 1;
ws.Cell("A4").FormulaA1 = "-1/FACT(2)";
ws.Cell("A5").FormulaA1 = "1/FACT(4)";
ws.Cell("A6").FormulaA1 = "-1/FACT(6)";
actual = ws.Evaluate("SERIESSUM(A2,0,2,A3:A6)");
Assert.IsTrue(Math.Abs(0.70710321482284566 - (double)actual) < XLHelper.Epsilon);
}
[Test]
public void SqrtPi()
{
object actual = XLWorkbook.EvaluateExpr("SqrtPi(1)");
Assert.IsTrue(Math.Abs(1.7724538509055159 - (double)actual) < XLHelper.Epsilon);
actual = XLWorkbook.EvaluateExpr("SqrtPi(2)");
Assert.IsTrue(Math.Abs(2.5066282746310002 - (double)actual) < XLHelper.Epsilon);
}
[Test]
public void SubtotalAverage()
{
object actual = XLWorkbook.EvaluateExpr("Subtotal(1,2,3)");
Assert.AreEqual(2.5, actual);
actual = XLWorkbook.EvaluateExpr(@"Subtotal(1,""A"",3, 2)");
Assert.AreEqual(2.5, actual);
}
[Test]
public void SubtotalCount()
{
object actual = XLWorkbook.EvaluateExpr("Subtotal(2,2,3)");
Assert.AreEqual(2, actual);
actual = XLWorkbook.EvaluateExpr(@"Subtotal(2,""A"",3)");
Assert.AreEqual(1, actual);
}
[Test]
public void SubtotalCountA()
{
Object actual;
actual = XLWorkbook.EvaluateExpr("Subtotal(3,2,3)");
Assert.AreEqual(2.0, actual);
actual = XLWorkbook.EvaluateExpr(@"Subtotal(3,"""",3)");
Assert.AreEqual(1.0, actual);
}
[Test]
public void SubtotalMax()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(4,2,3,""A"")");
Assert.AreEqual(3.0, actual);
}
[Test]
public void SubtotalMin()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(5,2,3,""A"")");
Assert.AreEqual(2.0, actual);
}
[Test]
public void SubtotalProduct()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(6,2,3,""A"")");
Assert.AreEqual(6.0, actual);
}
[Test]
public void SubtotalStDev()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(7,2,3,""A"")");
Assert.IsTrue(Math.Abs(0.70710678118654757 - (double)actual) < XLHelper.Epsilon);
}
[Test]
public void SubtotalStDevP()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(8,2,3,""A"")");
Assert.AreEqual(0.5, actual);
}
[Test]
public void SubtotalSum()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(9,2,3,""A"")");
Assert.AreEqual(5.0, actual);
}
[Test]
public void SubtotalVar()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(10,2,3,""A"")");
Assert.IsTrue(Math.Abs(0.5 - (double)actual) < XLHelper.Epsilon);
}
[Test]
public void SubtotalVarP()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"Subtotal(11,2,3,""A"")");
Assert.AreEqual(0.25, actual);
}
[Test]
public void SubtotalCalc()
{
var wb = new XLWorkbook();
var ws = wb.AddWorksheet();
ws.NamedRanges.Add("subtotalrange", "A37:A38");
ws.Cell("A1").Value = 2;
ws.Cell("A2").Value = 4;
ws.Cell("A3").FormulaA1 = "SUBTOTAL(9, A1:A2)"; // simple add subtotal
ws.Cell("A4").Value = 8;
ws.Cell("A5").Value = 16;
ws.Cell("A6").FormulaA1 = "SUBTOTAL(9, A4:A5)"; // simple add subtotal
ws.Cell("A7").Value = 32;
ws.Cell("A8").Value = 64;
ws.Cell("A9").FormulaA1 = "SUM(A7:A8)"; // func but not subtotal
ws.Cell("A10").Value = 128;
ws.Cell("A11").Value = 256;
ws.Cell("A12").FormulaA1 = "SUBTOTAL(1, A10:A11)"; // simple avg subtotal
ws.Cell("A13").Value = 512;
ws.Cell("A14").FormulaA1 = "SUBTOTAL(9, A1:A13)"; // subtotals in range
ws.Cell("A15").Value = 1024;
ws.Cell("A16").Value = 2048;
ws.Cell("A17").FormulaA1 = "42 + SUBTOTAL(9, A15:A16)"; // simple add subtotal in formula
ws.Cell("A18").Value = 4096;
ws.Cell("A19").FormulaA1 = "SUBTOTAL(9, A15:A18)"; // subtotals in range
ws.Cell("A20").Value = 8192;
ws.Cell("A21").Value = 16384;
ws.Cell("A22").FormulaA1 = @"32768 * SEARCH(""SUBTOTAL(9, A1:A2)"", A28)"; // subtotal literal in formula
ws.Cell("A23").FormulaA1 = "SUBTOTAL(9, A20:A22)"; // subtotal literal in formula in range
ws.Cell("A24").Value = 65536;
ws.Cell("A25").FormulaA1 = "A23"; // link to subtotal
ws.Cell("A26").FormulaA1 = "PRODUCT(SUBTOTAL(9, A24:A25), 2)"; // subtotal as parameter in func
ws.Cell("A27").Value = 131072;
ws.Cell("A28").Value = "SUBTOTAL(9, A1:A2)"; // subtotal literal
ws.Cell("A29").FormulaA1 = "SUBTOTAL(9, A27:A28)"; // subtotal literal in range
ws.Cell("A30").FormulaA1 = "SUBTOTAL(9, A31:A32)"; // simple add subtotal backward
ws.Cell("A31").Value = 262144;
ws.Cell("A32").Value = 524288;
ws.Cell("A33").FormulaA1 = "SUBTOTAL(9, A20:A32)"; // subtotals in range
ws.Cell("A34").FormulaA1 = @"SUBTOTAL(VALUE(""9""), A1:A33, A35:A41)"; // func as parameter in subtotal and many ranges
ws.Cell("A35").Value = 1048576;
ws.Cell("A36").FormulaA1 = "SUBTOTAL(9, A31:A32, A35)"; // many ranges
ws.Cell("A37").Value = 2097152;
ws.Cell("A38").Value = 4194304;
ws.Cell("A39").FormulaA1 = "SUBTOTAL(3*3, subtotalrange)"; // formula as parameter in subtotal and named range
ws.Cell("A40").Value = 8388608;
ws.Cell("A41").FormulaA1 = "PRODUCT(SUBTOTAL(A4+1, A35:A40), 2)"; // formula with link as parameter in subtotal
ws.Cell("A42").FormulaA1 = "PRODUCT(SUBTOTAL(A4+1, A35:A40), 2) + SUBTOTAL(A4+1, A35:A40)"; // two subtotals in one formula
Assert.AreEqual(6, ws.Cell("A3").Value);
Assert.AreEqual(24, ws.Cell("A6").Value);
Assert.AreEqual(192, ws.Cell("A12").Value);
Assert.AreEqual(1118, ws.Cell("A14").Value);
Assert.AreEqual(3114, ws.Cell("A17").Value);
Assert.AreEqual(7168, ws.Cell("A19").Value);
Assert.AreEqual(57344, ws.Cell("A23").Value);
Assert.AreEqual(245760, ws.Cell("A26").Value);
Assert.AreEqual(131072, ws.Cell("A29").Value);
Assert.AreEqual(786432, ws.Cell("A30").Value);
Assert.AreEqual(1097728, ws.Cell("A33").Value);
Assert.AreEqual(16834654, ws.Cell("A34").Value);
Assert.AreEqual(1835008, ws.Cell("A36").Value);
Assert.AreEqual(6291456, ws.Cell("A39").Value);
Assert.AreEqual(31457280, ws.Cell("A41").Value);
Assert.AreEqual(47185920, ws.Cell("A42").Value);
}
[Test]
public void Sum()
{
IXLCell cell = new XLWorkbook().AddWorksheet("Sheet1").FirstCell();
IXLCell fCell = cell.SetValue(1).CellBelow().SetValue(2).CellBelow();
fCell.FormulaA1 = "sum(A1:A2)";
Assert.AreEqual(3.0, fCell.Value);
}
[Test]
public void SumDateTimeAndNumber()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
ws.Cell("A1").Value = 1;
ws.Cell("A2").Value = new DateTime(2018, 1, 1);
Assert.AreEqual(43102, ws.Evaluate("SUM(A1:A2)"));
ws.Cell("A1").Value = 2;
ws.Cell("A2").FormulaA1 = "DATE(2018,1,1)";
Assert.AreEqual(43103, ws.Evaluate("SUM(A1:A2)"));
}
}
[Test]
public void SumSq()
{
Object actual;
actual = XLWorkbook.EvaluateExpr(@"SumSq(3,4)");
Assert.AreEqual(25.0, actual);
}
[Test]
public void TextConcat()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.Cell("A1").Value = 1;
ws.Cell("A2").Value = 1;
ws.Cell("B1").Value = 1;
ws.Cell("B2").Value = 1;
ws.Cell("C1").FormulaA1 = "\"The total value is: \" & SUM(A1:B2)";
object r = ws.Cell("C1").Value;
Assert.AreEqual("The total value is: 4", r.ToString());
}
[Test]
public void Trim()
{
Assert.AreEqual("Test", XLWorkbook.EvaluateExpr("Trim(\"Test \")"));
//Should not trim non breaking space
//See http://office.microsoft.com/en-us/excel-help/trim-function-HP010062581.aspx
Assert.AreEqual("Test\u00A0", XLWorkbook.EvaluateExpr("Trim(\"Test\u00A0 \")"));
}
[Test]
public void TestEmptyTallyOperations()
{
//In these test no values have been set
XLWorkbook wb = new XLWorkbook();
wb.Worksheets.Add("TallyTests");
var cell = wb.Worksheet(1).Cell(1, 1).SetFormulaA1("=MAX(D1,D2)");
Assert.AreEqual(0, cell.Value);
cell = wb.Worksheet(1).Cell(2, 1).SetFormulaA1("=MIN(D1,D2)");
Assert.AreEqual(0, cell.Value);
cell = wb.Worksheet(1).Cell(3, 1).SetFormulaA1("=SUM(D1,D2)");
Assert.AreEqual(0, cell.Value);
Assert.That(() => wb.Worksheet(1).Cell(3, 1).SetFormulaA1("=AVERAGE(D1,D2)").Value, Throws.TypeOf<ApplicationException>());
}
[Test]
public void TestOmittedParameters()
{
using (var wb = new XLWorkbook())
{
object value;
value = wb.Evaluate("=IF(TRUE,1)");
Assert.AreEqual(1, value);
value = wb.Evaluate("=IF(TRUE,1,)");
Assert.AreEqual(1, value);
value = wb.Evaluate("=IF(FALSE,1,)");
Assert.AreEqual(false, value);
value = wb.Evaluate("=IF(FALSE,,2)");
Assert.AreEqual(2, value);
}
}
[Test]
public void TestDefaultExcelFunctionNamespace()
{
Assert.DoesNotThrow(() => XLWorkbook.EvaluateExpr("TODAY()"));
Assert.DoesNotThrow(() => XLWorkbook.EvaluateExpr("_xlfn.TODAY()"));
Assert.IsTrue((bool)XLWorkbook.EvaluateExpr("_xlfn.TODAY() = TODAY()"));
}
[TestCase("=1234%", 12.34)]
[TestCase("=1234%%", 0.1234)]
[TestCase("=100+200%", 102.0)]
[TestCase("=100%+200", 201.0)]
[TestCase("=(100+200)%", 3.0)]
[TestCase("=200%^5", 32.0)]
[TestCase("=200%^400%", 16.0)]
[TestCase("=SUM(100,200,300)%", 6.0)]
public void PercentOperator(string formula, double expectedResult)
{
var res = (double)XLWorkbook.EvaluateExpr(formula);
Assert.AreEqual(expectedResult, res, XLHelper.Epsilon);
}
[TestCase("=--1", 1)]
[TestCase("=++1", 1)]
[TestCase("=-+-+-1", -1)]
[TestCase("=2^---2", 0.25)]
public void MultipleUnaryOperators(string formula, double expectedResult)
{
var res = (double)XLWorkbook.EvaluateExpr(formula);
Assert.AreEqual(expectedResult, res, XLHelper.Epsilon);
}
[TestCase("RIGHT(\"2020\", 2) + 1", 21)]
[TestCase("LEFT(\"20.2020\", 6) + 1", 21.202)]
[TestCase("2 + (\"3\" & \"4\")", 36)]
[TestCase("2 + \"3\" & \"4\"", "54")]
[TestCase("\"7\" & \"4\"", "74")]
public void TestStringSubExpression(string formula, object expectedResult)
{
var actual = XLWorkbook.EvaluateExpr(formula);
Assert.AreEqual(expectedResult, actual);
}
}
}
| |
// 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.Xml;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using Microsoft.Build.BuildEngine.Shared;
using System.Collections.Generic;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This is an enumeration of property types. Each one is explained further
/// below.
/// </summary>
/// <owner>rgoel</owner>
internal enum PropertyType
{
// A "normal" property is the kind that is settable by the project
// author from within the project file. They are arbitrarily named
// by the author.
NormalProperty,
// An "imported" property is like a "normal" property, except that
// instead of coming directly from the project file, its definition
// is in one of the imported files (e.g., "CSharp.buildrules").
ImportedProperty,
// A "global" property is the kind that is set outside of the project file.
// Once such a property is set, it cannot be overridden by the project file.
// For example, when the user sets a property via a switch on the XMake
// command-line, this is a global property. In the IDE case, "Configuration"
// would be a global property set by the IDE.
GlobalProperty,
// A "reserved" property behaves much like a read-only property, except
// that the names are not arbitrary; they are chosen by us. Also,
// no user can ever set or override these properties. For example,
// "XMakeProjectName" would be a property that is only settable by
// XMake code. Any attempt to set this property via the project file
// or any other mechanism should result in an error.
ReservedProperty,
// An "environment" property is one that came from an environment variable.
EnvironmentProperty,
// An "output" property is generated by a task. Properties of this type
// override all properties except "reserved" ones.
OutputProperty
}
/// <summary>
/// This class holds an MSBuild property. This may be a property that is
/// represented in the MSBuild project file by an XML element, or it
/// may not be represented in any real XML file (e.g., global properties,
/// environment properties, etc.)
/// </summary>
/// <owner>rgoel</owner>
[DebuggerDisplay("BuildProperty (Name = { Name }, Value = { Value }, FinalValue = { FinalValue }, Condition = { Condition })")]
public class BuildProperty
{
#region Member Data
// This is an alternative location for property data: if propertyElement
// is null, which means the property is not persisted, we should not store
// the name/value pair in an XML attribute, because the property name
// may contain illegal XML characters.
private string propertyName = null;
// We'll still store the value no matter what, because fetching the inner
// XML can be an expensive operation.
private string propertyValue = null;
// This is the final evaluated value for the property.
private string finalValueEscaped = String.Empty;
// This the type of the property from the PropertyType enumeration defined
// above.
private PropertyType type = PropertyType.NormalProperty;
// This is the XML element for this property. This contains the name and
// value for this property as well as the condition. For example,
// this node may look like this:
// <WarningLevel Condition="...">4</WarningLevel>
//
// If this property is not represented by an actual XML element in the
// project file, it's okay if this is null.
private XmlElement propertyElement = null;
// This is the specific XML attribute in the above XML element which
// contains the "Condition".
private XmlAttribute conditionAttribute = null;
// If this property is persisted in the project file, then we need to
// store a reference to the parent <PropertyGroup>.
private BuildPropertyGroup parentPersistedPropertyGroup = null;
// Dictionary to intern the value and finalEscapedValue strings as they are deserialized
private static Dictionary<string, string> customInternTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
#endregion
#region CustomSerializationToStream
internal void WriteToStream(BinaryWriter writer)
{
// Cannot be null
writer.Write(propertyName);
writer.Write(propertyValue);
// Only bother serializing the finalValueEscaped
// if it's not identical to the Value (it often is)
if (propertyValue == finalValueEscaped)
{
writer.Write((byte)1);
}
else
{
writer.Write((byte)0);
writer.Write(finalValueEscaped);
}
writer.Write((Int32)type);
}
/// <summary>
/// Avoid creating duplicate strings when deserializing. We are using a custom intern table
/// because String.Intern keeps a reference to the string until the appdomain is unloaded.
/// </summary>
private static string Intern(string stringToIntern)
{
string value = stringToIntern;
if (!customInternTable.TryGetValue(stringToIntern, out value))
{
customInternTable.Add(stringToIntern, stringToIntern);
value = stringToIntern;
}
return value;
}
internal static BuildProperty CreateFromStream(BinaryReader reader)
{
string name = reader.ReadString();
string value = Intern(reader.ReadString());
byte marker = reader.ReadByte();
string finalValueEscaped;
if (marker == (byte)1)
{
finalValueEscaped = value;
}
else
{
finalValueEscaped = Intern(reader.ReadString());
}
PropertyType type = (PropertyType)reader.ReadInt32();
BuildProperty property = new BuildProperty(name, value, type);
property.finalValueEscaped = finalValueEscaped;
return property;
}
/// <summary>
/// Clear the static intern table, so that the memory can be released
/// when a build is released and the node is waiting for re-use.
/// </summary>
internal static void ClearInternTable()
{
customInternTable.Clear();
}
#endregion
#region Constructors
/// <summary>
/// Constructor, that initializes the property with an existing XML element.
/// </summary>
/// <param name="propertyElement"></param>
/// <param name="propertyType"></param>
/// <owner>rgoel</owner>
internal BuildProperty
(
XmlElement propertyElement,
PropertyType propertyType
) :
this(propertyElement,
propertyElement != null ? Utilities.GetXmlNodeInnerContents(propertyElement) : null,
propertyType)
{
ProjectErrorUtilities.VerifyThrowInvalidProject(XMakeElements.IllegalItemPropertyNames[this.Name] == null,
propertyElement, "CannotModifyReservedProperty", this.Name);
}
/// <summary>
/// Constructor, that initializes the property with cloned information.
///
/// Callers -- Please ensure that the propertyValue passed into this constructor
/// is actually computed by calling GetXmlNodeInnerContents on the propertyElement.
/// </summary>
/// <param name="propertyElement"></param>
/// <param name="propertyValue"></param>
/// <param name="propertyType"></param>
/// <owner>rgoel</owner>
private BuildProperty
(
XmlElement propertyElement,
string propertyValue,
PropertyType propertyType
)
{
// Make sure the property node has been given to us.
ErrorUtilities.VerifyThrow(propertyElement != null,
"Need an XML node representing the property element.");
// Validate that the property name doesn't contain any illegal characters.
XmlUtilities.VerifyThrowProjectValidElementName(propertyElement);
this.propertyElement = propertyElement;
// Loop through the list of attributes on the property element.
foreach (XmlAttribute propertyAttribute in propertyElement.Attributes)
{
switch (propertyAttribute.Name)
{
case XMakeAttributes.condition:
// We found the "condition" attribute. Process it.
this.conditionAttribute = propertyAttribute;
break;
default:
ProjectXmlUtilities.ThrowProjectInvalidAttribute(propertyAttribute);
break;
}
}
this.propertyValue = propertyValue;
this.finalValueEscaped = propertyValue;
this.type = propertyType;
}
/// <summary>
/// Constructor, that initializes the property from the raw data, like
/// the property name and property value. This constructor actually creates
/// a new XML element to represent the property, and so it needs the owner
/// XML document.
/// </summary>
/// <param name="ownerDocument"></param>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
/// <param name="propertyType"></param>
/// <owner>rgoel</owner>
internal BuildProperty
(
XmlDocument ownerDocument,
string propertyName,
string propertyValue,
PropertyType propertyType
)
{
ErrorUtilities.VerifyThrowArgumentLength(propertyName, "propertyName");
ErrorUtilities.VerifyThrowArgumentNull(propertyValue, "propertyValue");
// Validate that the property name doesn't contain any illegal characters.
XmlUtilities.VerifyThrowValidElementName(propertyName);
// If we've been given an owner XML document, create a new property
// XML element in that document.
if (ownerDocument != null)
{
// Create the new property XML element.
this.propertyElement = ownerDocument.CreateElement(propertyName, XMakeAttributes.defaultXmlNamespace);
// Set the value
Utilities.SetXmlNodeInnerContents(this.propertyElement, propertyValue);
// Get the value back. Because of some XML weirdness (particularly whitespace between XML attribute),
// what you set may not be exactly what you get back. That's why we ask XML to give us the value
// back, rather than assuming it's the same as the string we set.
this.propertyValue = Utilities.GetXmlNodeInnerContents(this.propertyElement);
}
else
{
// Otherwise this property is not going to be persisted, so we don't
// need an XML element.
this.propertyName = propertyName;
this.propertyValue = propertyValue;
this.propertyElement = null;
}
ErrorUtilities.VerifyThrowInvalidOperation(XMakeElements.IllegalItemPropertyNames[this.Name] == null,
"CannotModifyReservedProperty", this.Name);
// Initialize the final evaluated value of this property to just the
// normal unevaluated value. We actually can't evaluate it in isolation ...
// we need the context of all the properties in the project file.
this.finalValueEscaped = propertyValue;
// We default to a null condition. Setting a condition must be done
// through the "Condition" property after construction.
this.conditionAttribute = null;
// Assign the property type.
this.type = propertyType;
}
/// <summary>
/// Constructor, that initializes the property from the raw data, like
/// the property name and property value. This constructor actually creates
/// a new XML element to represent the property, and creates this XML element
/// under some dummy XML document. This would be used if the property didn't
/// need to be persisted in an actual XML file at any point, like a "global"
/// property or an "environment" property".
/// </summary>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
/// <param name="propertyType"></param>
/// <owner>rgoel</owner>
internal BuildProperty
(
string propertyName,
string propertyValue,
PropertyType propertyType
) :
this(null, propertyName, propertyValue, propertyType)
{
}
/// <summary>
/// Constructor, which initializes the property from just the property
/// name and value, creating it as a "normal" property. This ends up
/// creating a new XML element for the property under a dummy XML document.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
/// <owner>rgoel</owner>
public BuildProperty
(
string propertyName,
string propertyValue
) :
this(propertyName, propertyValue, PropertyType.NormalProperty)
{
}
/// <summary>
/// Default constructor. This is not allowed because it leaves the
/// property in a bad state -- without a name or value. But we have to
/// have it, otherwise FXCop complains.
/// </summary>
/// <owner>sumedhk</owner>
private BuildProperty
(
)
{
// not allowed.
}
#endregion
#region Properties
/// <summary>
/// Accessor for the property name. This is read-only, so one cannot
/// change the property name once it's set ... your only option is
/// to create a new BuildProperty object. The reason is that BuildProperty objects
/// are often stored in hash tables where the hash function is based
/// on the property name. Modifying the property name of an existing
/// BuildProperty object would make the hash table incorrect.
/// </summary>
/// <owner>RGoel</owner>
public string Name
{
get
{
if (propertyElement != null)
{
// Get the property name directly off the XML element.
return this.propertyElement.Name;
}
else
{
// If we are not persisted, propertyName and propertyValue must not be null.
ErrorUtilities.VerifyThrow((this.propertyName != null) && (this.propertyName.Length > 0) && (this.propertyValue != null),
"BuildProperty object doesn't have a name/value pair.");
// Get the property name from the string variable
return this.propertyName;
}
}
}
/// <summary>
/// Accessor for the property value. Normal properties can be modified;
/// other property types cannot.
/// </summary>
/// <owner>RGoel</owner>
public string Value
{
get
{
// If we are not persisted, propertyName and propertyValue must not be null.
ErrorUtilities.VerifyThrow(this.propertyValue != null,
"BuildProperty object doesn't have a name/value pair.");
return this.propertyValue;
}
set
{
ErrorUtilities.VerifyThrowInvalidOperation(this.type != PropertyType.ImportedProperty,
"CannotModifyImportedProjects", this.Name);
ErrorUtilities.VerifyThrowInvalidOperation(this.type != PropertyType.EnvironmentProperty,
"CannotModifyEnvironmentProperty", this.Name);
ErrorUtilities.VerifyThrowInvalidOperation(this.type != PropertyType.ReservedProperty,
"CannotModifyReservedProperty", this.Name);
ErrorUtilities.VerifyThrowInvalidOperation(this.type != PropertyType.GlobalProperty,
"CannotModifyGlobalProperty", this.Name, "Project.GlobalProperties");
SetValue(value);
}
}
/// <summary>
/// Helper method to set the value of a BuildProperty.
/// </summary>
/// <owner>DavidLe</owner>
/// <param name="value"></param>
/// <returns>nothing</returns>
internal void SetValue(string value)
{
ErrorUtilities.VerifyThrowArgumentNull(value, "Value");
// NO OP if the value we set is the same we already have
// This will prevent making the project dirty
if (value == this.propertyValue)
return;
// NOTE: allow output properties to be modified -- they're just like normal properties (except for their
// precedence), and it doesn't really matter if they are modified, since they are transient (virtual)
if (this.propertyElement != null)
{
// If our XML element is not null, store the value in it.
Utilities.SetXmlNodeInnerContents(this.propertyElement, value);
// Get the value back. Because of some XML weirdness (particularly whitespace between XML attribute),
// what you set may not be exactly what you get back. That's why we ask XML to give us the value
// back, rather than assuming it's the same as the string we set.
this.propertyValue = Utilities.GetXmlNodeInnerContents(this.propertyElement);
}
else
{
// Otherwise, store the value in the string variable.
this.propertyValue = value;
}
this.finalValueEscaped = value;
MarkPropertyAsDirty();
}
/// <summary>
/// Accessor for the final evaluated property value. This is read-only.
/// To modify the raw value of a property, use BuildProperty.Value.
/// </summary>
/// <owner>RGoel</owner>
internal string FinalValueEscaped
{
get
{
return this.finalValueEscaped;
}
}
/// <summary>
/// Returns the unescaped value of the property.
/// </summary>
/// <owner>RGoel</owner>
public string FinalValue
{
get
{
return EscapingUtilities.UnescapeAll(this.FinalValueEscaped);
}
}
/// <summary>
/// Accessor for the property type. This is internal, so that nobody
/// calling the OM can modify the type. We actually need to modify
/// it in certain cases internally. C# doesn't allow a different
/// access mode for the "get" vs. the "set", so we've made them both
/// internal.
/// </summary>
/// <owner>RGoel</owner>
internal PropertyType Type
{
get
{
return this.type;
}
set
{
this.type = value;
}
}
/// <summary>
/// Did this property originate from an imported project file?
/// </summary>
/// <owner>RGoel</owner>
public bool IsImported
{
get
{
return (this.type == PropertyType.ImportedProperty);
}
}
/// <summary>
/// Accessor for the condition on the property.
/// </summary>
/// <owner>RGoel</owner>
public string Condition
{
get
{
return (this.conditionAttribute == null) ? String.Empty : this.conditionAttribute.Value;
}
set
{
// If this BuildProperty object is not actually represented by an
// XML element in the project file, then do not allow
// the caller to set the condition.
ErrorUtilities.VerifyThrowInvalidOperation(this.propertyElement != null,
"CannotSetCondition");
// If this property was imported from another project, we don't allow modifying it.
ErrorUtilities.VerifyThrowInvalidOperation(this.Type != PropertyType.ImportedProperty,
"CannotModifyImportedProjects");
this.conditionAttribute = ProjectXmlUtilities.SetOrRemoveAttribute(propertyElement, XMakeAttributes.condition, value);
MarkPropertyAsDirty();
}
}
/// <summary>
/// Read-only accessor for accessing the XML attribute for "Condition". Callers should
/// never try and modify this. Go through this.Condition to change the condition.
/// </summary>
/// <owner>RGoel</owner>
internal XmlAttribute ConditionAttribute
{
get
{
return this.conditionAttribute;
}
}
/// <summary>
/// Accessor for the XmlElement representing this property. This is internal
/// to MSBuild, and is read-only.
/// </summary>
/// <owner>RGoel</owner>
internal XmlElement PropertyElement
{
get
{
return this.propertyElement;
}
}
/// <summary>
/// We need to store a reference to the parent BuildPropertyGroup, so we can
/// send up notifications.
/// </summary>
/// <owner>RGoel</owner>
internal BuildPropertyGroup ParentPersistedPropertyGroup
{
get
{
return this.parentPersistedPropertyGroup;
}
set
{
ErrorUtilities.VerifyThrow( ((value == null) && (this.parentPersistedPropertyGroup != null)) || ((value != null) && (this.parentPersistedPropertyGroup == null)),
"Either new parent cannot be assigned because we already have a parent, or old parent cannot be removed because none exists.");
this.parentPersistedPropertyGroup = value;
}
}
#endregion
#region Methods
/// <summary>
/// Given a property bag, this method evaluates the current property,
/// expanding any property references contained within. It stores this
/// evaluated value in the "finalValue" member.
/// </summary>
/// <owner>RGoel</owner>
internal void Evaluate
(
Expander expander
)
{
ErrorUtilities.VerifyThrow(expander != null, "Expander required to evaluated property.");
this.finalValueEscaped = expander.ExpandAllIntoStringLeaveEscaped(this.Value, this.propertyElement);
}
/// <summary>
/// Marks the parent project as dirty.
/// </summary>
/// <owner>RGoel</owner>
private void MarkPropertyAsDirty
(
)
{
if (this.ParentPersistedPropertyGroup != null)
{
ErrorUtilities.VerifyThrow(this.ParentPersistedPropertyGroup.ParentProject != null, "Persisted BuildPropertyGroup doesn't have parent project.");
this.ParentPersistedPropertyGroup.MarkPropertyGroupAsDirty();
};
}
/// <summary>
/// Creates a shallow or deep clone of this BuildProperty object.
///
/// A shallow clone points at the same XML element as the original, so
/// that modifications to the name or value will be reflected in both
/// copies. However, the two copies could have different a finalValue.
///
/// A deep clone actually clones the XML element as well, so that the
/// two copies are completely independent of each other.
/// </summary>
/// <param name="deepClone"></param>
/// <returns></returns>
/// <owner>rgoel</owner>
public BuildProperty Clone
(
bool deepClone
)
{
BuildProperty clone;
// If this property object is represented as an XML element.
if (this.propertyElement != null)
{
XmlElement newPropertyElement;
if (deepClone)
{
// Clone the XML element itself. The new XML element will be
// associated with the same XML document as the original property,
// but won't actually get added to the XML document.
newPropertyElement = (XmlElement)this.propertyElement.Clone();
}
else
{
newPropertyElement = this.propertyElement;
}
// Create the cloned BuildProperty object, and return it.
clone = new BuildProperty(newPropertyElement, this.propertyValue, this.Type);
}
else
{
// Otherwise, it's just an in-memory property. We can't do a shallow
// clone for this type of property, because there's no XML element for
// the clone to share.
ErrorUtilities.VerifyThrowInvalidOperation(deepClone, "ShallowCloneNotAllowed");
// Create a new property, using the same name, value, and property type.
clone = new BuildProperty(this.Name, this.Value, this.Type);
}
// Do not set the ParentPersistedPropertyGroup on the cloned property, because it isn't really
// part of the property group.
// Be certain we didn't copy the value string: it's a waste of memory
ErrorUtilities.VerifyThrow(Object.ReferenceEquals(clone.Value, this.Value), "Clone value should be identical reference");
return clone;
}
/// <summary>
/// Compares two BuildProperty objects ("this" and "compareToProperty") to determine
/// if all the fields within the BuildProperty are the same.
/// </summary>
/// <param name="compareToProperty"></param>
/// <returns>true if the properties are equivalent, false otherwise</returns>
internal bool IsEquivalent
(
BuildProperty compareToProperty
)
{
// Intentionally do not compare parentPersistedPropertyGroup, because this is
// just a back-pointer, and doesn't really contribute to the "identity" of
// the property.
return
(compareToProperty != null) &&
(0 == String.Compare(compareToProperty.propertyName, this.propertyName, StringComparison.OrdinalIgnoreCase)) &&
(compareToProperty.propertyValue == this.propertyValue) &&
(compareToProperty.FinalValue == this.FinalValue) &&
(compareToProperty.type == this.type);
}
/// <summary>
/// Returns the property value.
/// </summary>
/// <owner>RGoel</owner>
public override string ToString
(
)
{
return (string) this;
}
#endregion
#region Operators
/// <summary>
/// This allows an implicit typecast from a "BuildProperty" to a "string"
/// when trying to access the property's value.
/// </summary>
/// <param name="propertyToCast"></param>
/// <returns></returns>
/// <owner>rgoel</owner>
public static explicit operator string
(
BuildProperty propertyToCast
)
{
if (propertyToCast == null)
{
return String.Empty;
}
return propertyToCast.FinalValue;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class NonLiftedComparisonGreaterThanNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableByteTest(bool useInterpreter)
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableCharTest(bool useInterpreter)
{
char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableChar(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableLong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableSByteTest(bool useInterpreter)
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableSByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableULong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNonLiftedComparisonGreaterThanNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyComparisonGreaterThanNullableUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyComparisonGreaterThanNullableByte(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableChar(char? a, char? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableDouble(double? a, double? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableFloat(float? a, float? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableInt(int? a, int? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableLong(long? a, long? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableSByte(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableShort(short? a, short? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableUInt(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
private static void VerifyComparisonGreaterThanNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.GreaterThan(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
false,
null));
Func<bool> f = e.Compile(useInterpreter);
bool expected = a > b;
bool result = f();
Assert.Equal(expected, result);
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace Northwind
{
/// <summary>
/// Strongly-typed collection for the Territory class.
/// </summary>
[Serializable]
public partial class TerritoryCollection : ActiveList<Territory, TerritoryCollection>
{
public TerritoryCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>TerritoryCollection</returns>
public TerritoryCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Territory o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Territories table.
/// </summary>
[Serializable]
public partial class Territory : ActiveRecord<Territory>, IActiveRecord
{
#region .ctors and Default Settings
public Territory()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Territory(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public Territory(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public Territory(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Territories", TableType.Table, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarTerritoryID = new TableSchema.TableColumn(schema);
colvarTerritoryID.ColumnName = "TerritoryID";
colvarTerritoryID.DataType = DbType.String;
colvarTerritoryID.MaxLength = 20;
colvarTerritoryID.AutoIncrement = false;
colvarTerritoryID.IsNullable = false;
colvarTerritoryID.IsPrimaryKey = true;
colvarTerritoryID.IsForeignKey = false;
colvarTerritoryID.IsReadOnly = false;
colvarTerritoryID.DefaultSetting = @"";
colvarTerritoryID.ForeignKeyTableName = "";
schema.Columns.Add(colvarTerritoryID);
TableSchema.TableColumn colvarTerritoryDescription = new TableSchema.TableColumn(schema);
colvarTerritoryDescription.ColumnName = "TerritoryDescription";
colvarTerritoryDescription.DataType = DbType.String;
colvarTerritoryDescription.MaxLength = 50;
colvarTerritoryDescription.AutoIncrement = false;
colvarTerritoryDescription.IsNullable = false;
colvarTerritoryDescription.IsPrimaryKey = false;
colvarTerritoryDescription.IsForeignKey = false;
colvarTerritoryDescription.IsReadOnly = false;
colvarTerritoryDescription.DefaultSetting = @"";
colvarTerritoryDescription.ForeignKeyTableName = "";
schema.Columns.Add(colvarTerritoryDescription);
TableSchema.TableColumn colvarRegionID = new TableSchema.TableColumn(schema);
colvarRegionID.ColumnName = "RegionID";
colvarRegionID.DataType = DbType.Int32;
colvarRegionID.MaxLength = 0;
colvarRegionID.AutoIncrement = false;
colvarRegionID.IsNullable = false;
colvarRegionID.IsPrimaryKey = false;
colvarRegionID.IsForeignKey = true;
colvarRegionID.IsReadOnly = false;
colvarRegionID.DefaultSetting = @"";
colvarRegionID.ForeignKeyTableName = "Region";
schema.Columns.Add(colvarRegionID);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Territories",schema);
}
}
#endregion
#region Props
[XmlAttribute("TerritoryID")]
[Bindable(true)]
public string TerritoryID
{
get { return GetColumnValue<string>(Columns.TerritoryID); }
set { SetColumnValue(Columns.TerritoryID, value); }
}
[XmlAttribute("TerritoryDescription")]
[Bindable(true)]
public string TerritoryDescription
{
get { return GetColumnValue<string>(Columns.TerritoryDescription); }
set { SetColumnValue(Columns.TerritoryDescription, value); }
}
[XmlAttribute("RegionID")]
[Bindable(true)]
public int RegionID
{
get { return GetColumnValue<int>(Columns.RegionID); }
set { SetColumnValue(Columns.RegionID, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
public Northwind.EmployeeTerritoryCollection EmployeeTerritories()
{
return new Northwind.EmployeeTerritoryCollection().Where(EmployeeTerritory.Columns.TerritoryID, TerritoryID).Load();
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a Region ActiveRecord object related to this Territory
///
/// </summary>
public Northwind.Region Region
{
get { return Northwind.Region.FetchByID(this.RegionID); }
set { SetColumnValue("RegionID", value.RegionID); }
}
#endregion
#region Many To Many Helpers
public Northwind.EmployeeCollection GetEmployeeCollection() { return Territory.GetEmployeeCollection(this.TerritoryID); }
public static Northwind.EmployeeCollection GetEmployeeCollection(string varTerritoryID)
{
SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [dbo].[Employees] INNER JOIN [EmployeeTerritories] ON [Employees].[EmployeeID] = [EmployeeTerritories].[EmployeeID] WHERE [EmployeeTerritories].[TerritoryID] = @TerritoryID", Territory.Schema.Provider.Name);
cmd.AddParameter("@TerritoryID", varTerritoryID, DbType.String);
IDataReader rdr = SubSonic.DataService.GetReader(cmd);
EmployeeCollection coll = new EmployeeCollection();
coll.LoadAndCloseReader(rdr);
return coll;
}
public static void SaveEmployeeMap(string varTerritoryID, EmployeeCollection items)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [EmployeeTerritories] WHERE [EmployeeTerritories].[TerritoryID] = @TerritoryID", Territory.Schema.Provider.Name);
cmdDel.AddParameter("@TerritoryID", varTerritoryID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (Employee item in items)
{
EmployeeTerritory varEmployeeTerritory = new EmployeeTerritory();
varEmployeeTerritory.SetColumnValue("TerritoryID", varTerritoryID);
varEmployeeTerritory.SetColumnValue("EmployeeID", item.GetPrimaryKeyValue());
varEmployeeTerritory.Save();
}
}
public static void SaveEmployeeMap(string varTerritoryID, System.Web.UI.WebControls.ListItemCollection itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [EmployeeTerritories] WHERE [EmployeeTerritories].[TerritoryID] = @TerritoryID", Territory.Schema.Provider.Name);
cmdDel.AddParameter("@TerritoryID", varTerritoryID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (System.Web.UI.WebControls.ListItem l in itemList)
{
if (l.Selected)
{
EmployeeTerritory varEmployeeTerritory = new EmployeeTerritory();
varEmployeeTerritory.SetColumnValue("TerritoryID", varTerritoryID);
varEmployeeTerritory.SetColumnValue("EmployeeID", l.Value);
varEmployeeTerritory.Save();
}
}
}
public static void SaveEmployeeMap(string varTerritoryID , int[] itemList)
{
QueryCommandCollection coll = new SubSonic.QueryCommandCollection();
//delete out the existing
QueryCommand cmdDel = new QueryCommand("DELETE FROM [EmployeeTerritories] WHERE [EmployeeTerritories].[TerritoryID] = @TerritoryID", Territory.Schema.Provider.Name);
cmdDel.AddParameter("@TerritoryID", varTerritoryID, DbType.String);
coll.Add(cmdDel);
DataService.ExecuteTransaction(coll);
foreach (int item in itemList)
{
EmployeeTerritory varEmployeeTerritory = new EmployeeTerritory();
varEmployeeTerritory.SetColumnValue("TerritoryID", varTerritoryID);
varEmployeeTerritory.SetColumnValue("EmployeeID", item);
varEmployeeTerritory.Save();
}
}
public static void DeleteEmployeeMap(string varTerritoryID)
{
QueryCommand cmdDel = new QueryCommand("DELETE FROM [EmployeeTerritories] WHERE [EmployeeTerritories].[TerritoryID] = @TerritoryID", Territory.Schema.Provider.Name);
cmdDel.AddParameter("@TerritoryID", varTerritoryID, DbType.String);
DataService.ExecuteQuery(cmdDel);
}
#endregion
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varTerritoryID,string varTerritoryDescription,int varRegionID)
{
Territory item = new Territory();
item.TerritoryID = varTerritoryID;
item.TerritoryDescription = varTerritoryDescription;
item.RegionID = varRegionID;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(string varTerritoryID,string varTerritoryDescription,int varRegionID)
{
Territory item = new Territory();
item.TerritoryID = varTerritoryID;
item.TerritoryDescription = varTerritoryDescription;
item.RegionID = varRegionID;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn TerritoryIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn TerritoryDescriptionColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn RegionIDColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string TerritoryID = @"TerritoryID";
public static string TerritoryDescription = @"TerritoryDescription";
public static string RegionID = @"RegionID";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.IO;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpClientHandler_Cancellation_Test : HttpClientTestBase
{
[Theory]
[MemberData(nameof(TwoBoolsAndCancellationMode))]
public async Task PostAsync_CancelDuringRequestContentSend_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, CancellationMode mode)
{
if (IsWinHttpHandler || IsNetfxHandler)
{
// Issue #27063: hangs / doesn't cancel
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
// Since we won't receive all of the request, just read everything we do get
byte[] ignored = new byte[100];
while (await connection.Stream.ReadAsync(ignored, 0, ignored.Length) > 0);
});
var preContentSent = new TaskCompletionSource<bool>();
var sendPostContent = new TaskCompletionSource<bool>();
await ValidateClientCancellationAsync(async () =>
{
var req = new HttpRequestMessage(HttpMethod.Post, url);
req.Content = new DelayedByteContent(2000, 3000, preContentSent, sendPostContent.Task);
req.Headers.TransferEncodingChunked = chunkedTransfer;
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> postResponse = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
await preContentSent.Task;
Cancel(mode, client, cts);
await postResponse;
});
try
{
sendPostContent.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[MemberData(nameof(TwoBoolsAndCancellationMode))]
public async Task GetAsync_CancelDuringResponseHeadersReceived_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, CancellationMode mode)
{
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var partialResponseHeadersSent = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync(
$"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\n"); // missing final \r\n so headers don't complete
partialResponseHeadersSent.TrySetResult(true);
await clientFinished.Task;
});
await ValidateClientCancellationAsync(async () =>
{
var req = new HttpRequestMessage(HttpMethod.Get, url);
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
await partialResponseHeadersSent.Task;
Cancel(mode, client, cts);
await getResponse;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[MemberData(nameof(TwoBoolsAndCancellationMode))]
public async Task GetAsync_CancelDuringResponseBodyReceived_Buffered_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, CancellationMode mode)
{
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var responseHeadersSent = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync(
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
(!chunkedTransfer ? "Content-Length: 20\r\n" : "") +
(connectionClose ? "Connection: close\r\n" : "") +
$"\r\n123"); // "123" is part of body and could either be chunked size or part of content-length bytes, both incomplete
responseHeadersSent.TrySetResult(true);
await clientFinished.Task;
});
await ValidateClientCancellationAsync(async () =>
{
var req = new HttpRequestMessage(HttpMethod.Get, url);
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseContentRead, cts.Token);
await responseHeadersSent.Task;
await Task.Delay(1); // make it more likely that client will have started processing response body
Cancel(mode, client, cts);
await getResponse;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[MemberData(nameof(ThreeBools))]
public async Task GetAsync_CancelDuringResponseBodyReceived_Unbuffered_TaskCanceledQuickly(bool chunkedTransfer, bool connectionClose, bool readOrCopyToAsync)
{
if (IsNetfxHandler || IsCurlHandler)
{
// doesn't cancel
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var cts = new CancellationTokenSource();
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var clientFinished = new TaskCompletionSource<bool>();
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync(
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
(!chunkedTransfer ? "Content-Length: 20\r\n" : "") +
(connectionClose ? "Connection: close\r\n" : "") +
$"\r\n");
await clientFinished.Task;
});
var req = new HttpRequestMessage(HttpMethod.Get, url);
req.Headers.ConnectionClose = connectionClose;
Task<HttpResponseMessage> getResponse = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
await ValidateClientCancellationAsync(async () =>
{
HttpResponseMessage resp = await getResponse;
Stream respStream = await resp.Content.ReadAsStreamAsync();
Task readTask = readOrCopyToAsync ?
respStream.ReadAsync(new byte[1], 0, 1, cts.Token) :
respStream.CopyToAsync(Stream.Null, 10, cts.Token);
cts.Cancel();
await readTask;
});
try
{
clientFinished.SetResult(true);
await serverTask;
} catch { }
});
}
}
[Theory]
[InlineData(CancellationMode.CancelPendingRequests, false)]
[InlineData(CancellationMode.DisposeHttpClient, true)]
[InlineData(CancellationMode.CancelPendingRequests, false)]
[InlineData(CancellationMode.DisposeHttpClient, true)]
public async Task GetAsync_CancelPendingRequests_DoesntCancelReadAsyncOnResponseStream(CancellationMode mode, bool copyToAsync)
{
if (IsNetfxHandler)
{
// throws ObjectDisposedException as part of Stream.CopyToAsync/ReadAsync
return;
}
if (IsCurlHandler)
{
// Issue #27065
// throws OperationCanceledException from Stream.CopyToAsync/ReadAsync
return;
}
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var clientReadSomeBody = new TaskCompletionSource<bool>();
var clientFinished = new TaskCompletionSource<bool>();
var responseContentSegment = new string('s', 3000);
int responseSegments = 4;
int contentLength = responseContentSegment.Length * responseSegments;
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync(
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
$"Content-Length: {contentLength}\r\n" +
$"\r\n");
for (int i = 0; i < responseSegments; i++)
{
await connection.Writer.WriteAsync(responseContentSegment);
if (i == 0)
{
await clientReadSomeBody.Task;
}
}
await clientFinished.Task;
});
using (HttpResponseMessage resp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
using (Stream respStream = await resp.Content.ReadAsStreamAsync())
{
var result = new MemoryStream();
int b = respStream.ReadByte();
Assert.NotEqual(-1, b);
result.WriteByte((byte)b);
Cancel(mode, client, null); // should not cancel the operation, as using ResponseHeadersRead
clientReadSomeBody.SetResult(true);
if (copyToAsync)
{
await respStream.CopyToAsync(result, 10, new CancellationTokenSource().Token);
}
else
{
byte[] buffer = new byte[10];
int bytesRead;
while ((bytesRead = await respStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
result.Write(buffer, 0, bytesRead);
}
}
Assert.Equal(contentLength, result.Length);
}
clientFinished.SetResult(true);
await serverTask;
});
}
}
[Fact]
public async Task MaxConnectionsPerServer_WaitingConnectionsAreCancelable()
{
if (IsWinHttpHandler)
{
// Issue #27064:
// Throws WinHttpException ("The server returned an invalid or unrecognized response")
// while parsing headers.
return;
}
if (IsNetfxHandler)
{
// Throws HttpRequestException wrapping a WebException for the canceled request
// instead of throwing an OperationCanceledException or a canceled WebException directly.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = new HttpClient(handler))
{
handler.MaxConnectionsPerServer = 1;
client.Timeout = Timeout.InfiniteTimeSpan;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var serverAboutToBlock = new TaskCompletionSource<bool>();
var blockServerResponse = new TaskCompletionSource<bool>();
Task serverTask1 = server.AcceptConnectionAsync(async connection1 =>
{
await connection1.ReadRequestHeaderAsync();
await connection1.Writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\n");
serverAboutToBlock.SetResult(true);
await blockServerResponse.Task;
await connection1.Writer.WriteAsync("Content-Length: 5\r\n\r\nhello");
});
Task get1 = client.GetAsync(url);
await serverAboutToBlock.Task;
var cts = new CancellationTokenSource();
Task get2 = ValidateClientCancellationAsync(() => client.GetAsync(url, cts.Token));
Task get3 = ValidateClientCancellationAsync(() => client.GetAsync(url, cts.Token));
Task get4 = client.GetAsync(url);
cts.Cancel();
await get2;
await get3;
blockServerResponse.SetResult(true);
await new[] { get1, serverTask1 }.WhenAllOrAnyFailed();
Task serverTask4 = server.AcceptConnectionSendResponseAndCloseAsync();
await new[] { get4, serverTask4 }.WhenAllOrAnyFailed();
});
}
}
private async Task ValidateClientCancellationAsync(Func<Task> clientBodyAsync)
{
var stopwatch = Stopwatch.StartNew();
Exception error = await Record.ExceptionAsync(clientBodyAsync);
stopwatch.Stop();
Assert.NotNull(error);
if (IsNetfxHandler)
{
Assert.True(
error is WebException we && we.Status == WebExceptionStatus.RequestCanceled ||
error is OperationCanceledException,
"Expected cancellation exception, got:" + Environment.NewLine + error);
}
else
{
Assert.True(
error is OperationCanceledException,
"Expected cancellation exception, got:" + Environment.NewLine + error);
}
Assert.True(stopwatch.Elapsed < new TimeSpan(0, 0, 30), $"Elapsed time {stopwatch.Elapsed} should be less than 30 seconds, was {stopwatch.Elapsed.TotalSeconds}");
}
private static void Cancel(CancellationMode mode, HttpClient client, CancellationTokenSource cts)
{
if ((mode & CancellationMode.Token) != 0)
{
cts?.Cancel();
}
if ((mode & CancellationMode.CancelPendingRequests) != 0)
{
client?.CancelPendingRequests();
}
if ((mode & CancellationMode.DisposeHttpClient) != 0)
{
client?.Dispose();
}
}
[Flags]
public enum CancellationMode
{
Token = 0x1,
CancelPendingRequests = 0x2,
DisposeHttpClient = 0x4
}
private static readonly bool[] s_bools = new[] { true, false };
public static IEnumerable<object[]> TwoBoolsAndCancellationMode() =>
from first in s_bools
from second in s_bools
from mode in new[] { CancellationMode.Token, CancellationMode.CancelPendingRequests, CancellationMode.DisposeHttpClient, CancellationMode.Token | CancellationMode.CancelPendingRequests }
select new object[] { first, second, mode };
public static IEnumerable<object[]> ThreeBools() =>
from first in s_bools
from second in s_bools
from third in s_bools
select new object[] { first, second, third };
private sealed class DelayedByteContent : HttpContent
{
private readonly TaskCompletionSource<bool> _preContentSent;
private readonly Task _waitToSendPostContent;
public DelayedByteContent(int preTriggerLength, int postTriggerLength, TaskCompletionSource<bool> preContentSent, Task waitToSendPostContent)
{
PreTriggerLength = preTriggerLength;
_preContentSent = preContentSent;
_waitToSendPostContent = waitToSendPostContent;
Content = new byte[preTriggerLength + postTriggerLength];
new Random().NextBytes(Content);
}
public byte[] Content { get; }
public int PreTriggerLength { get; }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
await stream.WriteAsync(Content, 0, PreTriggerLength);
_preContentSent.TrySetResult(true);
await _waitToSendPostContent;
await stream.WriteAsync(Content, PreTriggerLength, Content.Length - PreTriggerLength);
}
protected override bool TryComputeLength(out long length)
{
length = Content.Length;
return true;
}
}
}
}
| |
using CommandLine;
using CommandLine.Text;
using Newtonsoft.Json;
using Microsoft.Xunit.Performance.Api;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace SoDBench
{
// A simple tree node for tracking file and directory names and sizes
// Does not have to accurately represent the true file system; only what we care about
class SizeReportingNode
{
public SizeReportingNode(string name, long? size=null, bool expand=true)
{
Name = name;
_size = size;
Expanded = expand;
}
public SizeReportingNode(FileInfo file, bool expand=true)
{
Name = file.Name;
_size = file.Length;
Expanded = expand;
}
// Builds out the tree starting from a directory
public SizeReportingNode(DirectoryInfo dir, int? reportingDepth=null)
{
Name = dir.Name;
foreach (var childDir in dir.EnumerateDirectories())
{
AddChild(new SizeReportingNode(childDir));
}
foreach (var childFile in dir.EnumerateFiles())
{
AddChild(new SizeReportingNode(childFile));
}
if (reportingDepth != null)
{
LimitReportingDepth(reportingDepth ?? 0);
}
}
// The directory containing this node
public SizeReportingNode Parent { get; set; }
// All the directories and files this node contains
public List<SizeReportingNode> Children {get; private set;} = new List<SizeReportingNode>();
// The file or directory name
public string Name { get; set; }
public bool Expanded { get; set; } = true;
// A list version of the path up to the root level we care about
public List<string> SegmentedPath {
get
{
if (Parent != null)
{
var path = Parent.SegmentedPath;
path.Add(Name);
return path;
}
return new List<string> { Name };
}
}
// The size of the file or directory
public long Size {
get
{
if (_size == null)
{
_size = 0;
foreach (var node in Children)
{
_size += node.Size;
}
}
return _size ?? 0;
}
private set
{
_size = value;
}
}
// Add the adoptee node as a child and set the adoptee's parent
public void AddChild(SizeReportingNode adoptee)
{
Children.Add(adoptee);
adoptee.Parent = this;
_size = null;
}
public void LimitReportingDepth(int depth)
{
if (depth <= 0)
{
Expanded = false;
}
foreach (var childNode in Children)
{
childNode.LimitReportingDepth(depth-1);
}
}
// Return a CSV formatted string representation of the tree
public string FormatAsCsv()
{
return FormatAsCsv(new StringBuilder()).ToString();
}
// Add to the string build a csv formatted representation of the tree
public StringBuilder FormatAsCsv(StringBuilder builder)
{
string path = String.Join(",", SegmentedPath.Select(s => Csv.Escape(s)));
builder.AppendLine($"{path},{Size}");
if (Expanded)
{
foreach (var childNode in Children)
{
childNode.FormatAsCsv(builder);
}
}
return builder;
}
private long? _size = null;
}
class Program
{
public static readonly string NugetConfig =
@"<?xml version='1.0' encoding='utf-8'?>
<configuration>
<packageSources>
<add key='nuget.org' value='https://api.nuget.org/v3/index.json' protocolVersion='3' />
<add key='myget.org/dotnet-core' value='https://dotnet.myget.org/F/dotnet-core/api/v3/index.json' protocolVersion='3' />
<add key='myget.org/aspnet-core' value='https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json' protocolVersion='3' />
</packageSources>
</configuration>";
public static readonly string[] NewTemplates = new string[] {
"console",
"classlib",
"mstest",
"xunit",
"web",
"mvc",
"razor",
"webapi",
"nugetconfig",
"webconfig",
"sln",
"page",
"viewimports",
"viewstart"
};
public static readonly string[] OperatingSystems = new string[] {
"win10-x64",
"win10-x86",
"ubuntu.16.10-x64",
"rhel.7-x64"
};
static FileInfo s_dotnetExe;
static DirectoryInfo s_sandboxDir;
static DirectoryInfo s_fallbackDir;
static DirectoryInfo s_corelibsDir;
static bool s_keepArtifacts;
static string s_targetArchitecture;
static string s_dotnetChannel;
static void Main(string[] args)
{
try
{
var options = SoDBenchOptions.Parse(args);
s_targetArchitecture = options.TargetArchitecture;
s_dotnetChannel = options.DotnetChannel;
s_keepArtifacts = options.KeepArtifacts;
if (!String.IsNullOrWhiteSpace(options.DotnetExecutable))
{
s_dotnetExe = new FileInfo(options.DotnetExecutable);
}
if (s_sandboxDir == null)
{
// Truncate the Guid used for anti-collision because a full Guid results in expanded paths over 260 chars (the Windows max)
s_sandboxDir = new DirectoryInfo(Path.Combine(Path.GetTempPath(), $"sod{Guid.NewGuid().ToString().Substring(0,13)}"));
s_sandboxDir.Create();
Console.WriteLine($"** Running inside sandbox directory: {s_sandboxDir}");
}
if (s_dotnetExe == null)
{
if(!String.IsNullOrEmpty(options.CoreLibariesDirectory))
{
Console.WriteLine($"** Using core libraries found at {options.CoreLibariesDirectory}");
s_corelibsDir = new DirectoryInfo(options.CoreLibariesDirectory);
}
else
{
var coreroot = Environment.GetEnvironmentVariable("CORE_ROOT");
if (!String.IsNullOrEmpty(coreroot) && Directory.Exists(coreroot))
{
Console.WriteLine($"** Using core libraries from CORE_ROOT at {coreroot}");
s_corelibsDir = new DirectoryInfo(coreroot);
}
else
{
Console.WriteLine("** Using default dotnet-cli core libraries");
}
}
PrintHeader("** Installing Dotnet CLI");
s_dotnetExe = SetupDotnet();
}
if (s_fallbackDir == null)
{
s_fallbackDir = new DirectoryInfo(Path.Combine(s_sandboxDir.FullName, "fallback"));
s_fallbackDir.Create();
}
Console.WriteLine($"** Path to dotnet executable: {s_dotnetExe.FullName}");
PrintHeader("** Starting acquisition size test");
var acquisition = GetAcquisitionSize();
PrintHeader("** Running deployment size test");
var deployment = GetDeploymentSize();
var root = new SizeReportingNode("Dotnet Total");
root.AddChild(acquisition);
root.AddChild(deployment);
var formattedStr = root.FormatAsCsv();
File.WriteAllText(options.OutputFilename, formattedStr);
if (options.Verbose)
Console.WriteLine($"** CSV Output:\n{formattedStr}");
}
finally
{
if (!s_keepArtifacts && s_sandboxDir != null)
{
PrintHeader("** Cleaning up sandbox directory");
DeleteDirectory(s_sandboxDir);
s_sandboxDir = null;
}
}
}
private static void PrintHeader(string message)
{
Console.WriteLine();
Console.WriteLine("**********************************************************************");
Console.WriteLine($"** {message}");
Console.WriteLine("**********************************************************************");
}
private static SizeReportingNode GetAcquisitionSize()
{
var result = new SizeReportingNode("Acquisition Size");
// Arbitrary command to trigger first time setup
ProcessStartInfo dotnet = new ProcessStartInfo()
{
WorkingDirectory = s_sandboxDir.FullName,
FileName = s_dotnetExe.FullName,
Arguments = "new"
};
// Used to set where the packages will be unpacked to.
// There is a no gaurentee that this is a stable method, but is the only way currently to set the fallback folder location
dotnet.Environment["DOTNET_CLI_TEST_FALLBACKFOLDER"] = s_fallbackDir.FullName;
LaunchProcess(dotnet, 180000);
Console.WriteLine("\n** Measuring total size of acquired files");
result.AddChild(new SizeReportingNode(s_fallbackDir, 1));
var dotnetNode = new SizeReportingNode(s_dotnetExe.Directory);
var reportingDepths = new Dictionary<string, int>
{
{"additionalDeps", 1},
{"host", 0},
{"sdk", 2},
{"shared", 2},
{"store", 3}
};
foreach (var childNode in dotnetNode.Children)
{
int depth = 0;
if (reportingDepths.TryGetValue(childNode.Name, out depth))
{
childNode.LimitReportingDepth(depth);
}
}
result.AddChild(dotnetNode);
return result;
}
private static SizeReportingNode GetDeploymentSize()
{
// Write the NuGet.Config file
var nugetConfFile = new FileInfo(Path.Combine(s_sandboxDir.FullName, "NuGet.Config"));
File.WriteAllText(nugetConfFile.FullName, NugetConfig);
var result = new SizeReportingNode("Deployment Size");
foreach (string template in NewTemplates)
{
var templateNode = new SizeReportingNode(template);
result.AddChild(templateNode);
foreach (var os in OperatingSystems)
{
Console.WriteLine($"\n\n** Deploying {template}/{os}");
var deploymentSandbox = new DirectoryInfo(Path.Combine(s_sandboxDir.FullName, template, os));
var publishDir = new DirectoryInfo(Path.Combine(deploymentSandbox.FullName, "publish"));
deploymentSandbox.Create();
ProcessStartInfo dotnetNew = new ProcessStartInfo()
{
FileName = s_dotnetExe.FullName,
Arguments = $"new {template}",
UseShellExecute = false,
WorkingDirectory = deploymentSandbox.FullName
};
dotnetNew.Environment["DOTNET_CLI_TEST_FALLBACKFOLDER"] = s_fallbackDir.FullName;
ProcessStartInfo dotnetRestore = new ProcessStartInfo()
{
FileName = s_dotnetExe.FullName,
Arguments = $"restore --runtime {os}",
UseShellExecute = false,
WorkingDirectory = deploymentSandbox.FullName
};
dotnetRestore.Environment["DOTNET_CLI_TEST_FALLBACKFOLDER"] = s_fallbackDir.FullName;
ProcessStartInfo dotnetPublish = new ProcessStartInfo()
{
FileName = s_dotnetExe.FullName,
// The UserSharedCompiler flag is set to false to prevent handles from being held that will later cause deletion of the installed SDK to fail.
Arguments = $"publish -c Release --runtime {os} --output {publishDir.FullName} /p:UseSharedCompilation=false",
UseShellExecute = false,
WorkingDirectory = deploymentSandbox.FullName
};
dotnetPublish.Environment["DOTNET_CLI_TEST_FALLBACKFOLDER"] = s_fallbackDir.FullName;
try
{
LaunchProcess(dotnetNew, 180000);
if (deploymentSandbox.EnumerateFiles().Any(f => f.Name.EndsWith("proj")))
{
LaunchProcess(dotnetRestore, 180000);
LaunchProcess(dotnetPublish, 180000);
}
else
{
Console.WriteLine($"** {template} does not have a project file to restore or publish");
}
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
continue;
}
// If we published this project, only report published it's size
if (publishDir.Exists)
{
var publishNode = new SizeReportingNode(publishDir, 0);
publishNode.Name = deploymentSandbox.Name;
templateNode.AddChild(publishNode);
}
else
{
templateNode.AddChild(new SizeReportingNode(deploymentSandbox, 0));
}
}
}
return result;
}
private static void DownloadDotnetInstaller()
{
var psi = new ProcessStartInfo() {
WorkingDirectory = s_sandboxDir.FullName,
FileName = @"powershell.exe",
Arguments = $"-NoProfile wget https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.ps1 -OutFile Dotnet-Install.ps1"
};
LaunchProcess(psi, 180000);
}
private static void InstallSharedRuntime()
{
var psi = new ProcessStartInfo() {
WorkingDirectory = s_sandboxDir.FullName,
FileName = @"powershell.exe",
Arguments = $"-NoProfile .\\Dotnet-Install.ps1 -SharedRuntime -InstallDir .dotnet -Channel {s_dotnetChannel} -Architecture {s_targetArchitecture}"
};
LaunchProcess(psi, 180000);
}
private static void InstallDotnet()
{
var psi = new ProcessStartInfo() {
WorkingDirectory = s_sandboxDir.FullName,
FileName = @"powershell.exe",
Arguments = $"-NoProfile .\\Dotnet-Install.ps1 -InstallDir .dotnet -Channel {s_dotnetChannel} -Architecture {s_targetArchitecture}"
};
LaunchProcess(psi, 180000);
}
private static void ModifySharedFramework()
{
// Current working directory is the <coreclr repo root>/sandbox directory.
Console.WriteLine($"** Modifying the shared framework.");
var sourcedi = s_corelibsDir;
// Get the directory containing the newest version of Microsodt.NETCore.App libraries
var targetdi = new DirectoryInfo(
new DirectoryInfo(Path.Combine(s_sandboxDir.FullName, ".dotnet", "shared", "Microsoft.NETCore.App"))
.GetDirectories("*")
.OrderBy(s => s.Name)
.Last()
.FullName);
Console.WriteLine($"| Source : {sourcedi.FullName}");
Console.WriteLine($"| Target : {targetdi.FullName}");
var compiledBinariesOfInterest = new string[] {
"clretwrc.dll",
"clrjit.dll",
"coreclr.dll",
"mscordaccore.dll",
"mscordbi.dll",
"mscorrc.debug.dll",
"mscorrc.dll",
"sos.dll",
"SOS.NETCore.dll",
"System.Private.CoreLib.dll"
};
foreach (var compiledBinaryOfInterest in compiledBinariesOfInterest)
{
foreach (FileInfo fi in targetdi.GetFiles(compiledBinaryOfInterest))
{
var sourceFilePath = Path.Combine(sourcedi.FullName, fi.Name);
var targetFilePath = Path.Combine(targetdi.FullName, fi.Name);
if (File.Exists(sourceFilePath))
{
File.Copy(sourceFilePath, targetFilePath, true);
Console.WriteLine($"| Copied file - '{fi.Name}'");
}
}
}
}
private static FileInfo SetupDotnet()
{
DownloadDotnetInstaller();
InstallSharedRuntime();
InstallDotnet();
if (s_corelibsDir != null)
{
ModifySharedFramework();
}
var dotnetExe = new FileInfo(Path.Combine(s_sandboxDir.FullName, ".dotnet", "dotnet.exe"));
Debug.Assert(dotnetExe.Exists);
return dotnetExe;
}
private static void LaunchProcess(ProcessStartInfo processStartInfo, int timeoutMilliseconds, IDictionary<string, string> environment = null)
{
Console.WriteLine();
Console.WriteLine($"{System.Security.Principal.WindowsIdentity.GetCurrent().Name}@{Environment.MachineName} \"{processStartInfo.WorkingDirectory}\"");
Console.WriteLine($"[{DateTime.Now}] $ {processStartInfo.FileName} {processStartInfo.Arguments}");
if (environment != null)
{
foreach (KeyValuePair<string, string> pair in environment)
{
if (!processStartInfo.Environment.ContainsKey(pair.Key))
processStartInfo.Environment.Add(pair.Key, pair.Value);
else
processStartInfo.Environment[pair.Key] = pair.Value;
}
}
using (var p = new Process() { StartInfo = processStartInfo })
{
p.Start();
if (p.WaitForExit(timeoutMilliseconds) == false)
{
// FIXME: What about clean/kill child processes?
p.Kill();
throw new TimeoutException($"The process '{processStartInfo.FileName} {processStartInfo.Arguments}' timed out.");
}
if (p.ExitCode != 0)
throw new Exception($"{processStartInfo.FileName} exited with error code {p.ExitCode}");
}
}
/// <summary>
/// Provides an interface to parse the command line arguments passed to the SoDBench.
/// </summary>
private sealed class SoDBenchOptions
{
public SoDBenchOptions() { }
private static string NormalizePath(string path)
{
if (String.IsNullOrWhiteSpace(path))
throw new InvalidOperationException($"'{path}' is an invalid path: cannot be null or whitespace");
if (path.Any(c => Path.GetInvalidPathChars().Contains(c)))
throw new InvalidOperationException($"'{path}' is an invalid path: contains invalid characters");
return Path.IsPathRooted(path) ? path : Path.GetFullPath(path);
}
[Option('o', Required = false, HelpText = "Specifies the output file name for the csv document")]
public string OutputFilename
{
get { return _outputFilename; }
set
{
_outputFilename = NormalizePath(value);
}
}
[Option("dotnet", Required = false, HelpText = "Specifies the location of dotnet cli to use.")]
public string DotnetExecutable
{
get { return _dotnetExe; }
set
{
_dotnetExe = NormalizePath(value);
}
}
[Option("corelibs", Required = false, HelpText = "Specifies the location of .NET Core libaries to patch into dotnet. Cannot be used with --dotnet")]
public string CoreLibariesDirectory
{
get { return _corelibsDir; }
set
{
_corelibsDir = NormalizePath(value);
}
}
[Option("architecture", Required = false, Default = "x64", HelpText = "JitBench target architecture (It must match the built product that was copied into sandbox).")]
public string TargetArchitecture { get; set; }
[Option("channel", Required = false, Default = "master", HelpText = "Specifies the channel to use when installing the dotnet-cli")]
public string DotnetChannel { get; set; }
[Option('v', Required = false, HelpText = "Sets output to verbose")]
public bool Verbose { get; set; }
[Option("keep-artifacts", Required = false, HelpText = "Specifies that artifacts of this run should be kept")]
public bool KeepArtifacts { get; set; }
public static SoDBenchOptions Parse(string[] args)
{
using (var parser = new Parser((settings) => {
settings.CaseInsensitiveEnumValues = true;
settings.CaseSensitive = false;
settings.HelpWriter = new StringWriter();
settings.IgnoreUnknownArguments = true;
}))
{
SoDBenchOptions options = null;
parser.ParseArguments<SoDBenchOptions>(args)
.WithParsed(parsed => options = parsed)
.WithNotParsed(errors => {
foreach (Error error in errors)
{
switch (error.Tag)
{
case ErrorType.MissingValueOptionError:
throw new ArgumentException(
$"Missing value option for command line argument '{(error as MissingValueOptionError).NameInfo.NameText}'");
case ErrorType.HelpRequestedError:
Console.WriteLine(Usage());
Environment.Exit(0);
break;
case ErrorType.VersionRequestedError:
Console.WriteLine(new AssemblyName(typeof(SoDBenchOptions).GetTypeInfo().Assembly.FullName).Version);
Environment.Exit(0);
break;
case ErrorType.BadFormatTokenError:
case ErrorType.UnknownOptionError:
case ErrorType.MissingRequiredOptionError:
case ErrorType.MutuallyExclusiveSetError:
case ErrorType.BadFormatConversionError:
case ErrorType.SequenceOutOfRangeError:
case ErrorType.RepeatedOptionError:
case ErrorType.NoVerbSelectedError:
case ErrorType.BadVerbSelectedError:
case ErrorType.HelpVerbRequestedError:
break;
}
}
});
if (options != null && !String.IsNullOrEmpty(options.DotnetExecutable) && !String.IsNullOrEmpty(options.CoreLibariesDirectory))
{
throw new ArgumentException("--dotnet and --corlibs cannot be used together");
}
return options;
}
}
public static string Usage()
{
var parser = new Parser((parserSettings) =>
{
parserSettings.CaseInsensitiveEnumValues = true;
parserSettings.CaseSensitive = false;
parserSettings.EnableDashDash = true;
parserSettings.HelpWriter = new StringWriter();
parserSettings.IgnoreUnknownArguments = true;
});
var helpTextString = new HelpText
{
AddDashesToOption = true,
AddEnumValuesToHelpText = true,
AdditionalNewLineAfterOption = false,
Heading = "SoDBench",
MaximumDisplayWidth = 80,
}.AddOptions(parser.ParseArguments<SoDBenchOptions>(new string[] { "--help" })).ToString();
return helpTextString;
}
private string _dotnetExe;
private string _corelibsDir;
private string _outputFilename = "measurement.csv";
}
private static void DeleteDirectory(DirectoryInfo dir, uint maxWait=10000)
{
foreach (var subdir in dir.GetDirectories())
{
DeleteDirectory(subdir);
}
// Give it time to actually delete all the files
var files = dir.GetFiles();
bool wait = true;
uint waitTime = 0;
while (wait)
{
wait = false;
foreach (var f in files)
{
if (File.Exists(f.FullName))
{
try
{
File.Delete(f.FullName);
}
catch (IOException) { if (waitTime > maxWait) throw; }
catch (UnauthorizedAccessException) { if (waitTime > maxWait) throw; }
if (File.Exists(f.FullName))
{
wait = true;
// Print a message every 3 seconds if the thread is stuck
if (waitTime != 0 && waitTime % 3000 == 0)
{
Console.WriteLine($"Waiting to delete {f.FullName}");
}
}
}
}
// Try again in 100ms
if (wait)
{
Thread.Sleep(100);
waitTime += 100;
}
}
Directory.Delete(dir.FullName);
}
}
// A simple class for escaping strings for CSV writing
// https://stackoverflow.com/a/769713
// Used instead of a package because only these < 20 lines of code are needed
public static class Csv
{
public static string Escape( string s )
{
if ( s.Contains( QUOTE ) )
s = s.Replace( QUOTE, ESCAPED_QUOTE );
if ( s.IndexOfAny( CHARACTERS_THAT_MUST_BE_QUOTED ) > -1 )
s = QUOTE + s + QUOTE;
return s;
}
private const string QUOTE = "\"";
private const string ESCAPED_QUOTE = "\"\"";
private static char[] CHARACTERS_THAT_MUST_BE_QUOTED = { ',', '"', '\n' };
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Newtonsoft.Json;
using System.Threading;
using System.Threading.Tasks;
using GodotTools.IdeMessaging.Requests;
using GodotTools.IdeMessaging.Utils;
namespace GodotTools.IdeMessaging
{
// ReSharper disable once UnusedType.Global
public sealed class Client : IDisposable
{
private readonly ILogger logger;
private readonly string identity;
private string MetaFilePath { get; }
private DateTime? metaFileModifiedTime;
private GodotIdeMetadata godotIdeMetadata;
private readonly FileSystemWatcher fsWatcher;
public string GodotEditorExecutablePath => godotIdeMetadata.EditorExecutablePath;
private readonly IMessageHandler messageHandler;
private Peer peer;
private readonly SemaphoreSlim connectionSem = new SemaphoreSlim(1);
private readonly Queue<NotifyAwaiter<bool>> clientConnectedAwaiters = new Queue<NotifyAwaiter<bool>>();
private readonly Queue<NotifyAwaiter<bool>> clientDisconnectedAwaiters = new Queue<NotifyAwaiter<bool>>();
// ReSharper disable once UnusedMember.Global
public async Task<bool> AwaitConnected()
{
var awaiter = new NotifyAwaiter<bool>();
clientConnectedAwaiters.Enqueue(awaiter);
return await awaiter;
}
// ReSharper disable once UnusedMember.Global
public async Task<bool> AwaitDisconnected()
{
var awaiter = new NotifyAwaiter<bool>();
clientDisconnectedAwaiters.Enqueue(awaiter);
return await awaiter;
}
// ReSharper disable once MemberCanBePrivate.Global
public bool IsDisposed { get; private set; }
// ReSharper disable once MemberCanBePrivate.Global
public bool IsConnected => peer != null && !peer.IsDisposed && peer.IsTcpClientConnected;
// ReSharper disable once EventNeverSubscribedTo.Global
public event Action Connected
{
add
{
if (peer != null && !peer.IsDisposed)
peer.Connected += value;
}
remove
{
if (peer != null && !peer.IsDisposed)
peer.Connected -= value;
}
}
// ReSharper disable once EventNeverSubscribedTo.Global
public event Action Disconnected
{
add
{
if (peer != null && !peer.IsDisposed)
peer.Disconnected += value;
}
remove
{
if (peer != null && !peer.IsDisposed)
peer.Disconnected -= value;
}
}
~Client()
{
Dispose(disposing: false);
}
public async void Dispose()
{
if (IsDisposed)
return;
using (await connectionSem.UseAsync())
{
if (IsDisposed) // lock may not be fair
return;
IsDisposed = true;
}
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
peer?.Dispose();
fsWatcher?.Dispose();
}
}
public Client(string identity, string godotProjectDir, IMessageHandler messageHandler, ILogger logger)
{
this.identity = identity;
this.messageHandler = messageHandler;
this.logger = logger;
// TODO: Need to fetch the project data dir name from ProjectSettings instead of defaulting to ".godot"
string projectMetadataDir = Path.Combine(godotProjectDir, ".godot", "mono", "metadata");
MetaFilePath = Path.Combine(projectMetadataDir, GodotIdeMetadata.DefaultFileName);
// FileSystemWatcher requires an existing directory
if (!Directory.Exists(projectMetadataDir))
Directory.CreateDirectory(projectMetadataDir);
fsWatcher = new FileSystemWatcher(projectMetadataDir, GodotIdeMetadata.DefaultFileName);
}
private async void OnMetaFileChanged(object sender, FileSystemEventArgs e)
{
if (IsDisposed)
return;
using (await connectionSem.UseAsync())
{
if (IsDisposed)
return;
if (!File.Exists(MetaFilePath))
return;
var lastWriteTime = File.GetLastWriteTime(MetaFilePath);
if (lastWriteTime == metaFileModifiedTime)
return;
metaFileModifiedTime = lastWriteTime;
var metadata = ReadMetadataFile();
if (metadata != null && metadata != godotIdeMetadata)
{
godotIdeMetadata = metadata.Value;
_ = Task.Run(ConnectToServer);
}
}
}
private async void OnMetaFileDeleted(object sender, FileSystemEventArgs e)
{
if (IsDisposed)
return;
if (IsConnected)
{
using (await connectionSem.UseAsync())
peer?.Dispose();
}
// The file may have been re-created
using (await connectionSem.UseAsync())
{
if (IsDisposed)
return;
if (IsConnected || !File.Exists(MetaFilePath))
return;
var lastWriteTime = File.GetLastWriteTime(MetaFilePath);
if (lastWriteTime == metaFileModifiedTime)
return;
metaFileModifiedTime = lastWriteTime;
var metadata = ReadMetadataFile();
if (metadata != null)
{
godotIdeMetadata = metadata.Value;
_ = Task.Run(ConnectToServer);
}
}
}
private GodotIdeMetadata? ReadMetadataFile()
{
using (var fileStream = new FileStream(MetaFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(fileStream))
{
string portStr = reader.ReadLine();
if (portStr == null)
return null;
string editorExecutablePath = reader.ReadLine();
if (editorExecutablePath == null)
return null;
if (!int.TryParse(portStr, out int port))
return null;
return new GodotIdeMetadata(port, editorExecutablePath);
}
}
private async Task AcceptClient(TcpClient tcpClient)
{
logger.LogDebug("Accept client...");
using (peer = new Peer(tcpClient, new ClientHandshake(), messageHandler, logger))
{
// ReSharper disable AccessToDisposedClosure
peer.Connected += () =>
{
logger.LogInfo("Connection open with Ide Client");
while (clientConnectedAwaiters.Count > 0)
clientConnectedAwaiters.Dequeue().SetResult(true);
};
peer.Disconnected += () =>
{
while (clientDisconnectedAwaiters.Count > 0)
clientDisconnectedAwaiters.Dequeue().SetResult(true);
};
// ReSharper restore AccessToDisposedClosure
try
{
if (!await peer.DoHandshake(identity))
{
logger.LogError("Handshake failed");
return;
}
}
catch (Exception e)
{
logger.LogError("Handshake failed with unhandled exception: ", e);
return;
}
await peer.Process();
logger.LogInfo("Connection closed with Ide Client");
}
}
private async Task ConnectToServer()
{
var tcpClient = new TcpClient();
try
{
logger.LogInfo("Connecting to Godot Ide Server");
await tcpClient.ConnectAsync(IPAddress.Loopback, godotIdeMetadata.Port);
logger.LogInfo("Connection open with Godot Ide Server");
await AcceptClient(tcpClient);
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.ConnectionRefused)
logger.LogError("The connection to the Godot Ide Server was refused");
else
throw;
}
}
// ReSharper disable once UnusedMember.Global
public async void Start()
{
fsWatcher.Created += OnMetaFileChanged;
fsWatcher.Changed += OnMetaFileChanged;
fsWatcher.Deleted += OnMetaFileDeleted;
fsWatcher.EnableRaisingEvents = true;
using (await connectionSem.UseAsync())
{
if (IsDisposed)
return;
if (IsConnected)
return;
if (!File.Exists(MetaFilePath))
{
logger.LogInfo("There is no Godot Ide Server running");
return;
}
var metadata = ReadMetadataFile();
if (metadata != null)
{
godotIdeMetadata = metadata.Value;
_ = Task.Run(ConnectToServer);
}
else
{
logger.LogError("Failed to read Godot Ide metadata file");
}
}
}
public async Task<TResponse> SendRequest<TResponse>(Request request)
where TResponse : Response, new()
{
if (!IsConnected)
{
logger.LogError("Cannot write request. Not connected to the Godot Ide Server.");
return null;
}
string body = JsonConvert.SerializeObject(request);
return await peer.SendRequest<TResponse>(request.Id, body);
}
public async Task<TResponse> SendRequest<TResponse>(string id, string body)
where TResponse : Response, new()
{
if (!IsConnected)
{
logger.LogError("Cannot write request. Not connected to the Godot Ide Server.");
return null;
}
return await peer.SendRequest<TResponse>(id, body);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace PlayFab.PfEditor
{
public class PlayFabEditor : UnityEditor.EditorWindow
{
#region EdEx Variables
// vars for the plugin-wide event system
public enum EdExStates { OnEnable, OnDisable, OnLogin, OnLogout, OnMenuItemClicked, OnSubmenuItemClicked, OnHttpReq, OnHttpRes, OnError, OnSuccess, OnWarning, OnDataLoaded } //OnWaitBegin, OnWaitEnd,
public delegate void PlayFabEdExStateHandler(EdExStates state, string status, string misc);
public static event PlayFabEdExStateHandler EdExStateUpdate;
public static Dictionary<string, float> blockingRequests = new Dictionary<string, float>(); // key and blockingRequest start time
private static float blockingRequestTimeOut = 10f; // abandon the block after this many seconds.
public static string latestEdExVersion = string.Empty;
internal static PlayFabEditor window;
#endregion
#region unity lopps & methods
void OnEnable()
{
if (window == null)
{
window = this;
window.minSize = new Vector2(320, 0);
}
if (!IsEventHandlerRegistered(StateUpdateHandler))
{
EdExStateUpdate += StateUpdateHandler;
}
RaiseStateUpdate(EdExStates.OnEnable);
PlayFabEditorDataService.LoadAllData();
GetLatestEdExVersion();
}
void OnDisable()
{
// clean up objects:
PlayFabEditorDataService.EditorSettings.isEdExShown = false;
if (IsEventHandlerRegistered(StateUpdateHandler))
{
EdExStateUpdate -= StateUpdateHandler;
}
}
void OnFocus()
{
OnEnable();
}
[MenuItem("Window/PlayFab/Editor Extensions")]
static void PlayFabServices()
{
var editorAsm = typeof(UnityEditor.Editor).Assembly;
var inspWndType = editorAsm.GetType("UnityEditor.SceneHierarchyWindow");
if (inspWndType == null)
{
inspWndType = editorAsm.GetType("UnityEditor.InspectorWindow");
}
window = GetWindow<PlayFabEditor>(inspWndType);
window.titleContent = new GUIContent("PlayFab EdEx");
PlayFabEditorDataService.EditorSettings.isEdExShown = true;
}
[InitializeOnLoad]
public class Startup
{
static Startup()
{
PlayFabEditorDataService.LoadAllData();
if (PlayFabEditorDataService.EditorSettings.isEdExShown || !PlayFabEditorSDKTools.IsInstalled)
{
EditorCoroutine.Start(OpenPlayServices());
}
}
}
static IEnumerator OpenPlayServices()
{
yield return new WaitForSeconds(1f);
if (!Application.isPlaying)
{
PlayFabServices();
}
}
private void OnGUI()
{
HideRepaintErrors(OnGuiInternal);
}
private void OnGuiInternal()
{
GUI.skin = PlayFabEditorHelper.uiStyle;
using (new UnityVertical())
{
//Run all updaters prior to drawing;
PlayFabEditorPackageManager.Update();
PlayFabEditorHeader.DrawHeader();
GUI.enabled = blockingRequests.Count == 0 && !EditorApplication.isCompiling;
if (!PlayFabEditorDataService.IsDataLoaded)
return;
if (PlayFabEditorAuthenticate.IsAuthenticated())
{
PlayFabEditorMenu.DrawMenu();
switch (PlayFabEditorMenu._menuState)
{
case PlayFabEditorMenu.MenuStates.Sdks:
PlayFabEditorSDKTools.DrawSdkPanel();
break;
case PlayFabEditorMenu.MenuStates.Settings:
PlayFabEditorSettings.DrawSettingsPanel();
break;
case PlayFabEditorMenu.MenuStates.Help:
PlayFabEditorHelpMenu.DrawHelpPanel();
break;
case PlayFabEditorMenu.MenuStates.Data:
PlayFabEditorDataMenu.DrawDataPanel();
break;
case PlayFabEditorMenu.MenuStates.Tools:
PlayFabEditorToolsMenu.DrawToolsPanel();
break;
default:
break;
}
}
else
{
PlayFabEditorAuthenticate.DrawAuthPanels();
}
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"), GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true)))
{
GUILayout.FlexibleSpace();
}
// help tag at the bottom of the help menu.
if (PlayFabEditorMenu._menuState == PlayFabEditorMenu.MenuStates.Help)
{
DisplayHelpMenu();
}
}
PruneBlockingRequests();
Repaint();
}
private static void HideRepaintErrors(Action action)
{
try
{
action();
}
catch (Exception e)
{
if (!e.Message.ToLower().Contains("repaint"))
throw;
// Hide any repaint issues when recompiling
}
}
private static void DisplayHelpMenu()
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField(string.Format("PlayFab Editor Extensions: {0}", PlayFabEditorHelper.EDEX_VERSION), PlayFabEditorHelper.uiStyle.GetStyle("versionText"));
GUILayout.FlexibleSpace();
}
//TODO Add plugin upgrade option here (if available);
if (ShowEdExUpgrade())
{
using (new UnityHorizontal())
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("UPGRADE EDEX", PlayFabEditorHelper.uiStyle.GetStyle("textButtonOr")))
{
UpgradeEdEx();
}
GUILayout.FlexibleSpace();
}
}
using (new UnityHorizontal())
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("VIEW DOCUMENTATION", PlayFabEditorHelper.uiStyle.GetStyle("textButton")))
{
Application.OpenURL("https://github.com/PlayFab/UnityEditorExtensions");
}
GUILayout.FlexibleSpace();
}
using (new UnityHorizontal())
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("REPORT ISSUES", PlayFabEditorHelper.uiStyle.GetStyle("textButton")))
{
Application.OpenURL("https://github.com/PlayFab/UnityEditorExtensions/issues");
}
GUILayout.FlexibleSpace();
}
if (!string.IsNullOrEmpty(PlayFabEditorHelper.EDEX_ROOT))
{
using (new UnityHorizontal())
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("UNINSTALL ", PlayFabEditorHelper.uiStyle.GetStyle("textButton")))
{
RemoveEdEx();
}
GUILayout.FlexibleSpace();
}
}
}
}
#endregion
#region menu and helper methods
public static void RaiseStateUpdate(EdExStates state, string status = null, string json = null)
{
if (EdExStateUpdate != null)
EdExStateUpdate(state, status, json);
}
private static void PruneBlockingRequests()
{
List<string> itemsToRemove = new List<string>();
foreach (var req in blockingRequests)
if (req.Value + blockingRequestTimeOut < (float)EditorApplication.timeSinceStartup)
itemsToRemove.Add(req.Key);
foreach (var item in itemsToRemove)
{
ClearBlockingRequest(item);
RaiseStateUpdate(EdExStates.OnWarning, string.Format(" Request {0} has timed out after {1} seconds.", item, blockingRequestTimeOut));
}
}
private static void AddBlockingRequest(string state)
{
blockingRequests[state] = (float)EditorApplication.timeSinceStartup;
}
private static void ClearBlockingRequest(string state = null)
{
if (state == null)
{
blockingRequests.Clear();
}
else if (blockingRequests.ContainsKey(state))
{
blockingRequests.Remove(state);
}
}
/// <summary>
/// Handles state updates within the editor extension.
/// </summary>
/// <param name="state">the state that triggered this event.</param>
/// <param name="status">a generic message about the status.</param>
/// <param name="json">a generic container for additional JSON encoded info.</param>
private void StateUpdateHandler(EdExStates state, string status, string json)
{
switch (state)
{
case EdExStates.OnMenuItemClicked:
//Debug.Log(string.Format("State: {0} - MenuItem: {1} Clicked", state, status));
PlayFabEditorDataService.EditorView.currentSubMenu = 0;
break;
case EdExStates.OnSubmenuItemClicked:
//Debug.Log(string.Format("State: {0} - SubMenuItem: {1} Clicked", state, status));
int parsed;
if (int.TryParse(json, out parsed))
PlayFabEditorDataService.EditorView.currentSubMenu = parsed;
break;
case EdExStates.OnHttpReq:
object temp;
if (string.IsNullOrEmpty(json) || Json.PlayFabSimpleJson.TryDeserializeObject(json, out temp))
break;
var deserialized = temp as Json.JsonObject;
object useSpinner = false;
object blockUi = false;
if (deserialized.TryGetValue("useSpinner", out useSpinner) && bool.Parse(useSpinner.ToString()))
{
ProgressBar.UpdateState(ProgressBar.ProgressBarStates.spin);
}
if (deserialized.TryGetValue("blockUi", out blockUi) && bool.Parse(blockUi.ToString()))
{
AddBlockingRequest(status);
}
break;
case EdExStates.OnHttpRes:
ProgressBar.UpdateState(ProgressBar.ProgressBarStates.off);
ProgressBar.UpdateState(ProgressBar.ProgressBarStates.success);
ClearBlockingRequest(status);
break;
case EdExStates.OnError:
// deserialize and add json details
// clear blocking requests
ProgressBar.UpdateState(ProgressBar.ProgressBarStates.error);
ClearBlockingRequest();
Debug.LogError(string.Format("PlayFab EditorExtensions: Caught an error:{0}", status));
break;
case EdExStates.OnWarning:
ProgressBar.UpdateState(ProgressBar.ProgressBarStates.warning);
ClearBlockingRequest();
Debug.LogWarning(string.Format("PlayFab EditorExtensions: {0}", status));
break;
case EdExStates.OnSuccess:
ClearBlockingRequest();
ProgressBar.UpdateState(ProgressBar.ProgressBarStates.success);
break;
}
}
public static bool IsEventHandlerRegistered(PlayFabEdExStateHandler prospectiveHandler)
{
if (EdExStateUpdate == null)
return false;
foreach (PlayFabEdExStateHandler existingHandler in EdExStateUpdate.GetInvocationList())
if (existingHandler == prospectiveHandler)
return true;
return false;
}
private static void GetLatestEdExVersion()
{
var threshold = PlayFabEditorDataService.EditorSettings.lastEdExVersionCheck != DateTime.MinValue ? PlayFabEditorDataService.EditorSettings.lastEdExVersionCheck.AddHours(1) : DateTime.MinValue;
if (DateTime.Today > threshold)
{
PlayFabEditorHttp.MakeGitHubApiCall("https://api.github.com/repos/PlayFab/UnityEditorExtensions/git/refs/tags", (version) =>
{
latestEdExVersion = version ?? "Unknown";
PlayFabEditorDataService.EditorSettings.latestEdExVersion = latestEdExVersion;
});
}
else
{
latestEdExVersion = PlayFabEditorDataService.EditorSettings.latestEdExVersion;
}
}
private static bool ShowEdExUpgrade()
{
if (string.IsNullOrEmpty(latestEdExVersion) || latestEdExVersion == "Unknown")
{
return false;
}
if (string.IsNullOrEmpty(PlayFabEditorHelper.EDEX_VERSION) || PlayFabEditorHelper.EDEX_VERSION == "Unknown")
{
return true;
}
string[] currrent = PlayFabEditorHelper.EDEX_VERSION.Split('.');
string[] latest = latestEdExVersion.Split('.');
return int.Parse(latest[0]) > int.Parse(currrent[0])
|| int.Parse(latest[1]) > int.Parse(currrent[1])
|| int.Parse(latest[2]) > int.Parse(currrent[2]);
}
private static void RemoveEdEx(bool clearPrefs = true, bool prompt = true)
{
if (prompt && !EditorUtility.DisplayDialog("Confirm Editor Extensions Removal", "This action will remove PlayFab Editor Extensions from the current project.", "Confirm", "Cancel"))
return;
try
{
window.Close();
var edExRoot = new DirectoryInfo(PlayFabEditorHelper.EDEX_ROOT);
FileUtil.DeleteFileOrDirectory(edExRoot.Parent.FullName);
if (clearPrefs)
{
PlayFabEditorDataService.RemoveEditorPrefs();
}
AssetDatabase.Refresh();
}
catch (Exception ex)
{
RaiseStateUpdate(EdExStates.OnError, ex.Message);
}
}
private static void UpgradeEdEx()
{
if (EditorUtility.DisplayDialog("Confirm EdEx Upgrade", "This action will remove the current PlayFab Editor Extensions and install the lastet version.", "Confirm", "Cancel"))
{
window.Close();
ImportLatestEdEx();
}
}
private static void ImportLatestEdEx()
{
PlayFabEditorHttp.MakeDownloadCall("https://api.playfab.com/sdks/download/unity-edex-upgrade", (fileName) =>
{
AssetDatabase.ImportPackage(fileName, false);
Debug.Log("PlayFab EdEx Upgrade: Complete");
});
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WK.Orion.Applications.ADM.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);
}
}
}
}
| |
// 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.Threading.Tasks;
using Xunit;
namespace StreamTests
{
public class StreamMethods
{
[Fact]
public static void MemoryStreamSeekStress()
{
//MemoryStream
var ms1 = new MemoryStream();
SeekTest(ms1, false);
}
[Fact]
public static void MemoryStreamSeekStressWithInitialBuffer()
{
//MemoryStream
var ms1 = new MemoryStream(new Byte[1024], false);
SeekTest(ms1, false);
}
[Fact]
public static async Task MemoryStreamStress()
{
var ms1 = new MemoryStream();
await StreamTest(ms1, false);
}
static private void SeekTest(Stream stream, Boolean fSuppres)
{
long lngPos;
Byte btValue;
stream.Position = 0;
Assert.Equal(0, stream.Position);
Int32 length = 1 << 10; //fancy way of writing 2 to the pow 10
Byte[] btArr = new Byte[length];
for (int i = 0; i < btArr.Length; i++)
btArr[i] = (byte)i;
if (stream.CanWrite)
stream.Write(btArr, 0, btArr.Length);
else
stream.Position = btArr.Length;
Assert.Equal(btArr.Length, stream.Position);
lngPos = stream.Seek(0, SeekOrigin.Begin);
Assert.Equal(0, lngPos);
Assert.Equal(0, stream.Position);
for (int i = 0; i < btArr.Length; i++)
{
if (stream.CanWrite)
{
btValue = (Byte)stream.ReadByte();
Assert.Equal(btArr[i], btValue);
}
else
{
stream.Seek(1, SeekOrigin.Current);
}
Assert.Equal(i + 1, stream.Position);
}
Assert.Throws<IOException>(() => stream.Seek(-5, SeekOrigin.Begin));
lngPos = stream.Seek(5, SeekOrigin.Begin);
Assert.Equal(5, lngPos);
Assert.Equal(5, stream.Position);
lngPos = stream.Seek(5, SeekOrigin.End);
Assert.Equal(length + 5, lngPos);
Assert.Throws<IOException>(() => stream.Seek(-(btArr.Length + 1), SeekOrigin.End));
lngPos = stream.Seek(-5, SeekOrigin.End);
Assert.Equal(btArr.Length - 5, lngPos);
Assert.Equal(btArr.Length - 5, stream.Position);
lngPos = stream.Seek(0, SeekOrigin.End);
Assert.Equal(btArr.Length, stream.Position);
for (int i = btArr.Length; i > 0; i--)
{
stream.Seek(-1, SeekOrigin.Current);
Assert.Equal(i - 1, stream.Position);
}
Assert.Throws<IOException>(() => stream.Seek(-1, SeekOrigin.Current));
}
private static async Task StreamTest(Stream stream, Boolean fSuppress)
{
String strValue;
Int32 iValue;
//[] We will first use the stream's 2 writing methods
Int32 iLength = 1 << 10;
stream.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < iLength; i++)
stream.WriteByte((Byte)i);
Byte[] btArr = new Byte[iLength];
for (int i = 0; i < iLength; i++)
btArr[i] = (Byte)i;
stream.Write(btArr, 0, iLength);
//we will write many things here using a binary writer
BinaryWriter bw1 = new BinaryWriter(stream);
bw1.Write(false);
bw1.Write(true);
for (int i = 0; i < 10; i++)
{
bw1.Write((Byte)i);
bw1.Write((SByte)i);
bw1.Write((Int16)i);
bw1.Write((Char)i);
bw1.Write((UInt16)i);
bw1.Write(i);
bw1.Write((UInt32)i);
bw1.Write((Int64)i);
bw1.Write((UInt64)i);
bw1.Write((Single)i);
bw1.Write((Double)i);
}
//Some strings, chars and Bytes
Char[] chArr = new Char[iLength];
for (int i = 0; i < iLength; i++)
chArr[i] = (Char)i;
bw1.Write(chArr);
bw1.Write(chArr, 512, 512);
bw1.Write(new String(chArr));
bw1.Write(new String(chArr));
//[] we will now read
stream.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < iLength; i++)
{
Assert.Equal(i % 256, stream.ReadByte());
}
btArr = new Byte[iLength];
stream.Read(btArr, 0, iLength);
for (int i = 0; i < iLength; i++)
{
Assert.Equal((byte)i, btArr[i]);
}
//Now, for the binary reader
BinaryReader br1 = new BinaryReader(stream);
Assert.False(br1.ReadBoolean());
Assert.True(br1.ReadBoolean());
for (int i = 0; i < 10; i++)
{
Assert.Equal( (Byte)i, br1.ReadByte());
Assert.Equal((SByte)i, br1.ReadSByte());
Assert.Equal((Int16)i, br1.ReadInt16());
Assert.Equal((Char)i, br1.ReadChar());
Assert.Equal((UInt16)i, br1.ReadUInt16());
Assert.Equal(i, br1.ReadInt32());
Assert.Equal((UInt32)i, br1.ReadUInt32());
Assert.Equal((Int64)i, br1.ReadInt64());
Assert.Equal((UInt64)i, br1.ReadUInt64());
Assert.Equal((Single)i, br1.ReadSingle());
Assert.Equal((Double)i, br1.ReadDouble());
}
chArr = br1.ReadChars(iLength);
for (int i = 0; i < iLength; i++)
{
Assert.Equal((char)i, chArr[i]);
}
chArr = new Char[512];
chArr = br1.ReadChars(iLength / 2);
for (int i = 0; i < iLength / 2; i++)
{
Assert.Equal((char)(iLength / 2 + i), chArr[i]);
}
chArr = new Char[iLength];
for (int i = 0; i < iLength; i++)
chArr[i] = (Char)i;
strValue = br1.ReadString();
Assert.Equal(new String(chArr), strValue);
strValue = br1.ReadString();
Assert.Equal(new String(chArr), strValue);
stream.Seek(1, SeekOrigin.Current); // In the original test, success here would end the test
//[] we will do some async tests here now
stream.Position = 0;
btArr = new Byte[iLength];
for (int i = 0; i < iLength; i++)
btArr[i] = (Byte)(i + 5);
await stream.WriteAsync(btArr, 0, btArr.Length);
stream.Position = 0;
for (int i = 0; i < iLength; i++)
{
Assert.Equal((byte)(i + 5), stream.ReadByte());
}
//we will read asynchronously
stream.Position = 0;
Byte[] compArr = new Byte[iLength];
iValue = await stream.ReadAsync(compArr, 0, compArr.Length);
Assert.Equal(btArr.Length, iValue);
for (int i = 0; i < iLength; i++)
{
Assert.Equal(compArr[i], btArr[i]);
}
}
}
}
| |
/**
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine;
using UnityEngine.Serialization;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus
{
public class CommandInfoAttribute : Attribute
{
/**
* Metadata atribute for the Command class.
* @param category The category to place this command in.
* @param commandName The display name of the command.
* @param helpText Help information to display in the inspector.
* @param priority If two command classes have the same name, the one with highest priority is listed. Negative priority removess the command from the list.
*/
public CommandInfoAttribute(string category, string commandName, string helpText, int priority = 0)
{
this.Category = category;
this.CommandName = commandName;
this.HelpText = helpText;
this.Priority = priority;
}
public string Category { get; set; }
public string CommandName { get; set; }
public string HelpText { get; set; }
public int Priority { get; set; }
}
public class Command : MonoBehaviour
{
[FormerlySerializedAs("commandId")]
[HideInInspector]
public int itemId = -1; // Invalid flowchart item id
[HideInInspector]
public string errorMessage = "";
[HideInInspector]
public int indentLevel;
[NonSerialized]
public int commandIndex;
/**
* Set to true by the parent block while the command is executing.
*/
[NonSerialized]
public bool isExecuting;
/**
* Timer used to control appearance of executing icon in inspector.
*/
[NonSerialized]
public float executingIconTimer;
/**
* Reference to the Block object that this command belongs to.
* This reference is only populated at runtime and in the editor when the
* block is selected.
*/
[NonSerialized]
public Block parentBlock;
public virtual Flowchart GetFlowchart()
{
Flowchart flowchart = GetComponent<Flowchart>();
if (flowchart == null &&
transform.parent != null)
{
flowchart = transform.parent.GetComponent<Flowchart>();
}
return flowchart;
}
public virtual void Execute()
{
OnEnter();
}
public virtual void Continue()
{
// This is a noop if the Block has already been stopped
if (isExecuting)
{
Continue(commandIndex + 1);
}
}
public virtual void Continue(int nextCommandIndex)
{
OnExit();
if (parentBlock != null)
{
parentBlock.jumpToCommandIndex = nextCommandIndex;
}
}
public virtual void StopParentBlock()
{
OnExit();
if (parentBlock != null)
{
parentBlock.Stop();
}
}
/**
* Called when the parent block has been requested to stop executing, and
* this command is the currently executing command.
* Use this callback to terminate any asynchronous operations and
* cleanup state so that the command is ready to execute again later on.
*/
public virtual void OnStopExecuting()
{}
/**
* Called when the new command is added to a block in the editor.
*/
public virtual void OnCommandAdded(Block parentBlock)
{}
/**
* Called when the command is deleted from a block in the editor.
*/
public virtual void OnCommandRemoved(Block parentBlock)
{}
public virtual void OnEnter()
{}
public virtual void OnExit()
{}
public virtual void OnReset()
{}
public virtual void GetConnectedBlocks(ref List<Block> connectedBlocks)
{}
public virtual bool HasReference(Variable variable)
{
return false;
}
public virtual string GetSummary()
{
return "";
}
public virtual string GetHelpText()
{
return "";
}
/**
* This command starts a block of commands.
*/
public virtual bool OpenBlock()
{
return false;
}
/**
* This command ends a block of commands.
*/
public virtual bool CloseBlock()
{
return false;
}
/**
* Return the color for the command background in inspector.
*/
public virtual Color GetButtonColor()
{
return Color.white;
}
/**
* Returns true if the specified property should be displayed in the inspector.
* This is useful for hiding certain properties based on the value of another property.
*/
public virtual bool IsPropertyVisible(string propertyName)
{
return true;
}
/**
* Returns true if the specified property should be displayed as a reorderable list in the inspector.
* This only applies for array properties and has no effect for non-array properties.
*/
public virtual bool IsReorderableArray(string propertyName)
{
return false;
}
/**
* Returns the localization id for the Flowchart that contains this command.
*/
public virtual string GetFlowchartLocalizationId()
{
// If no localization id has been set then use the Flowchart name
Flowchart flowchart = GetFlowchart();
if (flowchart == null)
{
return "";
}
string localizationId = GetFlowchart().localizationId;
if (localizationId.Length == 0)
{
localizationId = flowchart.name;
}
return localizationId;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Dbg = System.Management.Automation;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
#pragma warning disable 56500
namespace System.Management.Automation
{
/// <summary>
/// Holds the state of a Monad Shell session.
/// </summary>
internal sealed partial class SessionStateInternal
{
/// <summary>
/// The current scope. It is either the global scope or
/// a nested scope within the global scope. The current
/// scope is implied or can be accessed using $local in
/// the shell.
/// </summary>
private SessionStateScope _currentScope;
/// <summary>
/// Cmdlet parameter name to return in the error message instead of "scopeID".
/// </summary>
internal const string ScopeParameterName = "Scope";
/// <summary>
/// Given a scope identifier, returns the proper session state scope.
/// </summary>
/// <param name="scopeID">
/// A scope identifier that is either one of the "special" scopes like
/// "global", "local", or "private, or a numeric ID of a relative scope
/// to the current scope.
/// </param>
/// <returns>
/// The scope identified by the scope ID or the current scope if the
/// scope ID is not defined as a special or numeric scope identifier.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="scopeID"/> is less than zero, or not
/// a number and not "script", "global", "local", or "private"
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
internal SessionStateScope GetScopeByID(string scopeID)
{
SessionStateScope result = _currentScope;
if (!string.IsNullOrEmpty(scopeID))
{
if (string.Equals(
scopeID,
StringLiterals.Global,
StringComparison.OrdinalIgnoreCase))
{
result = GlobalScope;
}
else if (string.Equals(
scopeID,
StringLiterals.Local,
StringComparison.OrdinalIgnoreCase))
{
result = _currentScope;
}
else if (string.Equals(
scopeID,
StringLiterals.Private,
StringComparison.OrdinalIgnoreCase))
{
result = _currentScope;
}
else if (string.Equals(
scopeID,
StringLiterals.Script,
StringComparison.OrdinalIgnoreCase))
{
// Get the current script scope from the stack.
result = _currentScope.ScriptScope;
}
else
{
// Since the scope is not any of the special scopes
// try parsing it as an ID
try
{
int scopeNumericID = Int32.Parse(scopeID, System.Globalization.CultureInfo.CurrentCulture);
if (scopeNumericID < 0)
{
throw PSTraceSource.NewArgumentOutOfRangeException(ScopeParameterName, scopeID);
}
result = GetScopeByID(scopeNumericID) ?? _currentScope;
}
catch (FormatException)
{
throw PSTraceSource.NewArgumentException(ScopeParameterName, AutomationExceptions.InvalidScopeIdArgument, ScopeParameterName);
}
catch (OverflowException)
{
throw PSTraceSource.NewArgumentOutOfRangeException(ScopeParameterName, scopeID);
}
}
}
return result;
}
/// <summary>
/// Given a scope ID, walks the scope list to the appropriate scope and returns it.
/// </summary>
/// <param name="scopeID">
/// The numeric indexer to the scope relative to the current scope.
/// </param>
/// <returns>
/// The scope at the index specified. The index is relative to the current
/// scope.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
/// active scopes.
/// </exception>
internal SessionStateScope GetScopeByID(int scopeID)
{
SessionStateScope processingScope = _currentScope;
int originalID = scopeID;
while (scopeID > 0 && processingScope != null)
{
processingScope = processingScope.Parent;
scopeID--;
}
if (processingScope == null && scopeID >= 0)
{
ArgumentOutOfRangeException outOfRange =
PSTraceSource.NewArgumentOutOfRangeException(
ScopeParameterName,
originalID,
SessionStateStrings.ScopeIDExceedsAvailableScopes,
originalID);
throw outOfRange;
}
return processingScope;
}
/// <summary>
/// The global scope of session state. Can be accessed
/// using $global in the shell.
/// </summary>
internal SessionStateScope GlobalScope { get; }
/// <summary>
/// The module scope of a session state. This is only used internally
/// by the engine. There is no module scope qualifier.
/// </summary>
internal SessionStateScope ModuleScope { get; }
/// <summary>
/// Gets the session state current scope.
/// </summary>
internal SessionStateScope CurrentScope
{
get
{
return _currentScope;
}
set
{
Diagnostics.Assert(
value != null,
"A null scope should never be set");
#if DEBUG
// This code is ifdef'd for DEBUG because it may pose a significant
// performance hit and is only really required to validate our internal
// code. There is no way anyone outside the Monad codebase can cause
// these error conditions to be hit.
// Need to make sure the new scope is in the global scope lineage
SessionStateScope scope = value;
bool inGlobalScopeLineage = false;
while (scope != null)
{
if (scope == GlobalScope)
{
inGlobalScopeLineage = true;
break;
}
scope = scope.Parent;
}
Diagnostics.Assert(
inGlobalScopeLineage,
"The scope specified to be set in CurrentScope is not in the global scope lineage. All scopes must originate from the global scope.");
#endif
_currentScope = value;
}
}
/// <summary>
/// Gets the session state current script scope.
/// </summary>
internal SessionStateScope ScriptScope { get { return _currentScope.ScriptScope; } }
/// <summary>
/// Creates a new scope in the scope tree and assigns the parent
/// and child scopes appropriately.
/// </summary>
/// <param name="isScriptScope">
/// If true, the new scope is pushed on to the script scope stack and
/// can be referenced using $script:
/// </param>
/// <returns>
/// A new SessionStateScope which is a child of the current scope.
/// </returns>
internal SessionStateScope NewScope(bool isScriptScope)
{
Diagnostics.Assert(
_currentScope != null,
"The currentScope should always be set.");
// Create the new child scope.
SessionStateScope newScope = new SessionStateScope(_currentScope);
if (isScriptScope)
{
newScope.ScriptScope = newScope;
}
return newScope;
}
/// <summary>
/// Removes the current scope from the scope tree and
/// changes the current scope to the parent scope.
/// </summary>
/// <param name="scope">
/// The scope to cleanup and remove.
/// </param>
/// <exception cref="SessionStateUnauthorizedAccessException">
/// The global scope cannot be removed.
/// </exception>
internal void RemoveScope(SessionStateScope scope)
{
Diagnostics.Assert(
_currentScope != null,
"The currentScope should always be set.");
if (scope == GlobalScope)
{
SessionStateUnauthorizedAccessException e =
new SessionStateUnauthorizedAccessException(
StringLiterals.Global,
SessionStateCategory.Scope,
"GlobalScopeCannotRemove",
SessionStateStrings.GlobalScopeCannotRemove);
throw e;
}
// Give the provider a chance to cleanup the drive data associated
// with drives in this scope
foreach (PSDriveInfo drive in scope.Drives)
{
if (drive == null)
{
continue;
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
// Call CanRemoveDrive to give the provider a chance to cleanup
// but ignore the return value and exceptions
try
{
CanRemoveDrive(drive, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception) // Catch-all OK, 3rd party callout.
{
// Ignore all exceptions from the provider as we are
// going to force the removal anyway
}
}
scope.RemoveAllDrives();
// If the scope being removed is the current scope,
// then it must be removed from the tree.
if (scope == _currentScope && _currentScope.Parent != null)
{
_currentScope = _currentScope.Parent;
}
scope.Parent = null;
}
}
}
#pragma warning restore 56500
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Metadata;
#endif //FEATURE_REMOTING
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Threading;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
#if FEATURE_SERIALIZATION
[Serializable]
#endif
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_FieldInfo))]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class FieldInfo : MemberInfo, _FieldInfo
{
#region Static Members
public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle)
{
if (handle.IsNullHandle())
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), "handle");
FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo());
Type declaringType = f.DeclaringType;
if (declaringType != null && declaringType.IsGenericType)
throw new ArgumentException(String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_FieldDeclaringTypeGeneric"),
f.Name, declaringType.GetGenericTypeDefinition()));
return f;
}
[System.Runtime.InteropServices.ComVisible(false)]
public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType)
{
if (handle.IsNullHandle())
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"));
return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo());
}
#endregion
#region Constructor
protected FieldInfo() { }
#endregion
#if !FEATURE_CORECLR
public static bool operator ==(FieldInfo left, FieldInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimeFieldInfo || right is RuntimeFieldInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(FieldInfo left, FieldInfo right)
{
return !(left == right);
}
#endif // !FEATURE_CORECLR
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
#endregion
#region Public Abstract\Virtual Members
public virtual Type[] GetRequiredCustomModifiers()
{
throw new NotImplementedException();
}
public virtual Type[] GetOptionalCustomModifiers()
{
throw new NotImplementedException();
}
[CLSCompliant(false)]
public virtual void SetValueDirect(TypedReference obj, Object value)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS"));
}
[CLSCompliant(false)]
public virtual Object GetValueDirect(TypedReference obj)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS"));
}
public abstract RuntimeFieldHandle FieldHandle { get; }
public abstract Type FieldType { get; }
public abstract Object GetValue(Object obj);
public virtual Object GetRawConstantValue() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); }
public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture);
public abstract FieldAttributes Attributes { get; }
#endregion
#region Public Members
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public void SetValue(Object obj, Object value)
{
// Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
// But to maintain backward compatibility we can't switch to calling an
// internal overload that takes a stack mark.
// Fortunately the stack walker skips all the reflection invocation frames including this one.
// So this method will never be returned by the stack walker as the caller.
// See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null);
}
public bool IsPublic { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } }
public bool IsPrivate { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } }
public bool IsFamily { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } }
public bool IsAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } }
public bool IsFamilyAndAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } }
public bool IsFamilyOrAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } }
public bool IsStatic { get { return(Attributes & FieldAttributes.Static) != 0; } }
public bool IsInitOnly { get { return(Attributes & FieldAttributes.InitOnly) != 0; } }
public bool IsLiteral { get { return(Attributes & FieldAttributes.Literal) != 0; } }
public bool IsNotSerialized { get { return(Attributes & FieldAttributes.NotSerialized) != 0; } }
public bool IsSpecialName { get { return(Attributes & FieldAttributes.SpecialName) != 0; } }
public bool IsPinvokeImpl { get { return(Attributes & FieldAttributes.PinvokeImpl) != 0; } }
public virtual bool IsSecurityCritical
{
get { return FieldHandle.IsSecurityCritical(); }
}
public virtual bool IsSecuritySafeCritical
{
get { return FieldHandle.IsSecuritySafeCritical(); }
}
public virtual bool IsSecurityTransparent
{
get { return FieldHandle.IsSecurityTransparent(); }
}
#endregion
#if !FEATURE_CORECLR
Type _FieldInfo.GetType()
{
return base.GetType();
}
void _FieldInfo.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _FieldInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _FieldInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
// If you implement this method, make sure to include _FieldInfo.Invoke in VM\DangerousAPIs.h and
// include _FieldInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
void _FieldInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
#if FEATURE_SERIALIZATION
[Serializable]
#endif
internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable
{
#region Private Data Members
private BindingFlags m_bindingFlags;
protected RuntimeTypeCache m_reflectedTypeCache;
protected RuntimeType m_declaringType;
#endregion
#region Constructor
protected RuntimeFieldInfo()
{
// Used for dummy head node during population
}
protected RuntimeFieldInfo(RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags)
{
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
m_reflectedTypeCache = reflectedTypeCache;
}
#endregion
#if FEATURE_REMOTING
#region Legacy Remoting Cache
// The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
// This member is currently being used by Remoting for caching remoting data. If you
// need to cache data here, talk to the Remoting team to work out a mechanism, so that
// both caching systems can happily work together.
private RemotingFieldCachedData m_cachedData;
internal RemotingFieldCachedData RemotingCache
{
get
{
// This grabs an internal copy of m_cachedData and uses
// that instead of looking at m_cachedData directly because
// the cache may get cleared asynchronously. This prevents
// us from having to take a lock.
RemotingFieldCachedData cache = m_cachedData;
if (cache == null)
{
cache = new RemotingFieldCachedData(this);
RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
if (ret != null)
cache = ret;
}
return cache;
}
}
#endregion
#endif //FEATURE_REMOTING
#region NonPublic Members
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
internal RuntimeType GetDeclaringTypeInternal()
{
return m_declaringType;
}
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal abstract RuntimeModule GetRuntimeModule();
#endregion
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Field; } }
public override Type ReflectedType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal;
}
}
public override Type DeclaringType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
}
}
public override Module Module { get { return GetRuntimeModule(); } }
#endregion
#region Object Overrides
public unsafe override String ToString()
{
return FieldType.FormatTypeName() + " " + Name;
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region FieldInfo Overrides
// All implemented on derived classes
#endregion
#region ISerializable Implementation
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
MemberTypes.Field);
}
#endregion
}
[Serializable]
internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo
{
#region FCalls
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags);
#endregion
#region Private Data Members
// agressive caching
private IntPtr m_fieldHandle;
private FieldAttributes m_fieldAttributes;
// lazy caching
private string m_name;
private RuntimeType m_fieldType;
private INVOCATION_FLAGS m_invocationFlags;
#if FEATURE_APPX
private bool IsNonW8PFrameworkAPI()
{
if (GetRuntimeType().IsNonW8PFrameworkAPI())
return true;
// Allow "value__"
if (m_declaringType.IsEnum)
return false;
RuntimeAssembly rtAssembly = GetRuntimeAssembly();
if (rtAssembly.IsFrameworkAssembly())
{
int ctorToken = rtAssembly.InvocableAttributeCtorToken;
if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
!CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
return true;
}
return false;
}
#endif
internal INVOCATION_FLAGS InvocationFlags
{
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
Type declaringType = DeclaringType;
bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType);
INVOCATION_FLAGS invocationFlags = 0;
// first take care of all the NO_INVOKE cases
if (
(declaringType != null && declaringType.ContainsGenericParameters) ||
(declaringType == null && Module.Assembly.ReflectionOnly) ||
(fIsReflectionOnlyType)
)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
// If the invocationFlags are still 0, then
// this should be an usable field, determine the other flags
if (invocationFlags == 0)
{
if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
// A public field is inaccesible to Transparent code if the field is Critical.
bool needsTransparencySecurityCheck = IsSecurityCritical && !IsSecuritySafeCritical;
bool needsVisibilitySecurityCheck = ((m_fieldAttributes & FieldAttributes.FieldAccessMask) != FieldAttributes.Public) ||
(declaringType != null && declaringType.NeedsReflectionSecurityCheck);
if (needsTransparencySecurityCheck || needsVisibilitySecurityCheck)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
// find out if the field type is one of the following: Primitive, Enum or Pointer
Type fieldType = FieldType;
if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST;
}
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
#endif // FEATURE_APPX
// must be last to avoid threading problems
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); }
#region Constructor
[System.Security.SecurityCritical] // auto-generated
internal RtFieldInfo(
RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
: base(reflectedTypeCache, declaringType, bindingFlags)
{
m_fieldHandle = handle.Value;
m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle);
}
#endregion
#region Private Members
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
{
[System.Security.SecuritySafeCritical]
get
{
return new RuntimeFieldHandleInternal(m_fieldHandle);
}
}
#endregion
#region Internal Members
internal void CheckConsistency(Object target)
{
// only test instance fields
if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
{
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatFldReqTarg"));
}
else
{
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_FieldDeclTarget"),
Name, m_declaringType, target.GetType()));
}
}
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RtFieldInfo m = o as RtFieldInfo;
if ((object)m == null)
return false;
return m.m_fieldHandle == m_fieldHandle;
}
[System.Security.SecurityCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
RuntimeType declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
if (declaringType != null && declaringType.ContainsGenericParameters)
throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField"));
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField"));
throw new FieldAccessException();
}
CheckConsistency(obj);
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
#region Security Check
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)m_invocationFlags);
#endregion
bool domainInitialized = false;
if (declaringType == null)
{
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
}
}
// UnsafeSetValue doesn't perform any consistency or visibility check.
// It is the caller's responsibility to ensure the operation is safe.
// When the caller needs to perform visibility checks they should call
// InternalSetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
[System.Security.SecurityCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
RuntimeType declaringType = DeclaringType as RuntimeType;
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
bool domainInitialized = false;
if (declaringType == null)
{
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
}
}
[System.Security.SecuritySafeCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
RuntimeType declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
if (declaringType != null && DeclaringType.ContainsGenericParameters)
throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField"));
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField"));
throw new FieldAccessException();
}
CheckConsistency(obj);
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
RuntimeType fieldType = (RuntimeType)FieldType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)(m_invocationFlags & ~INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD));
return UnsafeGetValue(obj);
}
// UnsafeGetValue doesn't perform any consistency or visibility check.
// It is the caller's responsibility to ensure the operation is safe.
// When the caller needs to perform visibility checks they should call
// InternalGetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
[System.Security.SecurityCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object UnsafeGetValue(Object obj)
{
RuntimeType declaringType = DeclaringType as RuntimeType;
RuntimeType fieldType = (RuntimeType)FieldType;
bool domainInitialized = false;
if (declaringType == null)
{
return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized);
}
else
{
domainInitialized = declaringType.DomainInitialized;
object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
return retVal;
}
}
#endregion
#region MemberInfo Overrides
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
m_name = RuntimeFieldHandle.GetName(this);
return m_name;
}
}
internal String FullName
{
get
{
return String.Format("{0}.{1}", DeclaringType.FullName, Name);
}
}
public override int MetadataToken
{
[System.Security.SecuritySafeCritical] // auto-generated
get { return RuntimeFieldHandle.GetToken(this); }
}
[System.Security.SecuritySafeCritical] // auto-generated
internal override RuntimeModule GetRuntimeModule()
{
return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this));
}
#endregion
#region FieldInfo Overrides
public override Object GetValue(Object obj)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetValue(obj, ref stackMark);
}
public override object GetRawConstantValue() { throw new InvalidOperationException(); }
[System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValueDirect(TypedReference obj)
{
if (obj.IsNull)
throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null"));
Contract.EndContractBlock();
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark);
}
[System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValueDirect(TypedReference obj, Object value)
{
if (obj.IsNull)
throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null"));
Contract.EndContractBlock();
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType);
}
}
public override RuntimeFieldHandle FieldHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
return new RuntimeFieldHandle(this);
}
}
internal IntPtr GetFieldHandle()
{
return m_fieldHandle;
}
public override FieldAttributes Attributes
{
get
{
return m_fieldAttributes;
}
}
public override Type FieldType
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_fieldType == null)
m_fieldType = new Signature(this, m_declaringType).FieldType;
return m_fieldType;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override Type[] GetRequiredCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override Type[] GetOptionalCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, false);
}
#endregion
}
#if FEATURE_SERIALIZATION
[Serializable]
#endif
internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable
{
#region Private Data Members
private int m_tkField;
private string m_name;
private RuntimeType m_fieldType;
private FieldAttributes m_fieldAttributes;
#endregion
#region Constructor
internal MdFieldInfo(
int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
: base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags)
{
m_tkField = tkField;
m_name = null;
m_fieldAttributes = fieldAttributes;
}
#endregion
#region Internal Members
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
MdFieldInfo m = o as MdFieldInfo;
if ((object)m == null)
return false;
return m.m_tkField == m_tkField &&
m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals(
m.m_declaringType.GetTypeHandleInternal().GetModuleHandle());
}
#endregion
#region MemberInfo Overrides
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString();
return m_name;
}
}
public override int MetadataToken { get { return m_tkField; } }
internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
#endregion
#region FieldInfo Overrides
public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } }
public override FieldAttributes Attributes { get { return m_fieldAttributes; } }
public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } }
public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } }
public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValueDirect(TypedReference obj)
{
return GetValue(null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValueDirect(TypedReference obj,Object value)
{
throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly"));
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public unsafe override Object GetValue(Object obj)
{
return GetValue(false);
}
public unsafe override Object GetRawConstantValue() { return GetValue(true); }
[System.Security.SecuritySafeCritical] // auto-generated
private unsafe Object GetValue(bool raw)
{
// Cannot cache these because they could be user defined non-agile enumerations
Object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw);
if (value == DBNull.Value)
throw new NotSupportedException(Environment.GetResourceString("Arg_EnumLitValueNotFound"));
return value;
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
{
throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly"));
}
public override Type FieldType
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_fieldType == null)
{
ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField);
m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(),
(int)fieldMarshal.Length, m_declaringType).FieldType;
}
return m_fieldType;
}
}
public override Type[] GetRequiredCustomModifiers()
{
return EmptyArray<Type>.Value;
}
public override Type[] GetOptionalCustomModifiers()
{
return EmptyArray<Type>.Value;
}
#endregion
}
}
| |
using System.Collections.Generic;
using dotless.Core.Exceptions;
namespace dotless.Test.Specs
{
using NUnit.Framework;
public class SelectorsFixture : SpecFixtureBase
{
[Test]
public void ParentSelector1()
{
var input =
@"
h1, h2, h3 {
a, p {
&:hover {
color: red;
}
}
}
";
var expected =
@"
h1 a:hover,
h2 a:hover,
h3 a:hover,
h1 p:hover,
h2 p:hover,
h3 p:hover {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector2()
{
// Note: http://github.com/cloudhead/less.js/issues/issue/9
var input =
@"
a {
color: red;
&:hover { color: blue; }
div & { color: green; }
p & span { color: yellow; }
}
";
var expected =
@"
a {
color: red;
}
a:hover {
color: blue;
}
div a {
color: green;
}
p a span {
color: yellow;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector3()
{
// Note: http://github.com/cloudhead/less.js/issues/issue/9
var input =
@"
.foo {
.bar, .baz {
& .qux {
display: block;
}
.qux & {
display:inline;
}
}
}
";
var expected =
@"
.foo .bar .qux,
.foo .baz .qux {
display: block;
}
.qux .foo .bar,
.qux .foo .baz {
display: inline;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector4()
{
var input =
@"
.foo {
.bar, .baz {
.qux& {
display:inline;
}
}
}
";
var expected =
@"
.qux.foo .bar,
.qux.foo .baz {
display: inline;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector5()
{
//https://github.com/cloudhead/less.js/issues/774
var input =
@"
.b {
&.c {
.a& {
color: red;
}
}
}
";
var expected =
@"
.a.b.c {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector6()
{
// https://github.com/cloudhead/less.js/issues/299
var input =
@"
.margin_between(@above, @below) {
* + & { margin-top: @above; }
legend + & { margin-top: 0; }
& + * { margin-top: @below; }
}
h1 { .margin_between(25px, 10px); }
h2 { .margin_between(20px, 8px); }
h3 { .margin_between(15px, 5px); }";
var expected =
@"
* + h1 {
margin-top: 25px;
}
legend + h1 {
margin-top: 0;
}
h1 + * {
margin-top: 10px;
}
* + h2 {
margin-top: 20px;
}
legend + h2 {
margin-top: 0;
}
h2 + * {
margin-top: 8px;
}
* + h3 {
margin-top: 15px;
}
legend + h3 {
margin-top: 0;
}
h3 + * {
margin-top: 5px;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector7()
{
// https://github.com/cloudhead/less.js/issues/749
var input =
@"
.b {
.c & {
&.a {
color: red;
}
}
}
";
var expected =
@"
.c .b.a {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector8()
{
var input = @"
.p {
.foo &.bar {
color: red;
}
}
";
var expected = @"
.foo .p.bar {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelector9()
{
var input = @"
.p {
.foo&.bar {
color: red;
}
}
";
var expected = @"
.foo.p.bar {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorCombinators()
{
// Note: https://github.com/dotless/dotless/issues/171
var input =
@"
.foo {
.foo + & {
background: amber;
}
& + & {
background: amber;
}
}
";
var expected =
@"
.foo + .foo {
background: amber;
}
.foo + .foo {
background: amber;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorMultiplied()
{
var input =
@"
.foo, .bar {
& + & {
background: amber;
}
}
";
var expected =
@"
.foo + .foo,
.foo + .bar,
.bar + .foo,
.bar + .bar {
background: amber;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorMultipliedDouble()
{
var input =
@"
.foo, .bar {
a, b {
& > & {
background: amber;
}
}
}
";
var expected =
@"
.foo a > .foo a,
.foo a > .bar a,
.foo a > .foo b,
.foo a > .bar b,
.bar a > .foo a,
.bar a > .bar a,
.bar a > .foo b,
.bar a > .bar b,
.foo b > .foo a,
.foo b > .bar a,
.foo b > .foo b,
.foo b > .bar b,
.bar b > .foo a,
.bar b > .bar a,
.bar b > .foo b,
.bar b > .bar b {
background: amber;
}
";
AssertLess(input, expected);
}
[Test]
public void IdSelectors()
{
var input =
@"
#all { color: blue; }
#the { color: blue; }
#same { color: blue; }
";
var expected = @"
#all {
color: blue;
}
#the {
color: blue;
}
#same {
color: blue;
}
";
AssertLess(input, expected);
}
[Test]
public void Tag()
{
var input = @"
td {
margin: 0;
padding: 0;
}
";
var expected = @"
td {
margin: 0;
padding: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void TwoTags()
{
var input = @"
td,
input {
line-height: 1em;
}
";
AssertLessUnchanged(input);
}
[Test]
public void MultipleTags()
{
var input =
@"
ul, li, div, q, blockquote, textarea {
margin: 0;
}
";
var expected = @"
ul,
li,
div,
q,
blockquote,
textarea {
margin: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void DecendantSelectorWithTabs()
{
var input = "td \t input { line-height: 1em; }";
var expected = @"
td input {
line-height: 1em;
}
";
AssertLess(input, expected);
}
[Test]
public void NestedCombinedSelector()
{
var input = @"
#parentRuleSet {
.selector1.selector2 { position: fixed; }
}";
var expected = @"
#parentRuleSet .selector1.selector2 {
position: fixed;
}";
AssertLess(input, expected);
}
[Test]
public void DynamicSelectors()
{
var input = @"
@a: 2;
a:nth-child(@a) {
border: 1px;
}";
var expected = @"
a:nth-child(2) {
border: 1px;
}";
AssertLess(input, expected);
}
[Test]
public void PseudoSelectors()
{
// from less.js bug 663
var input = @"
.other ::fnord { color: red }
.other::fnord { color: red }
.other {
::bnord {color: red }
&::bnord {color: red }
}";
var expected = @"
.other ::fnord {
color: red;
}
.other::fnord {
color: red;
}
.other ::bnord {
color: red;
}
.other::bnord {
color: red;
}";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorWhenNoParentExists1()
{
//comes up in bootstrap
var input = @"
.placeholder(@color) {
&:-moz-placeholder {
color: @color;
}
&:-ms-input-placeholder {
color: @color;
}
&::-webkit-input-placeholder {
color: @color;
}
}
.placeholder(red);
";
var expected = @"
:-moz-placeholder {
color: red;
}
:-ms-input-placeholder {
color: red;
}
::-webkit-input-placeholder {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorWhenNoParentExists2()
{
var input = @"
.placeholder(@color) {
.foo &.bar {
color: @color;
}
}
.placeholder(red);
";
var expected = @"
.foo .bar {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void VariableSelector()
{
var input = @"// Variables
@mySelector: banner;
// Usage
.@{mySelector} {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}";
var expected = @".banner {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}";
AssertLess(input,expected);
}
[Test]
public void VariableSelectorInRecursiveMixin()
{
var input = @"
.span (@index) {
margin: @index;
}
.spanX (@index) when (@index > 0) {
.span@{index} { .span(@index); }
.spanX(@index - 1);
}
.spanX(2);
";
var expected = @"
.span2 {
margin: 2;
}
.span1 {
margin: 1;
}
";
AssertLess(input, expected);
}
[Test]
public void AttributeCharacterTest()
{
var input = @"
.item[data-cra_zy-attr1b-ut3=bold] {
foo: bar;
}";
AssertLessUnchanged(input);
}
[Test]
public void SelectorInterpolation1()
{
var input = @"
@num: 2;
:nth-child(@{num}):nth-child(@num) {
foo: bar;
}";
var expected = @"
:nth-child(2):nth-child(2) {
foo: bar;
}";
AssertLess(input, expected);
}
[Test]
public void SelectorInterpolation2()
{
var input = @"
@theme: blood;
.@{theme} {
foo: bar;
}";
var expected = @"
.blood {
foo: bar;
}";
AssertLess(input, expected);
}
[Test]
public void SelectorInterpolationAndParent()
{
var input = @"
@theme: blood;
.@{theme} {
.red& {
foo: bar;
}
}";
var expected = @"
.red.blood {
foo: bar;
}";
AssertLess(input, expected);
}
[Test]
public void SelectorInterpolationAndParent2()
{
var input = @"
@theme: blood;
.@{theme} {
.red& {
foo: bar;
}
}";
var expected = @"
.red.blood {
foo: bar;
}";
AssertLess(input, expected);
}
[Test]
public void EscapedSelector()
{
var input = @"
#odd\:id,
[odd\.attr] {
foo: bar;
}";
AssertLessUnchanged(input);
}
[Test]
public void MixedCaseAttributeSelector()
{
var input = @"
img[imgType=""sort""] {
foo: bar;
}";
AssertLessUnchanged(input);
}
[Test]
public void MultipleIdenticalSelectorsAreOutputOnlyOnce()
{
var input = @"
.sel1, .sel2 {
float: left;
}
.test:extend(.sel1 all, .sel2 all) { }
";
var expected = @"
.sel1,
.sel2,
.test {
float: left;
}";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorWithVariableInterpolation() {
var input = @"
.test {
@var: 1;
&-@{var} {
color: black;
}
}
";
var expected = @"
.test-1 {
color: black;
}";
AssertLess(input, expected);
}
[Test]
public void ParentSelectorWithVariableInterpolationIsCallable() {
var input = @"
.test {
@var: 1;
&-@{var} {
color: black;
}
}
.call {
.test-1;
}
";
var expected = @"
.test-1 {
color: black;
}
.call {
color: #000000;
}";
AssertLess(input, expected);
}
}
}
| |
namespace GitVersion
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text.RegularExpressions;
public class ArgumentParser
{
public static Arguments ParseArguments(string commandLineArguments)
{
return ParseArguments(commandLineArguments.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList());
}
public static Arguments ParseArguments(List<string> commandLineArguments)
{
if (commandLineArguments.Count == 0)
{
return new Arguments
{
TargetPath = Environment.CurrentDirectory
};
}
var firstArgument = commandLineArguments.First();
if (IsHelp(firstArgument))
{
return new Arguments
{
IsHelp = true
};
}
if (IsInit(firstArgument))
{
return new Arguments
{
TargetPath = Environment.CurrentDirectory,
Init = true
};
}
if (commandLineArguments.Count == 1 && !(commandLineArguments[0].StartsWith("-") || commandLineArguments[0].StartsWith("/")))
{
return new Arguments
{
TargetPath = firstArgument
};
}
List<string> namedArguments;
var arguments = new Arguments();
if (firstArgument.StartsWith("-") || firstArgument.StartsWith("/"))
{
arguments.TargetPath = Environment.CurrentDirectory;
namedArguments = commandLineArguments;
}
else
{
arguments.TargetPath = firstArgument;
namedArguments = commandLineArguments.Skip(1).ToList();
}
var args = CollectSwitchesAndValuesFromArguments(namedArguments);
foreach (var name in args.AllKeys)
{
var values = args.GetValues(name);
string value = null;
if (values != null)
{
//Currently, no arguments use more than one value, so having multiple values is an input error.
//In the future, this exception can be removed to support multiple values for a switch.
if (values.Length > 1) throw new WarningException(string.Format("Could not parse command line parameter '{0}'.", values[1]));
value = values.FirstOrDefault();
}
if (IsSwitch("l", name))
{
arguments.LogFilePath = value;
continue;
}
if (IsSwitch("targetpath", name))
{
arguments.TargetPath = value;
continue;
}
if (IsSwitch("dynamicRepoLocation", name))
{
arguments.DynamicRepositoryLocation = value;
continue;
}
if (IsSwitch("url", name))
{
arguments.TargetUrl = value;
continue;
}
if (IsSwitch("b", name))
{
arguments.TargetBranch = value;
continue;
}
if (IsSwitch("u", name))
{
arguments.Authentication.Username = value;
continue;
}
if (IsSwitch("p", name))
{
arguments.Authentication.Password = value;
continue;
}
if (IsSwitch("c", name))
{
arguments.CommitId = value;
continue;
}
if (IsSwitch("exec", name))
{
arguments.Exec = value;
continue;
}
if (IsSwitch("execargs", name))
{
arguments.ExecArgs = value;
continue;
}
if (IsSwitch("proj", name))
{
arguments.Proj = value;
continue;
}
if (IsSwitch("projargs", name))
{
arguments.ProjArgs = value;
continue;
}
if (IsSwitch("updateAssemblyInfo", name))
{
if (new[] { "1", "true" }.Contains(value))
{
arguments.UpdateAssemblyInfo = true;
}
else if (new[] { "0", "false" }.Contains(value))
{
arguments.UpdateAssemblyInfo = false;
}
else if (!IsSwitchArgument(value))
{
arguments.UpdateAssemblyInfo = true;
arguments.UpdateAssemblyInfoFileName = value;
}
else
{
arguments.UpdateAssemblyInfo = true;
}
continue;
}
if (IsSwitch("assemblyversionformat", name))
{
throw new WarningException("assemblyversionformat switch removed, use AssemblyVersioningScheme configuration value instead");
}
if (IsSwitch("v", name) || IsSwitch("showvariable", name))
{
string versionVariable = null;
if (!string.IsNullOrWhiteSpace(value))
{
versionVariable = VersionVariables.AvailableVariables.SingleOrDefault(av => av.Equals(value.Replace("'", ""), StringComparison.CurrentCultureIgnoreCase));
}
if (versionVariable == null)
{
var messageFormat = "{0} requires a valid version variable. Available variables are:\n{1}";
var message = string.Format(messageFormat, name, String.Join(", ", VersionVariables.AvailableVariables.Select(x=>string.Concat("'", x, "'"))));
throw new WarningException(message);
}
arguments.ShowVariable = versionVariable;
continue;
}
if (IsSwitch("showConfig", name))
{
if (new[] { "1", "true" }.Contains(value))
{
arguments.ShowConfig = true;
}
else if (new[] { "0", "false" }.Contains(value))
{
arguments.UpdateAssemblyInfo = false;
}
else
{
arguments.ShowConfig = true;
}
continue;
}
if (IsSwitch("output", name))
{
OutputType outputType;
if (!Enum.TryParse(value, true, out outputType))
{
throw new WarningException(string.Format("Value '{0}' cannot be parsed as output type, please use 'json' or 'buildserver'", value));
}
arguments.Output = outputType;
continue;
}
if (IsSwitch("nofetch", name))
{
arguments.NoFetch = true;
continue;
}
throw new WarningException(string.Format("Could not parse command line parameter '{0}'.", name));
}
return arguments;
}
static NameValueCollection CollectSwitchesAndValuesFromArguments(List<string> namedArguments)
{
var args = new NameValueCollection();
string currentKey = null;
for (var index = 0; index < namedArguments.Count; index = index + 1)
{
var arg = namedArguments[index];
//If this is a switch, create new name/value entry for it, with a null value.
if (IsSwitchArgument(arg))
{
currentKey = arg;
args.Add(currentKey, null);
}
//If this is a value (not a switch)
else
{
//And if the current switch does not have a value yet, set it's value to this argument.
if (String.IsNullOrEmpty(args[currentKey]))
{
args[currentKey] = arg;
}
//Otherwise add the value under the same switch.
else
{
args.Add(currentKey, arg);
}
}
}
return args;
}
static bool IsSwitchArgument(string value)
{
return value != null && (value.StartsWith("-") || value.StartsWith("/"))
&& !Regex.Match(value, @"/\w+:").Success; //Exclude msbuild & project parameters in form /blah:, which should be parsed as values, not switch names.
}
static bool IsSwitch(string switchName, string value)
{
if (value.StartsWith("-"))
{
value = value.Remove(0, 1);
}
if (value.StartsWith("/"))
{
value = value.Remove(0, 1);
}
return (string.Equals(switchName, value, StringComparison.InvariantCultureIgnoreCase));
}
static bool IsInit(string singleArgument)
{
return singleArgument.Equals("init", StringComparison.InvariantCultureIgnoreCase);
}
static bool IsHelp(string singleArgument)
{
return (singleArgument == "?") ||
IsSwitch("h", singleArgument) ||
IsSwitch("help", singleArgument) ||
IsSwitch("?", singleArgument);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.PythonTools.Analysis;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.PythonTools.Intellisense {
/// <summary>
/// Parses an expression in reverse to get the experssion we need to
/// analyze for completion, quick info, or signature help.
/// </summary>
class ReverseExpressionParser : IEnumerable<ClassificationSpan> {
private readonly ITextSnapshot _snapshot;
private readonly ITextBuffer _buffer;
private readonly ITrackingSpan _span;
private ITextSnapshotLine _curLine;
private readonly PythonClassifier _classifier;
private static readonly HashSet<string> _assignOperators = new HashSet<string> {
"=" , "+=" , "-=" , "/=" , "%=" , "^=" , "*=" , "//=" , "&=" , "|=" , ">>=" , "<<=" , "**=", "@="
};
public ReverseExpressionParser(ITextSnapshot snapshot, ITextBuffer buffer, ITrackingSpan span) {
_snapshot = snapshot;
_buffer = buffer;
_span = span;
var loc = span.GetSpan(snapshot);
var line = _curLine = snapshot.GetLineFromPosition(loc.Start);
var targetSpan = new Span(line.Start.Position, span.GetEndPoint(snapshot).Position - line.Start.Position);
if (!_buffer.Properties.TryGetProperty(typeof(PythonClassifier), out _classifier) || _classifier == null) {
throw new ArgumentException("Failed to get classifier from buffer");
}
}
public SnapshotSpan? GetExpressionRange(bool forCompletion = true, int nesting = 0) {
int dummy;
SnapshotPoint? dummyPoint;
string lastKeywordArg;
bool isParameterName;
return GetExpressionRange(nesting, out dummy, out dummyPoint, out lastKeywordArg, out isParameterName, forCompletion);
}
internal static IEnumerator<ClassificationSpan> ForwardClassificationSpanEnumerator(PythonClassifier classifier, SnapshotPoint startPoint) {
var startLine = startPoint.GetContainingLine();
int curLine = startLine.LineNumber;
if (startPoint > startLine.End) {
// May occur if startPoint is between \r and \n
startPoint = startLine.End;
}
var tokens = classifier.GetClassificationSpans(new SnapshotSpan(startPoint, startLine.End));
for (; ; ) {
for (int i = 0; i < tokens.Count; ++i) {
yield return tokens[i];
}
// indicate the line break
yield return null;
++curLine;
if (curLine < startPoint.Snapshot.LineCount) {
var nextLine = startPoint.Snapshot.GetLineFromLineNumber(curLine);
tokens = classifier.GetClassificationSpans(nextLine.Extent);
} else {
break;
}
}
}
internal static IEnumerator<ClassificationSpan> ReverseClassificationSpanEnumerator(PythonClassifier classifier, SnapshotPoint startPoint) {
var startLine = startPoint.GetContainingLine();
int curLine = startLine.LineNumber;
var tokens = classifier.GetClassificationSpans(new SnapshotSpan(startLine.Start, startPoint));
for (; ; ) {
for (int i = tokens.Count - 1; i >= 0; i--) {
yield return tokens[i];
}
// indicate the line break
yield return null;
curLine--;
if (curLine >= 0) {
var prevLine = startPoint.Snapshot.GetLineFromLineNumber(curLine);
tokens = classifier.GetClassificationSpans(prevLine.Extent);
} else {
break;
}
}
}
/// <summary>
/// Walks backwards to figure out if we're a parameter name which comes after a (
/// </summary>
private bool IsParameterNameOpenParen(IEnumerator<ClassificationSpan> enumerator) {
if (MoveNextSkipExplicitNewLines(enumerator)) {
if (enumerator.Current.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier)) {
if (MoveNextSkipExplicitNewLines(enumerator) &&
enumerator.Current.ClassificationType == Classifier.Provider.Keyword &&
enumerator.Current.Span.GetText() == "def") {
return true;
}
}
}
return false;
}
/// <summary>
/// Walks backwards to figure out if we're a parameter name which comes after a comma.
/// </summary>
private bool IsParameterNameComma(IEnumerator<ClassificationSpan> enumerator) {
int groupingLevel = 1;
while (MoveNextSkipExplicitNewLines(enumerator)) {
if (enumerator.Current.ClassificationType == Classifier.Provider.Keyword) {
if (enumerator.Current.Span.GetText() == "def" && groupingLevel == 0) {
return true;
}
if (PythonKeywords.IsOnlyStatementKeyword(enumerator.Current.Span.GetText())) {
return false;
}
}
if (enumerator.Current.IsOpenGrouping()) {
groupingLevel--;
if (groupingLevel == 0) {
return IsParameterNameOpenParen(enumerator);
}
} else if (enumerator.Current.IsCloseGrouping()) {
groupingLevel++;
}
}
return false;
}
private bool MoveNextSkipExplicitNewLines(IEnumerator<ClassificationSpan> enumerator) {
while (enumerator.MoveNext()) {
if (enumerator.Current == null) {
while (enumerator.Current == null) {
if (!enumerator.MoveNext()) {
return false;
}
}
if (!IsExplicitLineJoin(enumerator.Current)) {
return true;
}
} else {
return true;
}
}
return false;
}
/// <summary>
/// Gets the range of the expression to the left of our starting span.
/// </summary>
/// <param name="nesting">1 if we have an opening parenthesis for sig completion</param>
/// <param name="paramIndex">The current parameter index.</param>
/// <returns></returns>
public SnapshotSpan? GetExpressionRange(int nesting, out int paramIndex, out SnapshotPoint? sigStart, out string lastKeywordArg, out bool isParameterName, bool forCompletion = true) {
SnapshotSpan? start = null;
paramIndex = 0;
sigStart = null;
bool nestingChanged = false, lastTokenWasCommaOrOperator = true, lastTokenWasKeywordArgAssignment = false;
int otherNesting = 0;
bool isSigHelp = nesting != 0;
isParameterName = false;
lastKeywordArg = null;
ClassificationSpan lastToken = null;
// Walks backwards over all the lines
var enumerator = ReverseClassificationSpanEnumerator(Classifier, _span.GetSpan(_snapshot).End);
if (enumerator.MoveNext()) {
if (enumerator.Current != null && enumerator.Current.ClassificationType == this.Classifier.Provider.StringLiteral) {
return enumerator.Current.Span;
}
lastToken = enumerator.Current;
while (ShouldSkipAsLastToken(lastToken, forCompletion) && enumerator.MoveNext()) {
// skip trailing new line if the user is hovering at the end of the line
if (lastToken == null && (nesting + otherNesting == 0)) {
// new line out of a grouping...
return _span.GetSpan(_snapshot);
}
lastToken = enumerator.Current;
}
int currentParamAtLastColon = -1; // used to track the current param index at this last colon, before we hit a lambda.
SnapshotSpan? startAtLastToken = null;
// Walk backwards over the tokens in the current line
do {
var token = enumerator.Current;
if (token == null) {
// new line
if (nesting != 0 || otherNesting != 0 || (enumerator.MoveNext() && IsExplicitLineJoin(enumerator.Current))) {
// we're in a grouping, or the previous token is an explicit line join, we'll keep going.
continue;
} else {
break;
}
}
var text = token.Span.GetText();
if (text == "(") {
if (nesting != 0) {
nesting--;
nestingChanged = true;
if (nesting == 0) {
if (sigStart == null) {
sigStart = token.Span.Start;
}
}
} else {
if (start == null && !forCompletion) {
// hovering directly over an open paren, don't provide a tooltip
return null;
}
// figure out if we're a parameter definition
isParameterName = IsParameterNameOpenParen(enumerator);
break;
}
lastTokenWasCommaOrOperator = true;
lastTokenWasKeywordArgAssignment = false;
} else if (token.IsOpenGrouping()) {
if (otherNesting != 0) {
otherNesting--;
} else {
if (nesting == 0) {
if (start == null) {
return null;
}
break;
}
paramIndex = 0;
}
nestingChanged = true;
lastTokenWasCommaOrOperator = true;
lastTokenWasKeywordArgAssignment = false;
} else if (text == ")") {
nesting++;
nestingChanged = true;
lastTokenWasCommaOrOperator = true;
lastTokenWasKeywordArgAssignment = false;
} else if (token.IsCloseGrouping()) {
otherNesting++;
nestingChanged = true;
lastTokenWasCommaOrOperator = true;
lastTokenWasKeywordArgAssignment = false;
} else if (token.ClassificationType == Classifier.Provider.Keyword ||
token.ClassificationType == Classifier.Provider.Operator) {
lastTokenWasKeywordArgAssignment = false;
if (token.ClassificationType == Classifier.Provider.Keyword && text == "lambda") {
if (currentParamAtLastColon != -1) {
paramIndex = currentParamAtLastColon;
currentParamAtLastColon = -1;
} else {
// fabcd(lambda a, b, c[PARAMINFO]
// We have to be the 1st param.
paramIndex = 0;
}
}
if (text == ":") {
startAtLastToken = start;
currentParamAtLastColon = paramIndex;
}
if (nesting == 0 && otherNesting == 0) {
if (start == null) {
// http://pytools.codeplex.com/workitem/560
// yield_value = 42
// def f():
// yield<ctrl-space>
// yield <ctrl-space>
//
// If we're next to the keyword, just return the keyword.
// If we're after the keyword, return the span of the text proceeding
// the keyword so we can complete after it.
//
// Also repros with "return <ctrl-space>" or "print <ctrl-space>" both
// of which we weren't reporting completions for before
if (forCompletion) {
if (token.Span.IntersectsWith(_span.GetSpan(_snapshot))) {
return token.Span;
} else {
return _span.GetSpan(_snapshot);
}
}
// hovering directly over a keyword, don't provide a tooltip
return null;
} else if ((nestingChanged || forCompletion) && token.ClassificationType == Classifier.Provider.Keyword && (text == "def" || text == "class")) {
return null;
}
if (text == "*" || text == "**") {
if (MoveNextSkipExplicitNewLines(enumerator)) {
if (enumerator.Current.ClassificationType == Classifier.Provider.CommaClassification) {
isParameterName = IsParameterNameComma(enumerator);
} else if (enumerator.Current.IsOpenGrouping() && enumerator.Current.Span.GetText() == "(") {
isParameterName = IsParameterNameOpenParen(enumerator);
}
}
}
break;
} else if ((token.ClassificationType == Classifier.Provider.Keyword &&
PythonKeywords.IsOnlyStatementKeyword(text)) ||
(token.ClassificationType == Classifier.Provider.Operator && IsAssignmentOperator(text))) {
if (nesting != 0 && text == "=") {
// keyword argument allowed in signatures
lastTokenWasKeywordArgAssignment = lastTokenWasCommaOrOperator = true;
} else if (start == null || (nestingChanged && nesting != 0)) {
return null;
} else {
break;
}
} else if (token.ClassificationType == Classifier.Provider.Keyword &&
(text == "if" || text == "else")) {
// if and else can be used in an expression context or a statement context
if (currentParamAtLastColon != -1) {
start = startAtLastToken;
if (start == null) {
return null;
}
break;
}
}
lastTokenWasCommaOrOperator = true;
} else if (token.ClassificationType == Classifier.Provider.DotClassification) {
lastTokenWasCommaOrOperator = true;
lastTokenWasKeywordArgAssignment = false;
} else if (token.ClassificationType == Classifier.Provider.CommaClassification) {
lastTokenWasCommaOrOperator = true;
lastTokenWasKeywordArgAssignment = false;
if (nesting == 0 && otherNesting == 0) {
if (start == null && !forCompletion) {
return null;
}
isParameterName = IsParameterNameComma(enumerator);
break;
} else if (nesting == 1 && otherNesting == 0 && sigStart == null) {
paramIndex++;
}
} else if (token.ClassificationType == Classifier.Provider.Comment) {
return null;
} else if (!lastTokenWasCommaOrOperator) {
if (nesting == 0 && otherNesting == 0) {
break;
}
} else {
if (lastTokenWasKeywordArgAssignment &&
token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier) &&
lastKeywordArg == null) {
if (paramIndex == 0) {
lastKeywordArg = text;
} else {
lastKeywordArg = "";
}
}
lastTokenWasCommaOrOperator = false;
}
start = token.Span;
} while (enumerator.MoveNext());
}
if (start.HasValue && lastToken != null && (lastToken.Span.End.Position - start.Value.Start.Position) >= 0) {
return new SnapshotSpan(
Snapshot,
new Span(
start.Value.Start.Position,
lastToken.Span.End.Position - start.Value.Start.Position
)
);
}
return _span.GetSpan(_snapshot);
}
private static bool IsAssignmentOperator(string text) {
return _assignOperators.Contains(text);
}
internal static bool IsExplicitLineJoin(ClassificationSpan cur) {
if (cur != null && cur.ClassificationType.IsOfType(PythonPredefinedClassificationTypeNames.Operator)) {
var text = cur.Span.GetText();
return text == "\\\r\n" || text == "\\\r" || text == "\n";
}
return false;
}
/// <summary>
/// Returns true if we should skip this token when it's the last token that the user hovers over. Currently true
/// for new lines and dot classifications.
/// </summary>
private bool ShouldSkipAsLastToken(ClassificationSpan lastToken, bool forCompletion) {
return lastToken == null || (
(lastToken.ClassificationType.Classification == PredefinedClassificationTypeNames.WhiteSpace &&
(lastToken.Span.GetText() == "\r\n" || lastToken.Span.GetText() == "\n" || lastToken.Span.GetText() == "\r")) ||
(lastToken.ClassificationType == Classifier.Provider.DotClassification && !forCompletion));
}
public PythonClassifier Classifier {
get { return _classifier; }
}
public ITextSnapshot Snapshot {
get { return _snapshot; }
}
public ITextBuffer Buffer {
get { return _buffer; }
}
public ITrackingSpan Span {
get { return _span; }
}
public IEnumerator<ClassificationSpan> GetEnumerator() {
return ReverseClassificationSpanEnumerator(Classifier, _span.GetSpan(_snapshot).End);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return ReverseClassificationSpanEnumerator(Classifier, _span.GetSpan(_snapshot).End);
}
internal bool IsInGrouping() {
// We assume that groupings are correctly matched and keep a simple
// nesting count.
int nesting = 0;
foreach (var token in this) {
if (token == null) {
continue;
}
if (token.IsCloseGrouping()) {
nesting++;
} else if (token.IsOpenGrouping()) {
if (nesting-- == 0) {
return true;
}
} else if (token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Keyword) &&
PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText())) {
return false;
}
}
return false;
}
internal SnapshotSpan? GetStatementRange() {
var tokenStack = new Stack<ClassificationSpan>();
bool eol = false, finishLine = false;
// Collect all the tokens until we know we're not in any groupings
foreach (var token in this) {
if (eol) {
eol = false;
if (!IsExplicitLineJoin(token)) {
tokenStack.Push(null);
if (finishLine) {
break;
}
}
}
if (token == null) {
eol = true;
continue;
}
tokenStack.Push(token);
if (token.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Keyword) &&
PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText())) {
finishLine = true;
}
}
if (tokenStack.Count == 0) {
return null;
}
// Now scan forward through the tokens setting our current statement
// start point.
SnapshotPoint start = new SnapshotPoint(_snapshot, 0);
SnapshotPoint end = start;
bool setStart = true;
int nesting = 0;
foreach (var token in tokenStack) {
if (setStart && token != null) {
start = token.Span.Start;
setStart = false;
}
if (token == null) {
if (nesting == 0) {
setStart = true;
}
} else {
end = token.Span.End;
if (token.IsOpenGrouping()) {
++nesting;
} else if (token.IsCloseGrouping()) {
--nesting;
}
}
}
// Keep going to find the end of the statement
using (var e = ForwardClassificationSpanEnumerator(Classifier, Span.GetStartPoint(Snapshot))) {
eol = false;
while (e.MoveNext()) {
if (e.Current == null) {
if (nesting == 0) {
break;
}
eol = true;
} else {
eol = false;
if (setStart) {
// Final token was EOL, so our start is the first
// token moving forwards
start = e.Current.Span.Start;
setStart = false;
}
end = e.Current.Span.End;
}
}
if (setStart) {
start = Span.GetStartPoint(Snapshot);
}
if (eol) {
end = Span.GetEndPoint(Snapshot);
}
}
if (end <= start) {
// No statement here
return null;
}
return new SnapshotSpan(start, end);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcav = Google.Cloud.Asset.V1;
using sys = System;
namespace Google.Cloud.Asset.V1
{
/// <summary>Resource name for the <c>Feed</c> resource.</summary>
public sealed partial class FeedName : gax::IResourceName, sys::IEquatable<FeedName>
{
/// <summary>The possible contents of <see cref="FeedName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/feeds/{feed}</c>.</summary>
ProjectFeed = 1,
/// <summary>A resource name with pattern <c>folders/{folder}/feeds/{feed}</c>.</summary>
FolderFeed = 2,
/// <summary>A resource name with pattern <c>organizations/{organization}/feeds/{feed}</c>.</summary>
OrganizationFeed = 3,
}
private static gax::PathTemplate s_projectFeed = new gax::PathTemplate("projects/{project}/feeds/{feed}");
private static gax::PathTemplate s_folderFeed = new gax::PathTemplate("folders/{folder}/feeds/{feed}");
private static gax::PathTemplate s_organizationFeed = new gax::PathTemplate("organizations/{organization}/feeds/{feed}");
/// <summary>Creates a <see cref="FeedName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="FeedName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static FeedName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new FeedName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="FeedName"/> with the pattern <c>projects/{project}/feeds/{feed}</c>.</summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="FeedName"/> constructed from the provided ids.</returns>
public static FeedName FromProjectFeed(string projectId, string feedId) =>
new FeedName(ResourceNameType.ProjectFeed, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)));
/// <summary>Creates a <see cref="FeedName"/> with the pattern <c>folders/{folder}/feeds/{feed}</c>.</summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="FeedName"/> constructed from the provided ids.</returns>
public static FeedName FromFolderFeed(string folderId, string feedId) =>
new FeedName(ResourceNameType.FolderFeed, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)));
/// <summary>
/// Creates a <see cref="FeedName"/> with the pattern <c>organizations/{organization}/feeds/{feed}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="FeedName"/> constructed from the provided ids.</returns>
public static FeedName FromOrganizationFeed(string organizationId, string feedId) =>
new FeedName(ResourceNameType.OrganizationFeed, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FeedName"/> with pattern
/// <c>projects/{project}/feeds/{feed}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FeedName"/> with pattern <c>projects/{project}/feeds/{feed}</c>
/// .
/// </returns>
public static string Format(string projectId, string feedId) => FormatProjectFeed(projectId, feedId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FeedName"/> with pattern
/// <c>projects/{project}/feeds/{feed}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FeedName"/> with pattern <c>projects/{project}/feeds/{feed}</c>
/// .
/// </returns>
public static string FormatProjectFeed(string projectId, string feedId) =>
s_projectFeed.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FeedName"/> with pattern
/// <c>folders/{folder}/feeds/{feed}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FeedName"/> with pattern <c>folders/{folder}/feeds/{feed}</c>.
/// </returns>
public static string FormatFolderFeed(string folderId, string feedId) =>
s_folderFeed.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FeedName"/> with pattern
/// <c>organizations/{organization}/feeds/{feed}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FeedName"/> with pattern
/// <c>organizations/{organization}/feeds/{feed}</c>.
/// </returns>
public static string FormatOrganizationFeed(string organizationId, string feedId) =>
s_organizationFeed.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)));
/// <summary>Parses the given resource name string into a new <see cref="FeedName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/feeds/{feed}</c></description></item>
/// <item><description><c>folders/{folder}/feeds/{feed}</c></description></item>
/// <item><description><c>organizations/{organization}/feeds/{feed}</c></description></item>
/// </list>
/// </remarks>
/// <param name="feedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="FeedName"/> if successful.</returns>
public static FeedName Parse(string feedName) => Parse(feedName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="FeedName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/feeds/{feed}</c></description></item>
/// <item><description><c>folders/{folder}/feeds/{feed}</c></description></item>
/// <item><description><c>organizations/{organization}/feeds/{feed}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="feedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="FeedName"/> if successful.</returns>
public static FeedName Parse(string feedName, bool allowUnparsed) =>
TryParse(feedName, allowUnparsed, out FeedName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>Tries to parse the given resource name string into a new <see cref="FeedName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/feeds/{feed}</c></description></item>
/// <item><description><c>folders/{folder}/feeds/{feed}</c></description></item>
/// <item><description><c>organizations/{organization}/feeds/{feed}</c></description></item>
/// </list>
/// </remarks>
/// <param name="feedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="FeedName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string feedName, out FeedName result) => TryParse(feedName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="FeedName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/feeds/{feed}</c></description></item>
/// <item><description><c>folders/{folder}/feeds/{feed}</c></description></item>
/// <item><description><c>organizations/{organization}/feeds/{feed}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="feedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="FeedName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string feedName, bool allowUnparsed, out FeedName result)
{
gax::GaxPreconditions.CheckNotNull(feedName, nameof(feedName));
gax::TemplatedResourceName resourceName;
if (s_projectFeed.TryParseName(feedName, out resourceName))
{
result = FromProjectFeed(resourceName[0], resourceName[1]);
return true;
}
if (s_folderFeed.TryParseName(feedName, out resourceName))
{
result = FromFolderFeed(resourceName[0], resourceName[1]);
return true;
}
if (s_organizationFeed.TryParseName(feedName, out resourceName))
{
result = FromOrganizationFeed(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(feedName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private FeedName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string feedId = null, string folderId = null, string organizationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
FeedId = feedId;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="FeedName"/> class from the component parts of pattern
/// <c>projects/{project}/feeds/{feed}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
public FeedName(string projectId, string feedId) : this(ResourceNameType.ProjectFeed, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Feed</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FeedId { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectFeed: return s_projectFeed.Expand(ProjectId, FeedId);
case ResourceNameType.FolderFeed: return s_folderFeed.Expand(FolderId, FeedId);
case ResourceNameType.OrganizationFeed: return s_organizationFeed.Expand(OrganizationId, FeedId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as FeedName);
/// <inheritdoc/>
public bool Equals(FeedName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(FeedName a, FeedName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(FeedName a, FeedName b) => !(a == b);
}
public partial class ExportAssetsRequest
{
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get => string.IsNullOrEmpty(Parent) ? null : gax::UnparsedResourceName.Parse(Parent);
set => Parent = value?.ToString() ?? "";
}
}
public partial class ListAssetsRequest
{
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get => string.IsNullOrEmpty(Parent) ? null : gax::UnparsedResourceName.Parse(Parent);
set => Parent = value?.ToString() ?? "";
}
}
public partial class BatchGetAssetsHistoryRequest
{
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get => string.IsNullOrEmpty(Parent) ? null : gax::UnparsedResourceName.Parse(Parent);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetFeedRequest
{
/// <summary>
/// <see cref="gcav::FeedName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::FeedName FeedName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::FeedName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeleteFeedRequest
{
/// <summary>
/// <see cref="gcav::FeedName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::FeedName FeedName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::FeedName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Feed
{
/// <summary>
/// <see cref="gcav::FeedName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::FeedName FeedName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::FeedName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Lucene.Net.Search.Spans
{
/*
* 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using IBits = Lucene.Net.Util.IBits;
using Term = Lucene.Net.Index.Term;
using TermContext = Lucene.Net.Index.TermContext;
/// <summary>
/// Similar to <see cref="NearSpansOrdered"/>, but for the unordered case.
/// <para/>
/// Expert:
/// Only public for subclassing. Most implementations should not need this class
/// </summary>
public class NearSpansUnordered : Spans
{
private SpanNearQuery query;
private IList<SpansCell> ordered = new List<SpansCell>(); // spans in query order
private Spans[] subSpans;
private int slop; // from query
private SpansCell first; // linked list of spans
private SpansCell last; // sorted by doc only
private int totalLength; // sum of current lengths
private CellQueue queue; // sorted queue of spans
private SpansCell max; // max element in queue
private bool more = true; // true iff not done
private bool firstTime = true; // true before first next()
private class CellQueue : Util.PriorityQueue<SpansCell>
{
private readonly NearSpansUnordered outerInstance;
public CellQueue(NearSpansUnordered outerInstance, int size)
: base(size)
{
this.outerInstance = outerInstance;
}
protected internal override bool LessThan(SpansCell spans1, SpansCell spans2)
{
if (spans1.Doc == spans2.Doc)
{
return NearSpansOrdered.DocSpansOrdered(spans1, spans2);
}
else
{
return spans1.Doc < spans2.Doc;
}
}
}
/// <summary>
/// Wraps a <see cref="Spans"/>, and can be used to form a linked list. </summary>
private class SpansCell : Spans
{
private readonly NearSpansUnordered outerInstance;
internal Spans spans;
internal SpansCell next;
private int length = -1;
private int index;
public SpansCell(NearSpansUnordered outerInstance, Spans spans, int index)
{
this.outerInstance = outerInstance;
this.spans = spans;
this.index = index;
}
public override bool Next()
{
return Adjust(spans.Next());
}
public override bool SkipTo(int target)
{
return Adjust(spans.SkipTo(target));
}
private bool Adjust(bool condition)
{
if (length != -1)
{
outerInstance.totalLength -= length; // subtract old length
}
if (condition)
{
length = End - Start;
outerInstance.totalLength += length; // add new length
if (outerInstance.max == null || Doc > outerInstance.max.Doc || (Doc == outerInstance.max.Doc) && (End > outerInstance.max.End))
{
outerInstance.max = this;
}
}
outerInstance.more = condition;
return condition;
}
public override int Doc
{
get { return spans.Doc; }
}
public override int Start
{
get { return spans.Start; }
}
// TODO: Remove warning after API has been finalized
public override int End
{
get { return spans.End; }
}
public override ICollection<byte[]> GetPayload()
{
return new List<byte[]>(spans.GetPayload());
}
// TODO: Remove warning after API has been finalized
public override bool IsPayloadAvailable
{
get
{
return spans.IsPayloadAvailable;
}
}
public override long GetCost()
{
return spans.GetCost();
}
public override string ToString()
{
return spans.ToString() + "#" + index;
}
}
public NearSpansUnordered(SpanNearQuery query, AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts)
{
this.query = query;
this.slop = query.Slop;
SpanQuery[] clauses = query.GetClauses();
queue = new CellQueue(this, clauses.Length);
subSpans = new Spans[clauses.Length];
for (int i = 0; i < clauses.Length; i++)
{
SpansCell cell = new SpansCell(this, clauses[i].GetSpans(context, acceptDocs, termContexts), i);
ordered.Add(cell);
subSpans[i] = cell.spans;
}
}
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public virtual Spans[] SubSpans
{
get { return subSpans; }
}
public override bool Next()
{
if (firstTime)
{
InitList(true);
ListToQueue(); // initialize queue
firstTime = false;
}
else if (more)
{
if (Min.Next()) // trigger further scanning
{
queue.UpdateTop(); // maintain queue
}
else
{
more = false;
}
}
while (more)
{
bool queueStale = false;
if (Min.Doc != max.Doc) // maintain list
{
QueueToList();
queueStale = true;
}
// skip to doc w/ all clauses
while (more && first.Doc < last.Doc)
{
more = first.SkipTo(last.Doc); // skip first upto last
FirstToLast(); // and move it to the end
queueStale = true;
}
if (!more)
{
return false;
}
// found doc w/ all clauses
if (queueStale) // maintain the queue
{
ListToQueue();
queueStale = false;
}
if (AtMatch)
{
return true;
}
more = Min.Next();
if (more)
{
queue.UpdateTop(); // maintain queue
}
}
return false; // no more matches
}
public override bool SkipTo(int target)
{
if (firstTime) // initialize
{
InitList(false);
for (SpansCell cell = first; more && cell != null; cell = cell.next)
{
more = cell.SkipTo(target); // skip all
}
if (more)
{
ListToQueue();
}
firstTime = false;
} // normal case
else
{
while (more && Min.Doc < target) // skip as needed
{
if (Min.SkipTo(target))
{
queue.UpdateTop();
}
else
{
more = false;
}
}
}
return more && (AtMatch || Next());
}
private SpansCell Min
{
get { return queue.Top; }
}
public override int Doc
{
get { return Min.Doc; }
}
public override int Start
{
get { return Min.Start; }
}
public override int End
{
get { return max.End; }
}
// TODO: Remove warning after API has been finalized
/// <summary>
/// WARNING: The List is not necessarily in order of the the positions </summary>
/// <returns> Collection of <see cref="T:byte[]"/> payloads </returns>
/// <exception cref="System.IO.IOException"> if there is a low-level I/O error </exception>
public override ICollection<byte[]> GetPayload()
{
var matchPayload = new HashSet<byte[]>();
for (var cell = first; cell != null; cell = cell.next)
{
if (cell.IsPayloadAvailable)
{
matchPayload.UnionWith(cell.GetPayload());
}
}
return matchPayload;
}
// TODO: Remove warning after API has been finalized
public override bool IsPayloadAvailable
{
get
{
SpansCell pointer = Min;
while (pointer != null)
{
if (pointer.IsPayloadAvailable)
{
return true;
}
pointer = pointer.next;
}
return false;
}
}
public override long GetCost()
{
long minCost = long.MaxValue;
for (int i = 0; i < subSpans.Length; i++)
{
minCost = Math.Min(minCost, subSpans[i].GetCost());
}
return minCost;
}
public override string ToString()
{
return this.GetType().Name + "(" + query.ToString() + ")@" + (firstTime ? "START" : (more ? (Doc + ":" + Start + "-" + End) : "END"));
}
private void InitList(bool next)
{
for (int i = 0; more && i < ordered.Count; i++)
{
SpansCell cell = ordered[i];
if (next)
{
more = cell.Next(); // move to first entry
}
if (more)
{
AddToList(cell); // add to list
}
}
}
private void AddToList(SpansCell cell)
{
if (last != null) // add next to end of list
{
last.next = cell;
}
else
{
first = cell;
}
last = cell;
cell.next = null;
}
private void FirstToLast()
{
last.next = first; // move first to end of list
last = first;
first = first.next;
last.next = null;
}
private void QueueToList()
{
last = first = null;
while (queue.Top != null)
{
AddToList(queue.Pop());
}
}
private void ListToQueue()
{
queue.Clear(); // rebuild queue
for (SpansCell cell = first; cell != null; cell = cell.next)
{
queue.Add(cell); // add to queue from list
}
}
private bool AtMatch
{
get { return (Min.Doc == max.Doc) && ((max.End - Min.Start - totalLength) <= slop); }
}
}
}
| |
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Text;
using System.Xml;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Build
{
public sealed class TFCommandManager : TfsVCCommandManager, ITfsVCCommandManager
{
public override TfsVCFeatures Features
{
get
{
return TfsVCFeatures.DefaultWorkfoldMap |
TfsVCFeatures.EscapedUrl |
TfsVCFeatures.GetFromUnmappedRoot |
TfsVCFeatures.LoginType |
TfsVCFeatures.Scorch;
}
}
// When output is redirected, TF.exe writes output using the current system code page
// (i.e. CP_ACP or code page 0). E.g. code page 1252 on an en-US box.
protected override Encoding OutputEncoding => StringUtil.GetSystemEncoding();
protected override string Switch => "/";
public string FilePath => Path.Combine(ExecutionContext.Variables.Agent_ServerOMDirectory, "tf.exe");
private string AppConfigFile => Path.Combine(ExecutionContext.Variables.Agent_ServerOMDirectory, "tf.exe.config");
private string AppConfigRestoreFile => Path.Combine(ExecutionContext.Variables.Agent_ServerOMDirectory, "tf.exe.config.restore");
// TODO: Remove AddAsync after last-saved-checkin-metadata problem is fixed properly.
public async Task AddAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "add", localPath);
}
public void CleanupProxySetting()
{
ArgUtil.File(AppConfigRestoreFile, "tf.exe.config.restore");
ExecutionContext.Debug("Restore default tf.exe.config.");
IOUtil.DeleteFile(AppConfigFile);
File.Copy(AppConfigRestoreFile, AppConfigFile);
}
public Task EulaAsync()
{
throw new NotSupportedException();
}
public async Task GetAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "get", $"/version:{SourceVersion}", "/recursive", "/overwrite", localPath);
}
public string ResolvePath(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
string localPath = RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "resolvePath", serverPath).GetAwaiter().GetResult();
return localPath?.Trim() ?? string.Empty;
}
// TODO: Fix scorch. Scorch blows up if a root mapping does not exist.
//
// No good workaround appears to exist. Attempting to resolve by workspace fails with
// the same error. Switching to "*" instead of passing "SourcesDirectory" allows the
// command to exit zero, but causes every source file to be deleted.
//
// The current approach taken is: allow the exception to bubble. The TfsVCSourceProvider
// will catch the exception, log it as a warning, throw away the workspace, and re-clone.
public async Task ScorchAsync() => await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "scorch", SourcesDirectory, "/recursive", "/diff", "/unmapped");
public void SetupProxy(string proxyUrl, string proxyUsername, string proxyPassword)
{
ArgUtil.File(AppConfigFile, "tf.exe.config");
if (!File.Exists(AppConfigRestoreFile))
{
Trace.Info("Take snapshot of current appconfig for restore modified appconfig.");
File.Copy(AppConfigFile, AppConfigRestoreFile);
}
else
{
// cleanup any appconfig changes from previous build.
CleanupProxySetting();
}
if (!string.IsNullOrEmpty(proxyUrl))
{
XmlDocument appConfig = new XmlDocument();
using (var appConfigStream = new FileStream(AppConfigFile, FileMode.Open, FileAccess.Read))
{
appConfig.Load(appConfigStream);
}
var configuration = appConfig.SelectSingleNode("configuration");
ArgUtil.NotNull(configuration, "configuration");
var exist_defaultProxy = appConfig.SelectSingleNode("configuration/system.net/defaultProxy");
if (exist_defaultProxy == null)
{
var system_net = appConfig.SelectSingleNode("configuration/system.net");
if (system_net == null)
{
Trace.Verbose("Create system.net section in appconfg.");
system_net = appConfig.CreateElement("system.net");
}
Trace.Verbose("Create defaultProxy section in appconfg.");
var defaultProxy = appConfig.CreateElement("defaultProxy");
defaultProxy.SetAttribute("useDefaultCredentials", "True");
Trace.Verbose("Create proxy section in appconfg.");
var proxy = appConfig.CreateElement("proxy");
proxy.SetAttribute("proxyaddress", proxyUrl);
defaultProxy.AppendChild(proxy);
system_net.AppendChild(defaultProxy);
configuration.AppendChild(system_net);
using (var appConfigStream = new FileStream(AppConfigFile, FileMode.Open, FileAccess.ReadWrite))
{
appConfig.Save(appConfigStream);
}
}
else
{
//proxy setting exist.
ExecutionContext.Debug("Proxy setting already exist in app.config file.");
}
// when tf.exe talk to any devfabric site, it will always bypass proxy.
// for testing, we need set this variable to let tf.exe hit the proxy server on devfabric.
if (Endpoint.Url.Host.Contains(".me.tfsallin.net"))
{
ExecutionContext.Debug("Set TFS_BYPASS_PROXY_ON_LOCAL on devfabric.");
AdditionalEnvironmentVariables["TFS_BYPASS_PROXY_ON_LOCAL"] = "0";
}
}
}
public async Task ShelveAsync(string shelveset, string commentFile, bool move)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
ArgUtil.NotNullOrEmpty(commentFile, nameof(commentFile));
// TODO: Remove parameter "move" after last-saved-checkin-metadata problem is fixed properly.
if (move)
{
await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "shelve", "/move", "/replace", "/recursive", $"/comment:@{commentFile}", shelveset, SourcesDirectory);
return;
}
await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "shelve", "/saved", "/replace", "/recursive", $"/comment:@{commentFile}", shelveset, SourcesDirectory);
}
public async Task<ITfsVCShelveset> ShelvesetsAsync(string shelveset)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
string xml = await RunPorcelainCommandAsync("vc", "shelvesets", "/format:xml", shelveset);
// Deserialize the XML.
// The command returns a non-zero exit code if the shelveset is not found.
// The assertions performed here should never fail.
var serializer = new XmlSerializer(typeof(TFShelvesets));
ArgUtil.NotNullOrEmpty(xml, nameof(xml));
using (var reader = new StringReader(xml))
{
var tfShelvesets = serializer.Deserialize(reader) as TFShelvesets;
ArgUtil.NotNull(tfShelvesets, nameof(tfShelvesets));
ArgUtil.NotNull(tfShelvesets.Shelvesets, nameof(tfShelvesets.Shelvesets));
ArgUtil.Equal(1, tfShelvesets.Shelvesets.Length, nameof(tfShelvesets.Shelvesets.Length));
return tfShelvesets.Shelvesets[0];
}
}
public async Task<ITfsVCStatus> StatusAsync(string localPath)
{
// It is expected that the caller only invokes this method against the sources root
// directory. The "status" subcommand cannot correctly resolve the workspace from the
// an unmapped root folder. For example, if a workspace contains only two mappings,
// $/foo -> $(build.sourcesDirectory)\foo and $/bar -> $(build.sourcesDirectory)\bar,
// then "tf status $(build.sourcesDirectory) /r" will not be able to resolve the workspace.
// Therefore, the "localPath" parameter is not actually passed to the "status" subcommand -
// the collection URL and workspace name are used instead.
ArgUtil.Equal(SourcesDirectory, localPath, nameof(localPath));
string xml = await RunPorcelainCommandAsync("vc", "status", $"/workspace:{WorkspaceName}", "/recursive", "/nodetect", "/format:xml");
var serializer = new XmlSerializer(typeof(TFStatus));
using (var reader = new StringReader(xml ?? string.Empty))
{
return serializer.Deserialize(reader) as TFStatus;
}
}
public bool TestEulaAccepted()
{
throw new NotSupportedException();
}
public async Task<bool> TryWorkspaceDeleteAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
try
{
await RunCommandAsync("vc", "workspace", "/delete", $"{workspace.Name};{workspace.Owner}");
return true;
}
catch (Exception ex)
{
ExecutionContext.Warning(ex.Message);
return false;
}
}
public async Task UndoAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "undo", "/recursive", localPath);
}
public async Task UnshelveAsync(string shelveset)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "unshelve", shelveset);
}
public async Task WorkfoldCloakAsync(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
await RunCommandAsync("vc", "workfold", "/cloak", $"/workspace:{WorkspaceName}", serverPath);
}
public async Task WorkfoldMapAsync(string serverPath, string localPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunCommandAsync("vc", "workfold", "/map", $"/workspace:{WorkspaceName}", serverPath, localPath);
}
public async Task WorkfoldUnmapAsync(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
await RunCommandAsync("vc", "workfold", "/unmap", $"/workspace:{WorkspaceName}", serverPath);
}
public async Task WorkspaceDeleteAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
await RunCommandAsync("vc", "workspace", "/delete", $"{workspace.Name};{workspace.Owner}");
}
public async Task WorkspaceNewAsync()
{
await RunCommandAsync("vc", "workspace", "/new", "/location:local", "/permission:Public", WorkspaceName);
}
public async Task<ITfsVCWorkspace[]> WorkspacesAsync(bool matchWorkspaceNameOnAnyComputer = false)
{
// Build the args.
var args = new List<string>();
args.Add("vc");
args.Add("workspaces");
if (matchWorkspaceNameOnAnyComputer)
{
args.Add(WorkspaceName);
args.Add($"/computer:*");
}
args.Add("/format:xml");
// Run the command.
string xml = await RunPorcelainCommandAsync(args.ToArray()) ?? string.Empty;
// Deserialize the XML.
var serializer = new XmlSerializer(typeof(TFWorkspaces));
using (var reader = new StringReader(xml))
{
return (serializer.Deserialize(reader) as TFWorkspaces)
?.Workspaces
?.Cast<ITfsVCWorkspace>()
.ToArray();
}
}
public async Task WorkspacesRemoveAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
await RunCommandAsync("vc", "workspace", $"/remove:{workspace.Name};{workspace.Owner}");
}
}
////////////////////////////////////////////////////////////////////////////////
// tf shelvesets data objects
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "Shelvesets", Namespace = "")]
public sealed class TFShelvesets
{
[XmlElement(ElementName = "Shelveset", Namespace = "")]
public TFShelveset[] Shelvesets { get; set; }
}
public sealed class TFShelveset : ITfsVCShelveset
{
// Attributes.
[XmlAttribute(AttributeName = "date", Namespace = "")]
public string Date { get; set; }
[XmlAttribute(AttributeName = "name", Namespace = "")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "owner", Namespace = "")]
public string Owner { get; set; }
// Elements.
[XmlElement(ElementName = "Comment", Namespace = "")]
public string Comment { get; set; }
}
////////////////////////////////////////////////////////////////////////////////
// tf status data objects.
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "Status", Namespace = "")]
public sealed class TFStatus : ITfsVCStatus
{
// Elements.
[XmlElement(ElementName = "PendingSet", Namespace = "")]
public TFPendingSet[] PendingSets { get; set; }
// Interface-only properties.
[XmlIgnore]
public IEnumerable<ITfsVCPendingChange> AllAdds
{
get
{
return PendingSets
?.SelectMany(x => x.PendingChanges ?? new TFPendingChange[0])
.Where(x => (x.ChangeType ?? string.Empty).Split(' ').Any(y => string.Equals(y, "Add", StringComparison.OrdinalIgnoreCase)));
}
}
[XmlIgnore]
public bool HasPendingChanges => PendingSets?.Any(x => x.PendingChanges?.Any() ?? false) ?? false;
}
public sealed class TFPendingSet
{
// Attributes.
[XmlAttribute(AttributeName = "computer", Namespace = "")]
public string Computer { get; set; }
[XmlAttribute(AttributeName = "name", Namespace = "")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "owner", Namespace = "")]
public string Owner { get; set; }
[XmlAttribute(AttributeName = "ownerdisp", Namespace = "")]
public string OwnerDisplayName { get; set; }
[XmlAttribute(AttributeName = "ownership", Namespace = "")]
public string Ownership { get; set; }
// Elements.
[XmlArray(ElementName = "PendingChanges", Namespace = "")]
[XmlArrayItem(ElementName = "PendingChange", Namespace = "")]
public TFPendingChange[] PendingChanges { get; set; }
}
public sealed class TFPendingChange : ITfsVCPendingChange
{
// Attributes.
[XmlAttribute(AttributeName = "chg", Namespace = "")]
public string ChangeType { get; set; }
[XmlAttribute(AttributeName = "date", Namespace = "")]
public string Date { get; set; }
[XmlAttribute(AttributeName = "enc", Namespace = "")]
public string Encoding { get; set; }
[XmlAttribute(AttributeName = "hash", Namespace = "")]
public string Hash { get; set; }
[XmlAttribute(AttributeName = "item", Namespace = "")]
public string Item { get; set; }
[XmlAttribute(AttributeName = "itemid", Namespace = "")]
public string ItemId { get; set; }
[XmlAttribute(AttributeName = "local", Namespace = "")]
public string LocalItem { get; set; }
[XmlAttribute(AttributeName = "pcid", Namespace = "")]
public string PCId { get; set; }
[XmlAttribute(AttributeName = "psn", Namespace = "")]
public string Psn { get; set; }
[XmlAttribute(AttributeName = "pso", Namespace = "")]
public string Pso { get; set; }
[XmlAttribute(AttributeName = "psod", Namespace = "")]
public string Psod { get; set; }
[XmlAttribute(AttributeName = "srcitem", Namespace = "")]
public string SourceItem { get; set; }
[XmlAttribute(AttributeName = "svrfm", Namespace = "")]
public string Svrfm { get; set; }
[XmlAttribute(AttributeName = "type", Namespace = "")]
public string Type { get; set; }
[XmlAttribute(AttributeName = "uhash", Namespace = "")]
public string UHash { get; set; }
[XmlAttribute(AttributeName = "ver", Namespace = "")]
public string Version { get; set; }
}
////////////////////////////////////////////////////////////////////////////////
// tf workspaces data objects.
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "Workspaces", Namespace = "")]
public sealed class TFWorkspaces
{
[XmlElement(ElementName = "Workspace", Namespace = "")]
public TFWorkspace[] Workspaces { get; set; }
}
public sealed class TFWorkspace : ITfsVCWorkspace
{
// Attributes.
[XmlAttribute(AttributeName = "computer", Namespace = "")]
public string Computer { get; set; }
[XmlAttribute(AttributeName = "islocal", Namespace = "")]
public string IsLocal { get; set; }
[XmlAttribute(AttributeName = "name", Namespace = "")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "owner", Namespace = "")]
public string Owner { get; set; }
[XmlAttribute(AttributeName = "ownerdisp", Namespace = "")]
public string OwnerDisplayName { get; set; }
[XmlAttribute(AttributeName = "ownerid", Namespace = "")]
public string OwnerId { get; set; }
[XmlAttribute(AttributeName = "ownertype", Namespace = "")]
public string OwnerType { get; set; }
[XmlAttribute(AttributeName = "owneruniq", Namespace = "")]
public string OwnerUnique { get; set; }
// Elements.
[XmlArray(ElementName = "Folders", Namespace = "")]
[XmlArrayItem(ElementName = "WorkingFolder", Namespace = "")]
public TFMapping[] TFMappings { get; set; }
// Interface-only properties.
[XmlIgnore]
public ITfsVCMapping[] Mappings => TFMappings?.Cast<ITfsVCMapping>().ToArray();
}
public sealed class TFMapping : ITfsVCMapping
{
[XmlIgnore]
public bool Cloak => string.Equals(Type, "Cloak", StringComparison.OrdinalIgnoreCase);
[XmlAttribute(AttributeName = "depth", Namespace = "")]
public string Depth { get; set; }
[XmlAttribute(AttributeName = "local", Namespace = "")]
public string LocalPath { get; set; }
[XmlIgnore]
public bool Recursive => !string.Equals(Depth, "1", StringComparison.OrdinalIgnoreCase);
[XmlAttribute(AttributeName = "item", Namespace = "")]
public string ServerPath { get; set; }
[XmlAttribute(AttributeName = "type", Namespace = "")]
public string Type { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Ludiq.Controls.Editor;
using Ludiq.Reflection.Internal;
using UnityEditor;
using UnityEngine;
using UnityObject = UnityEngine.Object;
namespace Ludiq.Reflection.Editor
{
[CustomPropertyDrawer(typeof(UnityMember))]
public class UnityMemberDrawer : TargetedDrawer
{
internal static FilterAttribute filterOverride;
internal static bool? labelTypeAfterOverride;
#region Fields
/// <summary>
/// The filter attribute on the inspected field.
/// </summary>
protected FilterAttribute filter;
/// <summary>
/// Whether to display the label type after the name.
/// </summary>
private bool labelTypeAfter = false;
/// <summary>
/// The inspected property, of type UnityMember.
/// </summary>
protected SerializedProperty property;
/// <summary>
/// The UnityMember.component of the inspected property, of type string.
/// </summary>
protected SerializedProperty componentProperty;
/// <summary>
/// The UnityMember.name of the inspected property, of type string.
/// </summary>
protected SerializedProperty nameProperty;
/// <summary>
/// The UnityMethod.parameterTypes of the inspected property, of type Type[].
/// </summary>
protected SerializedProperty parameterTypesProperty;
/// <summary>
/// The targeted Unity Objects.
/// </summary>
protected UnityObject[] targets;
/// <summary>
/// The type of targeted objects.
/// </summary>
protected UnityObjectType targetType;
#endregion
/// <inheritdoc />
protected override void Update(SerializedProperty property)
{
// Update the targeted drawer
base.Update(property);
// Assign the property and sub-properties
this.property = property;
componentProperty = property.FindPropertyRelative("_component");
nameProperty = property.FindPropertyRelative("_name");
parameterTypesProperty = property.FindPropertyRelative("_parameterTypes");
// Fetch the filter
filter = filterOverride ?? (FilterAttribute)fieldInfo.GetCustomAttributes(typeof(FilterAttribute), true).FirstOrDefault() ?? new FilterAttribute();
// Check for the label type after attribute
labelTypeAfter = labelTypeAfterOverride ?? fieldInfo.IsDefined(typeof(LabelTypeAfterAttribute), true);
// Find the targets
targets = FindTargets();
targetType = DetermineTargetType();
}
/// <inheritdoc />
protected override void RenderMemberControl(Rect position)
{
// Other Targets
// Some Unity Objects, like Assets, are not supported by the drawer.
// Just display an error message to let the user change their target.
if (targetType == UnityObjectType.Other)
{
EditorGUI.HelpBox(position, "Unsupported Unity Object type.", MessageType.None);
return;
}
// Display a list of all available reflected members in a popup.
UnityMember value = GetValue();
DropdownOption<UnityMember> selectedOption = null;
if (value != null)
{
if (targetType == UnityObjectType.GameObject)
{
string label;
if (value.component == null)
{
label = string.Format("GameObject.{0}", value.name);
}
else
{
label = string.Format("{0}.{1}", value.component, value.name);
}
// There seems to be no way of differentiating between null parameter types
// (fields, properties and implicitly typed methods) and zero parameter types
// because Unity's serialized property array cannot be assigned to null, only
// given an array size of zero.
// TODO: The solution would be to use a single comma-separated
// string instead of an array of strings, which we could differentiate manually.
if (value.parameterTypes != null && value.parameterTypes.Length > 0)
{
string parameterString = string.Join(", ", value.parameterTypes.Select(t => t.PrettyName()).ToArray());
label += string.Format(" ({0})", parameterString);
}
selectedOption = new DropdownOption<UnityMember>(value, label);
}
else if (targetType == UnityObjectType.ScriptableObject)
{
selectedOption = new DropdownOption<UnityMember>(value, value.name);
}
}
bool enabled = targetType != UnityObjectType.None;
if (!enabled) EditorGUI.BeginDisabledGroup(true);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = nameProperty.hasMultipleDifferentValues;
value = DropdownGUI<UnityMember>.PopupSingle
(
position,
GetAllMemberOptions,
selectedOption,
new DropdownOption<UnityMember>(null, string.Format("Nothing"))
);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
SetValue(value);
}
if (!enabled) EditorGUI.EndDisabledGroup();
}
private List<DropdownOption<UnityMember>> GetAllMemberOptions()
{
var options = new List<DropdownOption<UnityMember>>();
if (targetType == UnityObjectType.GameObject)
{
// Check if all targets have a GameObject (none are empty).
// If they do, display all members of the GameObject type.
if (HasSharedGameObject())
{
var gameObjectOptions = GetTypeMemberOptions(typeof(GameObject));
foreach (var gameObjectOption in gameObjectOptions)
{
// Prefix label by GameObject for popup clarity.
gameObjectOption.label = string.Format("GameObject/{0}", gameObjectOption.label);
options.Add(gameObjectOption);
}
}
// Find all shared component types across targets.
// Display all members of each one found.
foreach (Type componentType in GetSharedComponentTypes())
{
var componentOptions = GetTypeMemberOptions(componentType, componentType.Name);
foreach (var componentOption in componentOptions)
{
// Prefix label and option by component type for clear distinction.
componentOption.label = string.Format("{0}/{1}", componentType.Name, componentOption.label);
options.Add(componentOption);
}
}
}
else if (targetType == UnityObjectType.ScriptableObject)
{
// ScriptableObject Target
// Make sure all targets share the same ScriptableObject Type.
// If they do, display all members of that type.
Type scriptableObjectType = GetSharedScriptableObjectType();
if (scriptableObjectType != null)
{
options.AddRange(GetTypeMemberOptions(scriptableObjectType));
}
}
return options;
}
#region Value
/// <summary>
/// Returns a member constructed from the current parameter values.
/// </summary>
/// <returns></returns>
protected UnityMember GetValue()
{
if (hasMultipleDifferentValues ||
string.IsNullOrEmpty(nameProperty.stringValue))
{
return null;
}
string component = componentProperty.stringValue;
string name = nameProperty.stringValue;
Type[] parameterTypes = UnityMemberDrawerHelper.DeserializeParameterTypes(parameterTypesProperty);
if (component == string.Empty) component = null;
if (name == string.Empty) name = null;
// Cannot reliably determine if parameterTypes should be null; see other TODO note for selectedOption.
return new UnityMember(component, name, parameterTypes);
}
/// <summary>
/// Assigns the property values from a specified member.
/// </summary>
protected virtual void SetValue(UnityMember value)
{
if (value != null)
{
componentProperty.stringValue = value.component;
nameProperty.stringValue = value.name;
UnityMemberDrawerHelper.SerializeParameterTypes(parameterTypesProperty, value.parameterTypes);
}
else
{
componentProperty.stringValue = null;
nameProperty.stringValue = null;
parameterTypesProperty.arraySize = 0;
}
}
/// <summary>
/// Indicated whether the property has multiple different values.
/// </summary>
protected virtual bool hasMultipleDifferentValues
{
get
{
return
componentProperty.hasMultipleDifferentValues ||
nameProperty.hasMultipleDifferentValues ||
UnityMemberDrawerHelper.ParameterTypesHasMultipleValues(parameterTypesProperty);
}
}
#endregion
#region Targeting
/// <summary>
/// Get the list of targets on the inspected objects.
/// </summary>
protected UnityObject[] FindTargets()
{
if (isSelfTargeted)
{
// In self targeting mode, the targets are the inspected objects themselves.
return property.serializedObject.targetObjects;
}
else
{
// In manual targeting mode, the targets the values of each target property.
return targetProperty.Multiple().Select(p => p.objectReferenceValue).ToArray();
}
}
/// <summary>
/// Determine the Unity type of the targets.
/// </summary>
protected UnityObjectType DetermineTargetType()
{
UnityObjectType unityObjectType = UnityObjectType.None;
foreach (UnityObject targetObject in targets)
{
// Null (non-specified) targets don't affect the type
// If no non-null target is specified, the type will be None
// as the loop will simply exit.
if (targetObject == null)
{
continue;
}
if (targetObject is GameObject || targetObject is Component)
{
// For GameObjects and Components, the target is either the
// GameObject itself, or the one to which the Component belongs.
// If a ScriptableObject target was previously found,
// return that the targets are of mixed types.
if (unityObjectType == UnityObjectType.ScriptableObject)
{
return UnityObjectType.Mixed;
}
unityObjectType = UnityObjectType.GameObject;
}
else if (targetObject is ScriptableObject)
{
// For ScriptableObjects, the target is simply the
// ScriptableObject itself.
// If a GameObject target was previously found,
// return that the targets are of mixed types.
if (unityObjectType == UnityObjectType.GameObject)
{
return UnityObjectType.Mixed;
}
unityObjectType = UnityObjectType.ScriptableObject;
}
else
{
// Other target types
return UnityObjectType.Other;
}
}
return unityObjectType;
}
/// <summary>
/// Determines if the targets all share a GameObject.
/// </summary>
public bool HasSharedGameObject()
{
return !targets.Contains(null);
}
/// <summary>
/// Determines which types of Components are shared on all GameObject targets.
/// </summary>
protected IEnumerable<Type> GetSharedComponentTypes()
{
if (targets.Contains(null))
{
return Enumerable.Empty<Type>();
}
var childrenComponents = targets.OfType<GameObject>().Select(gameObject => gameObject.GetComponents<Component>().Where(c => c != null));
var siblingComponents = targets.OfType<Component>().Select(component => component.GetComponents<Component>().Where(c => c != null));
return childrenComponents.Concat(siblingComponents)
.Select(components => components.Select(component => component.GetType()))
.IntersectAll()
.Distinct();
}
/// <summary>
/// Determines which type of ScriptableObject is shared across targets.
/// Returns null if none are shared.
/// </summary>
protected Type GetSharedScriptableObjectType()
{
if (targets.Contains(null))
{
return null;
}
return targets
.OfType<ScriptableObject>()
.Select(scriptableObject => scriptableObject.GetType())
.Distinct()
.SingleOrDefault(); // Null (default) if multiple or zero
}
#endregion
#region Reflection
/// <summary>
/// Gets the list of members available on a type as popup options.
/// </summary>
protected virtual List<DropdownOption<UnityMember>> GetTypeMemberOptions(Type type, string component = null)
{
var options = type
.GetMembers(validBindingFlags)
.Where(member => validMemberTypes.HasFlag(member.MemberType))
.Where(ValidateMember)
.Select(member => GetMemberOption(member, component, member.DeclaringType != type))
.ToList();
if (filter.Extension)
{
var extensionMethods = type.GetExtensionMethods(filter.Inherited)
.Where(ValidateMember)
.Select(method => GetMemberOption(method, component, filter.Inherited && method.GetParameters()[0].ParameterType != type));
options.AddRange(extensionMethods);
}
// Sort the options
options.Sort((a, b) =>
{
var aSub = a.label.Contains("/");
var bSub = b.label.Contains("/");
if (aSub != bSub)
{
return bSub.CompareTo(aSub);
}
else
{
return a.value.name.CompareTo(b.value.name);
}
});
return options;
}
protected DropdownOption<UnityMember> GetMemberOption(MemberInfo member, string component, bool inherited)
{
UnityMember value;
string label;
if (member is FieldInfo)
{
FieldInfo field = (FieldInfo)member;
value = new UnityMember(component, field.Name);
label = string.Format(labelTypeAfter ? "{1} : {0}" : "{0} {1}", field.FieldType.PrettyName(), field.Name);
}
else if (member is PropertyInfo)
{
PropertyInfo property = (PropertyInfo)member;
value = new UnityMember(component, property.Name);
label = string.Format(labelTypeAfter ? "{1} : {0}" : "{0} {1}", property.PropertyType.PrettyName(), property.Name);
}
else if (member is MethodInfo)
{
MethodInfo method = (MethodInfo)member;
ParameterInfo[] parameters = method.GetParameters();
value = new UnityMember(component, member.Name, parameters.Select(p => p.ParameterType).ToArray());
string parameterString = string.Join(", ", parameters.Select(p => p.ParameterType.PrettyName()).ToArray());
label = string.Format(labelTypeAfter ? "{1} ({2}) : {0}" : "{0} {1} ({2})", method.ReturnType.PrettyName(), member.Name, parameterString);
}
else
{
throw new UnityReflectionException();
}
if (inherited)
{
label = "(Inherited)/" + label;
}
return new DropdownOption<UnityMember>(value, label);
}
#endregion
#region Filtering
/// <summary>
/// The valid BindingFlags when looking for reflected members.
/// </summary>
protected virtual BindingFlags validBindingFlags
{
get
{
// Build the flags from the filter attribute
BindingFlags flags = 0;
if (filter.Public) flags |= BindingFlags.Public;
if (filter.NonPublic) flags |= BindingFlags.NonPublic;
if (filter.Instance) flags |= BindingFlags.Instance;
if (filter.Static) flags |= BindingFlags.Static;
if (!filter.Inherited) flags |= BindingFlags.DeclaredOnly;
if (filter.Static && filter.Inherited) flags |= BindingFlags.FlattenHierarchy;
return flags;
}
}
/// <summary>
/// The valid MemberTypes when looking for reflected members.
/// </summary>
protected virtual MemberTypes validMemberTypes
{
get
{
MemberTypes types = 0;
if (filter.Fields || filter.Gettable || filter.Settable)
{
types |= MemberTypes.Field;
}
if (filter.Properties || filter.Gettable || filter.Settable)
{
types |= MemberTypes.Property;
}
if (filter.Methods || filter.Gettable)
{
types |= MemberTypes.Method;
}
return types;
}
}
/// <summary>
/// Determines whether a given MemberInfo should be included in the options.
/// This check follows the BindingFlags and MemberTypes filtering.
/// </summary>
protected virtual bool ValidateMember(MemberInfo member)
{
bool valid = true;
FieldInfo field = member as FieldInfo;
PropertyInfo property = member as PropertyInfo;
MethodInfo method = member as MethodInfo;
if (field != null) // Member is a field
{
// Validate type based on field type
valid &= ValidateMemberType(field.FieldType);
// Exclude constants (literal) and readonly (init) fields if
// the filter rejects read-only fields.
if (!filter.ReadOnly) valid &= !field.IsLiteral || !field.IsInitOnly;
}
else if (property != null) // Member is a property
{
// Validate type based on property type
valid &= ValidateMemberType(property.PropertyType);
// Exclude read-only and write-only properties
if (!filter.ReadOnly || (!filter.Properties && filter.Settable)) valid &= property.CanWrite;
if (!filter.WriteOnly || (!filter.Properties && filter.Gettable)) valid &= property.CanRead;
}
else if (method != null) // Member is a method
{
// Exclude methods without a return type
if (!filter.Methods && filter.Gettable) valid &= method.ReturnType != typeof(void);
// Validate type based on return type
valid &= ValidateMemberType(method.ReturnType);
// Exclude special compiler methods
valid &= !method.IsSpecialName;
// Exclude generic methods
// TODO: Generic type (de)serialization
valid &= !method.ContainsGenericParameters;
// Exclude methods with parameters
if (!filter.Parameters)
{
valid &= method.GetParameters().Length == 0;
}
}
return valid;
}
/// <summary>
/// Determines whether a MemberInfo of the given type should be included in the options.
/// </summary>
protected virtual bool ValidateMemberType(Type type)
{
bool validFamily = false;
bool validType;
// Allow type families based on the filter attribute
TypeFamily families = filter.TypeFamilies;
if (families.HasFlag(TypeFamily.Array)) validFamily |= type.IsArray;
if (families.HasFlag(TypeFamily.Class)) validFamily |= type.IsClass;
if (families.HasFlag(TypeFamily.Enum)) validFamily |= type.IsEnum;
if (families.HasFlag(TypeFamily.Interface)) validFamily |= type.IsInterface;
if (families.HasFlag(TypeFamily.Primitive)) validFamily |= type.IsPrimitive;
if (families.HasFlag(TypeFamily.Reference)) validFamily |= !type.IsValueType;
if (families.HasFlag(TypeFamily.Value)) validFamily |= (type.IsValueType && type != typeof(void));
if (families.HasFlag(TypeFamily.Void)) validFamily |= type == typeof(void);
// Allow types based on the filter attribute
// If no filter types are specified, all types are allowed.
if (filter.Types.Count > 0)
{
validType = false;
foreach (Type allowedType in filter.Types)
{
if (allowedType.IsAssignableFrom(type))
{
validType = true;
break;
}
}
}
else
{
validType = true;
}
return validFamily && validType;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NServiceKit.Common;
using NServiceKit.Common.Extensions;
using NServiceKit.Common.Web;
namespace NServiceKit.CacheAccess.Providers
{
/// <summary>
/// Stores both 'compressed' and 'text' caches of the dto in the FileSystem and ICacheTextManager provided.
/// The ContentType is inferred from the ICacheTextManager's ContentType.
/// </summary>
public class FileAndCacheTextManager
: ICompressableCacheTextManager
{
private readonly string baseCachePath;
private readonly ICacheTextManager cacheManager;
/// <summary>Initializes a new instance of the NServiceKit.CacheAccess.Providers.FileAndCacheTextManager class.</summary>
///
/// <param name="baseCachePath">Full pathname of the base cache file.</param>
/// <param name="cacheManager"> Manager for cache.</param>
public FileAndCacheTextManager(string baseCachePath, ICacheTextManager cacheManager)
{
this.baseCachePath = baseCachePath;
this.cacheManager = cacheManager;
}
/// <summary>Gets the cache client.</summary>
///
/// <value>The cache client.</value>
public ICacheClient CacheClient
{
get { return this.cacheManager.CacheClient; }
}
/// <summary>Gets the type of the content.</summary>
///
/// <value>The type of the content.</value>
public string ContentType
{
get { return cacheManager.ContentType; }
}
/// <summary>Resolves.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="compressionType">Type of the compression.</param>
/// <param name="cacheKey"> The cache key.</param>
/// <param name="createCacheFn"> The create cache function.</param>
///
/// <returns>An object.</returns>
public object Resolve<T>(string compressionType, string cacheKey, Func<T> createCacheFn)
where T : class
{
var contentTypeCacheKey = cacheKey + MimeTypes.GetExtension(this.ContentType);
var acceptsCompress = !string.IsNullOrEmpty(compressionType);
var cacheKeyZip = acceptsCompress
? contentTypeCacheKey + CompressionTypes.GetExtension(compressionType)
: null;
if (acceptsCompress)
{
var fromCache = GetCompressedBytesFromCache(compressionType, cacheKeyZip);
if (fromCache != null) return fromCache;
var fromFile = GetCompressedBytesFromFile(compressionType, cacheKeyZip);
if (fromFile != null) return fromFile;
}
else
{
var result = this.CacheClient.Get<string>(cacheKey);
if (result != null) return result;
var fromFile = GetFromFile(contentTypeCacheKey);
if (fromFile != null) return fromFile;
}
var cacheValueString = this.cacheManager.ResolveText(cacheKey, createCacheFn);
WriteToFile(contentTypeCacheKey, Encoding.UTF8.GetBytes(cacheValueString));
if (acceptsCompress)
{
var cacheValueZip = cacheValueString.Compress(compressionType);
this.CacheClient.Set(cacheKeyZip, cacheValueZip);
WriteToFile(cacheKeyZip, cacheValueZip);
return new CompressedResult(cacheValueZip, compressionType, this.ContentType);
}
return cacheValueString;
}
/// <summary>Clears this object to its blank/initial state.</summary>
///
/// <param name="cacheKeys">A variable-length parameters list containing cache keys.</param>
public void Clear(IEnumerable<string> cacheKeys)
{
Clear(cacheKeys.ToArray());
}
/// <summary>Clears this object to its blank/initial state.</summary>
///
/// <param name="cacheKeys">A variable-length parameters list containing cache keys.</param>
public void Clear(params string[] cacheKeys)
{
this.cacheManager.Clear(cacheKeys);
var contentTypeCacheKeys = cacheKeys.ToList().ConvertAll(x => x + MimeTypes.GetExtension(this.ContentType));
foreach (var cacheKey in contentTypeCacheKeys)
{
var filePath = Path.Combine(this.baseCachePath, cacheKey);
var gzipFilePath = Path.Combine(this.baseCachePath, cacheKey + CompressionTypes.GetExtension(CompressionTypes.GZip));
var deflateFilePath = Path.Combine(this.baseCachePath, cacheKey + CompressionTypes.GetExtension(CompressionTypes.Deflate));
DeleteFiles(filePath, gzipFilePath, deflateFilePath);
}
}
private static void DeleteFiles(params string[] filePaths)
{
foreach (var filePath in filePaths)
{
//Catching an exception is quicker if you expect the file to be there.
try
{
File.Delete(filePath);
}
catch (Exception) { }
}
}
/// <summary>Gets compressed bytes from cache.</summary>
///
/// <param name="compressionType">Type of the compression.</param>
/// <param name="cacheKey"> The cache key.</param>
///
/// <returns>The compressed bytes from cache.</returns>
public CompressedResult GetCompressedBytesFromCache(string compressionType, string cacheKey)
{
var result = this.CacheClient.Get<byte[]>(cacheKey);
return result != null
? new CompressedResult(result, compressionType, this.ContentType)
: null;
}
/// <summary>Gets compressed bytes from file.</summary>
///
/// <param name="compressionType">Type of the compression.</param>
/// <param name="cacheKey"> The cache key.</param>
///
/// <returns>The compressed bytes from file.</returns>
public CompressedFileResult GetCompressedBytesFromFile(string compressionType, string cacheKey)
{
var filePath = Path.Combine(this.baseCachePath, cacheKey);
if (!File.Exists(filePath)) return null;
return new CompressedFileResult
(
filePath,
compressionType,
this.ContentType
);
}
/// <summary>Gets from file.</summary>
///
/// <param name="cacheKey">The cache key.</param>
///
/// <returns>The data that was read from the file.</returns>
public HttpResult GetFromFile(string cacheKey)
{
try
{
var filePath = Path.Combine(this.baseCachePath, cacheKey);
return File.Exists(filePath)
? new HttpResult(new FileInfo(filePath), this.ContentType)
: null;
}
catch (Exception)
{
return null;
}
}
/// <summary>Writes to file.</summary>
///
/// <param name="cacheKey">The cache key.</param>
/// <param name="bytes"> The bytes.</param>
public void WriteToFile(string cacheKey, byte[] bytes)
{
var filePath = Path.Combine(this.baseCachePath, cacheKey);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
{
fs.Write(bytes, 0, bytes.Length);
}
}
}
}
| |
using System;
/// <summary>
/// char.IsSeparator(string, int)
/// Indicates whether the character at the specified position in a specified string is categorized
/// as a separator.
/// </summary>
public class CharIsSeparator
{
private const int c_MIN_STR_LEN = 2;
private const int c_MAX_STR_LEN = 256;
public static int Main()
{
CharIsSeparator testObj = new CharIsSeparator();
TestLibrary.TestFramework.BeginTestCase("for method: char.IsSeparator(string, int)");
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;
TestLibrary.TestFramework.LogInformation("[Negaitive]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
//Generate the character for validate
char ch = ' '; //space character
return this.DoTest("PosTest1: Separator character",
"P001", "001", "002", ch, true);
}
public bool PosTest2()
{
//Generate a non separator character for validate
char ch = TestLibrary.Generator.GetCharLetter(-55);
return this.DoTest("PosTest2: Non-separator character.",
"P002", "003", "004", ch, false);
}
#endregion
#region Helper method for positive tests
private bool DoTest(string testDesc,
string testId,
string errorNum1,
string errorNum2,
char ch,
bool expectedResult)
{
bool retVal = true;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
string str = new string(ch, 1);
bool actualResult = char.IsSeparator(str, 0);
if (expectedResult != actualResult)
{
if (expectedResult)
{
errorDesc = string.Format("Character \\u{0:x} should belong to separator.", (int)ch);
}
else
{
errorDesc = string.Format("Character \\u{0:x} does not belong to separator.", (int)ch);
}
TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nCharacter is \\u{0:x}", ch);
TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentNullException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: String is a null reference (Nothing in Visual Basic).";
string errorDesc;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
index = TestLibrary.Generator.GetInt32(-55);
char.IsSeparator(null, index);
errorDesc = "ArgumentNullException is not thrown as expected, index is " + index;
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e + "\n Index is " + index;
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//ArgumentOutOfRangeException
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: Index is too great.";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = str.Length + TestLibrary.Generator.GetInt16(-55);
index = str.Length;
char.IsSeparator(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: Index is a negative value";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = -1 * (TestLibrary.Generator.GetInt16(-55));
char.IsSeparator(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index);
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Export(typeof(MiscellaneousFilesWorkspace))]
internal sealed partial class MiscellaneousFilesWorkspace : Workspace, IVsRunningDocTableEvents2, IVisualStudioHostProjectContainer
{
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
private readonly IMetadataAsSourceFileService _fileTrackingMetadataAsSourceService;
private readonly IVsRunningDocumentTable4 _runningDocumentTable;
private readonly IVsTextManager _textManager;
private readonly RoslynDocumentProvider _documentProvider;
private readonly Dictionary<Guid, LanguageInformation> _languageInformationByLanguageGuid = new Dictionary<Guid, LanguageInformation>();
/// <summary>
/// <see cref="WorkspaceRegistration"/> instances for all open buffers being tracked by by this object
/// for possible inclusion into this workspace.
/// </summary>
private IBidirectionalMap<uint, WorkspaceRegistration> _docCookieToWorkspaceRegistration = BidirectionalMap<uint, WorkspaceRegistration>.Empty;
private readonly Dictionary<ProjectId, HostProject> _hostProjects = new Dictionary<ProjectId, HostProject>();
private readonly Dictionary<uint, HostProject> _docCookiesToHostProject = new Dictionary<uint, HostProject>();
private readonly ImmutableArray<MetadataReference> _metadataReferences;
private uint _runningDocumentTableEventsCookie;
private readonly ForegroundThreadAffinitizedObject _foregroundThreadAffinitization;
[ImportingConstructor]
public MiscellaneousFilesWorkspace(
IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
IMetadataAsSourceFileService fileTrackingMetadataAsSourceService,
SaveEventsService saveEventsService,
VisualStudioWorkspace visualStudioWorkspace,
SVsServiceProvider serviceProvider) :
base(visualStudioWorkspace.Services.HostServices, WorkspaceKind.MiscellaneousFiles)
{
_foregroundThreadAffinitization = new ForegroundThreadAffinitizedObject(assertIsForeground: true);
_editorAdaptersFactoryService = editorAdaptersFactoryService;
_fileTrackingMetadataAsSourceService = fileTrackingMetadataAsSourceService;
_runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
_textManager = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager));
((IVsRunningDocumentTable)_runningDocumentTable).AdviseRunningDocTableEvents(this, out _runningDocumentTableEventsCookie);
_metadataReferences = ImmutableArray.CreateRange(CreateMetadataReferences());
_documentProvider = new RoslynDocumentProvider(this, serviceProvider);
saveEventsService.StartSendingSaveEvents();
}
public void RegisterLanguage(Guid languageGuid, string languageName, string scriptExtension, ParseOptions parseOptions)
{
_languageInformationByLanguageGuid.Add(languageGuid, new LanguageInformation(languageName, scriptExtension, parseOptions));
}
internal void StartSolutionCrawler()
{
DiagnosticProvider.Enable(this, DiagnosticProvider.Options.Syntax);
}
internal void StopSolutionCrawler()
{
DiagnosticProvider.Disable(this);
}
private LanguageInformation TryGetLanguageInformation(string filename)
{
Guid fileLanguageGuid;
LanguageInformation languageInformation = null;
if (ErrorHandler.Succeeded(_textManager.MapFilenameToLanguageSID(filename, out fileLanguageGuid)))
{
_languageInformationByLanguageGuid.TryGetValue(fileLanguageGuid, out languageInformation);
}
return languageInformation;
}
private IEnumerable<MetadataReference> CreateMetadataReferences()
{
var manager = this.Services.GetService<VisualStudioMetadataReferenceManager>();
var searchPaths = ReferencePathUtilities.GetReferencePaths();
return from fileName in new[] { "mscorlib.dll", "System.dll", "System.Core.dll" }
let fullPath = FileUtilities.ResolveRelativePath(fileName, basePath: null, baseDirectory: null, searchPaths: searchPaths, fileExists: File.Exists)
where fullPath != null
select manager.CreateMetadataReferenceSnapshot(fullPath, MetadataReferenceProperties.Assembly);
}
public int OnAfterAttributeChange(uint docCookie, uint grfAttribs)
{
return VSConstants.S_OK;
}
public int OnAfterAttributeChangeEx(uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
{
// Did we rename?
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_MkDocument) != 0)
{
// We want to consider this file to be added in one of two situations:
//
// 1) the old file already was a misc file, at which point we might just be doing a rename from
// one name to another with the same extension
// 2) the old file was a different extension that we weren't tracking, which may have now changed
if (TryUntrackClosingDocument(docCookie, pszMkDocumentOld) || TryGetLanguageInformation(pszMkDocumentOld) == null)
{
// Add the new one, if appropriate.
TrackOpenedDocument(docCookie, pszMkDocumentNew);
}
}
// When starting a diff, the RDT doesn't call OnBeforeDocumentWindowShow, but it does call
// OnAfterAttributeChangeEx for the temporary buffer. The native IDE used this even to
// add misc files, so we'll do the same.
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) != 0)
{
var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
if (moniker != null && TryGetLanguageInformation(moniker) != null && !_docCookiesToHostProject.ContainsKey(docCookie))
{
TrackOpenedDocument(docCookie, moniker);
}
}
if ((grfAttribs & (uint)__VSRDTATTRIB3.RDTA_DocumentInitialized) != 0)
{
// The document is now initialized, we should try tracking it
TrackOpenedDocument(docCookie, _runningDocumentTable.GetDocumentMoniker(docCookie));
}
return VSConstants.S_OK;
}
public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterSave(uint docCookie)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
_foregroundThreadAffinitization.AssertIsForeground();
if (dwReadLocksRemaining + dwEditLocksRemaining == 0)
{
TryUntrackClosingDocument(docCookie, _runningDocumentTable.GetDocumentMoniker(docCookie));
}
return VSConstants.S_OK;
}
private void TrackOpenedDocument(uint docCookie, string moniker)
{
_foregroundThreadAffinitization.AssertIsForeground();
var languageInformation = TryGetLanguageInformation(moniker);
if (languageInformation == null)
{
// We can never put this document in a workspace, so just bail
return;
}
// We don't want to realize the document here unless it's already initialized. Document initialization is watched in
// OnAfterAttributeChangeEx and will retrigger this if it wasn't already done.
if (_runningDocumentTable.IsDocumentInitialized(docCookie) && !_docCookieToWorkspaceRegistration.ContainsKey(docCookie))
{
var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);
// As long as the buffer is initialized, then we should see if we should attach
if (textBuffer != null)
{
var registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer());
registration.WorkspaceChanged += Registration_WorkspaceChanged;
_docCookieToWorkspaceRegistration = _docCookieToWorkspaceRegistration.Add(docCookie, registration);
if (!IsClaimedByAnotherWorkspace(registration))
{
AttachToDocument(docCookie, moniker);
}
}
}
}
private void Registration_WorkspaceChanged(object sender, EventArgs e)
{
// We may or may not be getting this notification from the foreground thread if another workspace
// is raising events on a background. Let's send it back to the UI thread since we can't talk
// to the RDT in the background thread. Since this is all asynchronous a bit more asynchrony is fine.
if (!_foregroundThreadAffinitization.IsForeground())
{
ScheduleTask(() => Registration_WorkspaceChanged(sender, e));
return;
}
_foregroundThreadAffinitization.AssertIsForeground();
var workspaceRegistration = (WorkspaceRegistration)sender;
uint docCookie;
// Since WorkspaceChanged notifications may be asynchronous and happened on a different thread,
// we might have already unsubscribed for this synchronously from the RDT while we were in the process of sending this
// request back to the UI thread.
if (!_docCookieToWorkspaceRegistration.TryGetKey(workspaceRegistration, out docCookie))
{
return;
}
// It's also theoretically possible that we are getting notified about a workspace change to a document that has
// been simultaneously removed from the RDT but we haven't gotten the notification. In that case, also bail.
if (!_runningDocumentTable.IsCookieValid(docCookie))
{
return;
}
var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
if (workspaceRegistration.Workspace == null)
{
HostProject hostProject;
if (_docCookiesToHostProject.TryGetValue(docCookie, out hostProject))
{
// The workspace was taken from us and released and we have only asynchronously found out now.
var document = hostProject.Document;
if (document.IsOpen)
{
RegisterText(document.GetOpenTextContainer());
}
}
else
{
// We should now try to claim this. The moniker we have here is the moniker after the rename if we're currently processing
// a rename. It's possible in that case that this is being closed by the other workspace due to that rename. If the rename
// is changing or removing the file extension, we wouldn't want to try attaching, which is why we have to re-check
// the moniker. Once we observe the rename later in OnAfterAttributeChangeEx we'll completely disconnect.
if (TryGetLanguageInformation(moniker) != null)
{
AttachToDocument(docCookie, moniker);
}
}
}
else if (IsClaimedByAnotherWorkspace(workspaceRegistration))
{
// It's now claimed by another workspace, so we should unclaim it
if (_docCookiesToHostProject.ContainsKey(docCookie))
{
DetachFromDocument(docCookie, moniker);
}
}
}
/// <summary>
/// Stops tracking a document in the RDT for whether we should attach to it.
/// </summary>
/// <returns>true if we were previously tracking it.</returns>
private bool TryUntrackClosingDocument(uint docCookie, string moniker)
{
bool unregisteredRegistration = false;
// Remove our registration changing handler before we call DetachFromDocument. Otherwise, calling DetachFromDocument
// causes us to set the workspace to null, which we then respond to as an indication that we should
// attach again.
WorkspaceRegistration registration;
if (_docCookieToWorkspaceRegistration.TryGetValue(docCookie, out registration))
{
registration.WorkspaceChanged -= Registration_WorkspaceChanged;
_docCookieToWorkspaceRegistration = _docCookieToWorkspaceRegistration.RemoveKey(docCookie);
unregisteredRegistration = true;
}
DetachFromDocument(docCookie, moniker);
return unregisteredRegistration;
}
private bool IsClaimedByAnotherWorkspace(WorkspaceRegistration registration)
{
// Currently, we are also responsible for pushing documents to the metadata as source workspace,
// so we count that here as well
return registration.Workspace != null && registration.Workspace.Kind != WorkspaceKind.MetadataAsSource && registration.Workspace.Kind != WorkspaceKind.MiscellaneousFiles;
}
private void AttachToDocument(uint docCookie, string moniker)
{
_foregroundThreadAffinitization.AssertIsForeground();
var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);
if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
{
// We already added it, so we will keep it excluded from the misc files workspace
return;
}
// This should always succeed since we only got here if we already confirmed the moniker is acceptable
var languageInformation = TryGetLanguageInformation(moniker);
Contract.ThrowIfNull(languageInformation);
var parseOptions = languageInformation.ParseOptions;
if (Path.GetExtension(moniker) == languageInformation.ScriptExtension)
{
parseOptions = parseOptions.WithKind(SourceCodeKind.Script);
}
// First, create the project
var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptions, _metadataReferences);
// Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
var document = _documentProvider.TryGetDocumentForFile(
hostProject,
moniker,
parseOptions.Kind,
getFolderNames: _ => SpecializedCollections.EmptyReadOnlyList<string>(),
canUseTextBuffer: _ => true);
// If the buffer has not yet been initialized, we won't get a document.
if (document == null)
{
return;
}
// Since we have a document, we can do the rest of the project setup.
_hostProjects.Add(hostProject.Id, hostProject);
OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());
OnDocumentAdded(document.GetInitialState());
hostProject.Document = document;
// Notify the document provider, so it knows the document is now open and a part of
// the project
_documentProvider.NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(document);
Contract.ThrowIfFalse(document.IsOpen);
var buffer = document.GetOpenTextBuffer();
OnDocumentOpened(document.Id, document.GetOpenTextContainer());
_docCookiesToHostProject.Add(docCookie, hostProject);
}
private void DetachFromDocument(uint docCookie, string moniker)
{
_foregroundThreadAffinitization.AssertIsForeground();
HostProject hostProject;
if (_fileTrackingMetadataAsSourceService.TryRemoveDocumentFromWorkspace(moniker))
{
return;
}
if (_docCookiesToHostProject.TryGetValue(docCookie, out hostProject))
{
var document = hostProject.Document;
OnDocumentClosed(document.Id, document.Loader);
OnDocumentRemoved(document.Id);
OnProjectRemoved(hostProject.Id);
_hostProjects.Remove(hostProject.Id);
_docCookiesToHostProject.Remove(docCookie);
document.Dispose();
return;
}
}
protected override void Dispose(bool finalize)
{
StopSolutionCrawler();
var runningDocumentTableForEvents = (IVsRunningDocumentTable)_runningDocumentTable;
runningDocumentTableForEvents.UnadviseRunningDocTableEvents(_runningDocumentTableEventsCookie);
_runningDocumentTableEventsCookie = 0;
base.Dispose(finalize);
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.ChangeDocument:
return true;
default:
return false;
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
{
var hostDocument = this.GetDocument(documentId);
hostDocument.UpdateText(newText);
}
private HostProject GetHostProject(ProjectId id)
{
HostProject project;
_hostProjects.TryGetValue(id, out project);
return project;
}
internal IVisualStudioHostDocument GetDocument(DocumentId id)
{
var project = GetHostProject(id.ProjectId);
if (project != null && project.Document.Id == id)
{
return project.Document;
}
return null;
}
IReadOnlyList<IVisualStudioHostProject> IVisualStudioHostProjectContainer.GetProjects()
{
return _hostProjects.Values.ToImmutableReadOnlyListOrEmpty<IVisualStudioHostProject>();
}
void IVisualStudioHostProjectContainer.NotifyNonDocumentOpenedForProject(IVisualStudioHostProject project)
{
// Since the MiscellaneousFilesWorkspace doesn't do anything lazily, this is a no-op
}
private class LanguageInformation
{
public LanguageInformation(string languageName, string scriptExtension, ParseOptions parseOptions)
{
this.LanguageName = languageName;
this.ScriptExtension = scriptExtension;
this.ParseOptions = parseOptions;
}
public string LanguageName { get; }
public string ScriptExtension { get; }
public ParseOptions ParseOptions { get; }
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnDiasSemana class.
/// </summary>
[Serializable]
public partial class PnDiasSemanaCollection : ActiveList<PnDiasSemana, PnDiasSemanaCollection>
{
public PnDiasSemanaCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnDiasSemanaCollection</returns>
public PnDiasSemanaCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnDiasSemana o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_dias_semana table.
/// </summary>
[Serializable]
public partial class PnDiasSemana : ActiveRecord<PnDiasSemana>, IActiveRecord
{
#region .ctors and Default Settings
public PnDiasSemana()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnDiasSemana(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnDiasSemana(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnDiasSemana(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_dias_semana", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdDia = new TableSchema.TableColumn(schema);
colvarIdDia.ColumnName = "id_dia";
colvarIdDia.DataType = DbType.Int32;
colvarIdDia.MaxLength = 0;
colvarIdDia.AutoIncrement = true;
colvarIdDia.IsNullable = false;
colvarIdDia.IsPrimaryKey = true;
colvarIdDia.IsForeignKey = false;
colvarIdDia.IsReadOnly = false;
colvarIdDia.DefaultSetting = @"";
colvarIdDia.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdDia);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = -1;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = true;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_dias_semana",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdDia")]
[Bindable(true)]
public int IdDia
{
get { return GetColumnValue<int>(Columns.IdDia); }
set { SetColumnValue(Columns.IdDia, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre)
{
PnDiasSemana item = new PnDiasSemana();
item.Nombre = varNombre;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdDia,string varNombre)
{
PnDiasSemana item = new PnDiasSemana();
item.IdDia = varIdDia;
item.Nombre = varNombre;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdDiaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdDia = @"id_dia";
public static string Nombre = @"nombre";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlTextWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Versioning;
namespace System.Xml {
// Specifies formatting options for XmlTextWriter.
public enum Formatting {
// No special formatting is done (this is the default).
None,
//This option causes child elements to be indented using the Indentation and IndentChar properties.
// It only indents Element Content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-element-content)
// and not Mixed Content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-mixed-content)
// according to the XML 1.0 definitions of these terms.
Indented,
};
// Represents a writer that provides fast non-cached forward-only way of generating XML streams
// containing XML documents that conform to the W3CExtensible Markup Language (XML) 1.0 specification
// and the Namespaces in XML specification.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class XmlTextWriter : XmlWriter {
//
// Private types
//
enum NamespaceState {
Uninitialized,
NotDeclaredButInScope,
DeclaredButNotWrittenOut,
DeclaredAndWrittenOut
}
struct TagInfo {
internal string name;
internal string prefix;
internal string defaultNs;
internal NamespaceState defaultNsState;
internal XmlSpace xmlSpace;
internal string xmlLang;
internal int prevNsTop;
internal int prefixCount;
internal bool mixed; // whether to pretty print the contents of this element.
internal void Init( int nsTop ) {
name = null;
defaultNs = String.Empty;
defaultNsState = NamespaceState.Uninitialized;
xmlSpace = XmlSpace.None;
xmlLang = null;
prevNsTop = nsTop;
prefixCount = 0;
mixed = false;
}
}
struct Namespace {
internal string prefix;
internal string ns;
internal bool declared;
internal int prevNsIndex;
internal void Set( string prefix, string ns, bool declared ) {
this.prefix = prefix;
this.ns = ns;
this.declared = declared;
this.prevNsIndex = -1;
}
}
enum SpecialAttr {
None,
XmlSpace,
XmlLang,
XmlNs
};
// State machine is working through autocomplete
private enum State {
Start,
Prolog,
PostDTD,
Element,
Attribute,
Content,
AttrOnly,
Epilog,
Error,
Closed,
}
private enum Token {
PI,
Doctype,
Comment,
CData,
StartElement,
EndElement,
LongEndElement,
StartAttribute,
EndAttribute,
Content,
Base64,
RawData,
Whitespace,
Empty
}
//
// Fields
//
// output
TextWriter textWriter;
XmlTextEncoder xmlEncoder;
Encoding encoding;
// formatting
Formatting formatting;
bool indented; // perf - faster to check a boolean.
int indentation;
char indentChar;
// element stack
TagInfo[] stack;
int top;
// state machine for AutoComplete
State[] stateTable;
State currentState;
Token lastToken;
// Base64 content
XmlTextWriterBase64Encoder base64Encoder;
// misc
char quoteChar;
char curQuoteChar;
bool namespaces;
SpecialAttr specialAttr;
string prefixForXmlNs;
bool flush;
// namespaces
Namespace[] nsStack;
int nsTop;
Dictionary<string, int> nsHashtable;
bool useNsHashtable;
// char types
XmlCharType xmlCharType = XmlCharType.Instance;
//
// Constants and constant tables
//
const int NamespaceStackInitialSize = 8;
#if DEBUG
const int MaxNamespacesWalkCount = 3;
#else
const int MaxNamespacesWalkCount = 16;
#endif
static string[] stateName = {
"Start",
"Prolog",
"PostDTD",
"Element",
"Attribute",
"Content",
"AttrOnly",
"Epilog",
"Error",
"Closed",
};
static string[] tokenName = {
"PI",
"Doctype",
"Comment",
"CData",
"StartElement",
"EndElement",
"LongEndElement",
"StartAttribute",
"EndAttribute",
"Content",
"Base64",
"RawData",
"Whitespace",
"Empty"
};
static readonly State[] stateTableDefault = {
// State.Start State.Prolog State.PostDTD State.Element State.Attribute State.Content State.AttrOnly State.Epilog
//
/* Token.PI */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.Doctype */ State.PostDTD, State.PostDTD, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error,
/* Token.Comment */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.CData */ State.Content, State.Content, State.Error, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.StartElement */ State.Element, State.Element, State.Element, State.Element, State.Element, State.Element, State.Error, State.Element,
/* Token.EndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.LongEndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.StartAttribute */ State.AttrOnly, State.Error, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error,
/* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Error, State.Element, State.Error, State.Epilog, State.Error,
/* Token.Content */ State.Content, State.Content, State.Error, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
/* Token.Base64 */ State.Content, State.Content, State.Error, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
/* Token.RawData */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
/* Token.Whitespace */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
};
static readonly State[] stateTableDocument = {
// State.Start State.Prolog State.PostDTD State.Element State.Attribute State.Content State.AttrOnly State.Epilog
//
/* Token.PI */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.Doctype */ State.Error, State.PostDTD, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error,
/* Token.Comment */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.CData */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.StartElement */ State.Error, State.Element, State.Element, State.Element, State.Element, State.Element, State.Error, State.Error,
/* Token.EndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.LongEndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.StartAttribute */ State.Error, State.Error, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error,
/* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Error, State.Element, State.Error, State.Error, State.Error,
/* Token.Content */ State.Error, State.Error, State.Error, State.Content, State.Attribute, State.Content, State.Error, State.Error,
/* Token.Base64 */ State.Error, State.Error, State.Error, State.Content, State.Attribute, State.Content, State.Error, State.Error,
/* Token.RawData */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Error, State.Epilog,
/* Token.Whitespace */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Error, State.Epilog,
};
//
// Constructors
//
internal XmlTextWriter() {
namespaces = true;
formatting = Formatting.None;
indentation = 2;
indentChar = ' ';
// namespaces
nsStack = new Namespace[NamespaceStackInitialSize];
nsTop = -1;
// element stack
stack = new TagInfo[10];
top = 0;// 0 is an empty sentanial element
stack[top].Init( -1 );
quoteChar = '"';
stateTable = stateTableDefault;
currentState = State.Start;
lastToken = Token.Empty;
}
// Creates an instance of the XmlTextWriter class using the specified stream.
public XmlTextWriter(Stream w, Encoding encoding) : this() {
this.encoding = encoding;
if (encoding != null)
textWriter = new StreamWriter(w, encoding);
else
textWriter = new StreamWriter(w);
xmlEncoder = new XmlTextEncoder(textWriter);
xmlEncoder.QuoteChar = this.quoteChar;
}
// Creates an instance of the XmlTextWriter class using the specified file.
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public XmlTextWriter(String filename, Encoding encoding)
: this(new FileStream(filename, FileMode.Create,
FileAccess.Write, FileShare.Read), encoding) {
}
// Creates an instance of the XmlTextWriter class using the specified TextWriter.
public XmlTextWriter(TextWriter w) : this() {
textWriter = w;
encoding = w.Encoding;
xmlEncoder = new XmlTextEncoder(w);
xmlEncoder.QuoteChar = this.quoteChar;
}
//
// XmlTextWriter properties
//
// Gets the XmlTextWriter base stream.
public Stream BaseStream {
get {
StreamWriter streamWriter = textWriter as StreamWriter;
return (streamWriter == null ? null : streamWriter.BaseStream);
}
}
// Gets or sets a value indicating whether to do namespace support.
public bool Namespaces {
get { return this.namespaces;}
set {
if (this.currentState != State.Start)
throw new InvalidOperationException(Res.GetString(Res.Xml_NotInWriteState));
this.namespaces = value;
}
}
// Indicates how the output is formatted.
public Formatting Formatting {
get { return this.formatting;}
set { this.formatting = value; this.indented = value == Formatting.Indented;}
}
// Gets or sets how many IndentChars to write for each level in the hierarchy when Formatting is set to "Indented".
public int Indentation {
get { return this.indentation;}
set {
if (value < 0)
throw new ArgumentException(Res.GetString(Res.Xml_InvalidIndentation));
this.indentation = value;
}
}
// Gets or sets which character to use for indenting when Formatting is set to "Indented".
public char IndentChar {
get { return this.indentChar;}
set { this.indentChar = value;}
}
// Gets or sets which character to use to quote attribute values.
public char QuoteChar {
get { return this.quoteChar;}
set {
if (value != '"' && value != '\'') {
throw new ArgumentException(Res.GetString(Res.Xml_InvalidQuote));
}
this.quoteChar = value;
this.xmlEncoder.QuoteChar = value;
}
}
//
// XmlWriter implementation
//
// Writes out the XML declaration with the version "1.0".
public override void WriteStartDocument() {
StartDocument(-1);
}
// Writes out the XML declaration with the version "1.0" and the standalone attribute.
public override void WriteStartDocument(bool standalone) {
StartDocument(standalone ? 1 : 0);
}
// Closes any open elements or attributes and puts the writer back in the Start state.
public override void WriteEndDocument() {
try {
AutoCompleteAll();
if (this.currentState != State.Epilog) {
if (this.currentState == State.Closed) {
throw new ArgumentException(Res.GetString(Res.Xml_ClosedOrError));
}
else {
throw new ArgumentException(Res.GetString(Res.Xml_NoRoot));
}
}
this.stateTable = stateTableDefault;
this.currentState = State.Start;
this.lastToken = Token.Empty;
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
public override void WriteDocType(string name, string pubid, string sysid, string subset) {
try {
ValidateName(name, false);
AutoComplete(Token.Doctype);
textWriter.Write("<!DOCTYPE ");
textWriter.Write(name);
if (pubid != null) {
textWriter.Write(" PUBLIC " + quoteChar);
textWriter.Write(pubid);
textWriter.Write(quoteChar + " " + quoteChar);
textWriter.Write(sysid);
textWriter.Write(quoteChar);
}
else if (sysid != null) {
textWriter.Write(" SYSTEM " + quoteChar);
textWriter.Write(sysid);
textWriter.Write(quoteChar);
}
if (subset != null) {
textWriter.Write("[");
textWriter.Write(subset);
textWriter.Write("]");
}
textWriter.Write('>');
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
public override void WriteStartElement(string prefix, string localName, string ns) {
try {
AutoComplete(Token.StartElement);
PushStack();
textWriter.Write('<');
if (this.namespaces) {
// Propagate default namespace and mix model down the stack.
stack[top].defaultNs = stack[top-1].defaultNs;
if (stack[top-1].defaultNsState != NamespaceState.Uninitialized)
stack[top].defaultNsState = NamespaceState.NotDeclaredButInScope;
stack[top].mixed = stack[top-1].mixed;
if (ns == null) {
// use defined prefix
if (prefix != null && prefix.Length != 0 && (LookupNamespace(prefix) == -1)) {
throw new ArgumentException(Res.GetString(Res.Xml_UndefPrefix));
}
}
else {
if (prefix == null) {
string definedPrefix = FindPrefix(ns);
if (definedPrefix != null) {
prefix = definedPrefix;
}
else {
PushNamespace(null, ns, false); // new default
}
}
else if (prefix.Length == 0) {
PushNamespace(null, ns, false); // new default
}
else {
if (ns.Length == 0) {
prefix = null;
}
VerifyPrefixXml(prefix, ns);
PushNamespace(prefix, ns, false); // define
}
}
stack[top].prefix = null;
if (prefix != null && prefix.Length != 0) {
stack[top].prefix = prefix;
textWriter.Write(prefix);
textWriter.Write(':');
}
}
else {
if ((ns != null && ns.Length != 0) || (prefix != null && prefix.Length != 0)) {
throw new ArgumentException(Res.GetString(Res.Xml_NoNamespaces));
}
}
stack[top].name = localName;
textWriter.Write(localName);
}
catch {
currentState = State.Error;
throw;
}
}
// Closes one element and pops the corresponding namespace scope.
public override void WriteEndElement() {
InternalWriteEndElement(false);
}
// Closes one element and pops the corresponding namespace scope.
public override void WriteFullEndElement() {
InternalWriteEndElement(true);
}
// Writes the start of an attribute.
public override void WriteStartAttribute(string prefix, string localName, string ns) {
try {
AutoComplete(Token.StartAttribute);
this.specialAttr = SpecialAttr.None;
if (this.namespaces) {
if (prefix != null && prefix.Length == 0) {
prefix = null;
}
if (ns == XmlReservedNs.NsXmlNs && prefix == null && localName != "xmlns") {
prefix = "xmlns";
}
if (prefix == "xml") {
if (localName == "lang") {
this.specialAttr = SpecialAttr.XmlLang;
}
else if (localName == "space") {
this.specialAttr = SpecialAttr.XmlSpace;
}
/* bug54408. to be fwd compatible we need to treat xml prefix as reserved
and not really insist on a specific value. Who knows in the future it
might be OK to say xml:blabla
else {
throw new ArgumentException(Res.GetString(Res.Xml_InvalidPrefix));
}*/
}
else if (prefix == "xmlns") {
if (XmlReservedNs.NsXmlNs != ns && ns != null) {
throw new ArgumentException(Res.GetString(Res.Xml_XmlnsBelongsToReservedNs));
}
if (localName == null || localName.Length == 0) {
localName = prefix;
prefix = null;
this.prefixForXmlNs = null;
}
else {
this.prefixForXmlNs = localName;
}
this.specialAttr = SpecialAttr.XmlNs;
}
else if (prefix == null && localName == "xmlns") {
if (XmlReservedNs.NsXmlNs != ns && ns != null) {
// add the below line back in when DOM is fixed
throw new ArgumentException(Res.GetString(Res.Xml_XmlnsBelongsToReservedNs));
}
this.specialAttr = SpecialAttr.XmlNs;
this.prefixForXmlNs = null;
}
else {
if (ns == null) {
// use defined prefix
if (prefix != null && (LookupNamespace(prefix) == -1)) {
throw new ArgumentException(Res.GetString(Res.Xml_UndefPrefix));
}
}
else if (ns.Length == 0) {
// empty namespace require null prefix
prefix = string.Empty;
}
else { // ns.Length != 0
VerifyPrefixXml(prefix, ns);
if (prefix != null && LookupNamespaceInCurrentScope(prefix) != -1) {
prefix = null;
}
// Now verify prefix validity
string definedPrefix = FindPrefix(ns);
if (definedPrefix != null && (prefix == null || prefix == definedPrefix)) {
prefix = definedPrefix;
}
else {
if (prefix == null) {
prefix = GeneratePrefix(); // need a prefix if
}
PushNamespace(prefix, ns, false);
}
}
}
if (prefix != null && prefix.Length != 0) {
textWriter.Write(prefix);
textWriter.Write(':');
}
}
else {
if ((ns != null && ns.Length != 0) || (prefix != null && prefix.Length != 0)) {
throw new ArgumentException(Res.GetString(Res.Xml_NoNamespaces));
}
if (localName == "xml:lang") {
this.specialAttr = SpecialAttr.XmlLang;
}
else if (localName == "xml:space") {
this.specialAttr = SpecialAttr.XmlSpace;
}
}
xmlEncoder.StartAttribute(this.specialAttr != SpecialAttr.None);
textWriter.Write(localName);
textWriter.Write('=');
if (this.curQuoteChar != this.quoteChar) {
this.curQuoteChar = this.quoteChar;
xmlEncoder.QuoteChar = this.quoteChar;
}
textWriter.Write(this.curQuoteChar);
}
catch {
currentState = State.Error;
throw;
}
}
// Closes the attribute opened by WriteStartAttribute.
public override void WriteEndAttribute() {
try {
AutoComplete(Token.EndAttribute);
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out a <![CDATA[...]]> block containing the specified text.
public override void WriteCData(string text) {
try {
AutoComplete(Token.CData);
if (null != text && text.IndexOf("]]>", StringComparison.Ordinal) >= 0) {
throw new ArgumentException(Res.GetString(Res.Xml_InvalidCDataChars));
}
textWriter.Write("<![CDATA[");
if (null != text) {
xmlEncoder.WriteRawWithSurrogateChecking(text);
}
textWriter.Write("]]>");
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out a comment <!--...--> containing the specified text.
public override void WriteComment(string text) {
try {
if (null != text && (text.IndexOf("--", StringComparison.Ordinal)>=0 || (text.Length != 0 && text[text.Length-1] == '-'))) {
throw new ArgumentException(Res.GetString(Res.Xml_InvalidCommentChars));
}
AutoComplete(Token.Comment);
textWriter.Write("<!--");
if (null != text) {
xmlEncoder.WriteRawWithSurrogateChecking(text);
}
textWriter.Write("-->");
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
public override void WriteProcessingInstruction(string name, string text) {
try {
if (null != text && text.IndexOf("?>", StringComparison.Ordinal)>=0) {
throw new ArgumentException(Res.GetString(Res.Xml_InvalidPiChars));
}
if (0 == String.Compare(name, "xml", StringComparison.OrdinalIgnoreCase) && this.stateTable == stateTableDocument) {
throw new ArgumentException(Res.GetString(Res.Xml_DupXmlDecl));
}
AutoComplete(Token.PI);
InternalWriteProcessingInstruction(name, text);
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out an entity reference as follows: "&"+name+";".
public override void WriteEntityRef(string name) {
try {
ValidateName(name, false);
AutoComplete(Token.Content);
xmlEncoder.WriteEntityRef(name);
}
catch {
currentState = State.Error;
throw;
}
}
// Forces the generation of a character entity for the specified Unicode character value.
public override void WriteCharEntity(char ch) {
try {
AutoComplete(Token.Content);
xmlEncoder.WriteCharEntity(ch);
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out the given whitespace.
public override void WriteWhitespace(string ws) {
try {
if (null == ws) {
ws = String.Empty;
}
if (!xmlCharType.IsOnlyWhitespace(ws)) {
throw new ArgumentException(Res.GetString(Res.Xml_NonWhitespace));
}
AutoComplete(Token.Whitespace);
xmlEncoder.Write(ws);
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out the specified text content.
public override void WriteString(string text) {
try {
if (null != text && text.Length != 0 ) {
AutoComplete(Token.Content);
xmlEncoder.Write(text);
}
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out the specified surrogate pair as a character entity.
public override void WriteSurrogateCharEntity(char lowChar, char highChar){
try {
AutoComplete(Token.Content);
xmlEncoder.WriteSurrogateCharEntity(lowChar, highChar);
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out the specified text content.
public override void WriteChars(Char[] buffer, int index, int count) {
try {
AutoComplete(Token.Content);
xmlEncoder.Write(buffer, index, count);
}
catch {
currentState = State.Error;
throw;
}
}
// Writes raw markup from the specified character buffer.
public override void WriteRaw(Char[] buffer, int index, int count) {
try {
AutoComplete(Token.RawData);
xmlEncoder.WriteRaw(buffer, index, count);
}
catch {
currentState = State.Error;
throw;
}
}
// Writes raw markup from the specified character string.
public override void WriteRaw(String data) {
try {
AutoComplete(Token.RawData);
xmlEncoder.WriteRawWithSurrogateChecking(data);
}
catch {
currentState = State.Error;
throw;
}
}
// Encodes the specified binary bytes as base64 and writes out the resulting text.
public override void WriteBase64(byte[] buffer, int index, int count) {
try {
if (!this.flush) {
AutoComplete(Token.Base64);
}
this.flush = true;
// No need for us to explicitly validate the args. The StreamWriter will do
// it for us.
if (null == this.base64Encoder) {
this.base64Encoder = new XmlTextWriterBase64Encoder( xmlEncoder );
}
// Encode will call WriteRaw to write out the encoded characters
this.base64Encoder.Encode( buffer, index, count );
}
catch {
currentState = State.Error;
throw;
}
}
// Encodes the specified binary bytes as binhex and writes out the resulting text.
public override void WriteBinHex( byte[] buffer, int index, int count ) {
try {
AutoComplete( Token.Content );
BinHexEncoder.Encode( buffer, index, count, this );
}
catch {
currentState = State.Error;
throw;
}
}
// Returns the state of the XmlWriter.
public override WriteState WriteState {
get {
switch (this.currentState) {
case State.Start :
return WriteState.Start;
case State.Prolog :
case State.PostDTD :
return WriteState.Prolog;
case State.Element :
return WriteState.Element;
case State.Attribute :
case State.AttrOnly:
return WriteState.Attribute;
case State.Content :
case State.Epilog :
return WriteState.Content;
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
default:
Debug.Assert( false );
return WriteState.Error;
}
}
}
// Closes the XmlWriter and the underlying stream/TextWriter.
public override void Close() {
try {
AutoCompleteAll();
}
catch { // never fail
}
finally {
this.currentState = State.Closed;
textWriter.Close();
}
}
// Flushes whatever is in the buffer to the underlying stream/TextWriter and flushes the underlying stream/TextWriter.
public override void Flush() {
textWriter.Flush();
}
// Writes out the specified name, ensuring it is a valid Name according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name
public override void WriteName(string name) {
try {
AutoComplete(Token.Content);
InternalWriteName(name, false);
}
catch {
currentState = State.Error;
throw;
}
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
public override void WriteQualifiedName(string localName, string ns) {
try {
AutoComplete(Token.Content);
if (this.namespaces) {
if (ns != null && ns.Length != 0 && ns != stack[top].defaultNs) {
string prefix = FindPrefix(ns);
if (prefix == null) {
if (this.currentState != State.Attribute) {
throw new ArgumentException(Res.GetString(Res.Xml_UndefNamespace, ns));
}
prefix = GeneratePrefix(); // need a prefix if
PushNamespace(prefix, ns, false);
}
if (prefix.Length != 0) {
InternalWriteName(prefix, true);
textWriter.Write(':');
}
}
}
else if (ns != null && ns.Length != 0) {
throw new ArgumentException(Res.GetString(Res.Xml_NoNamespaces));
}
InternalWriteName(localName, true);
}
catch {
currentState = State.Error;
throw;
}
}
// Returns the closest prefix defined in the current namespace scope for the specified namespace URI.
public override string LookupPrefix(string ns) {
if (ns == null || ns.Length == 0) {
throw new ArgumentException(Res.GetString(Res.Xml_EmptyName));
}
string s = FindPrefix(ns);
if (s == null && ns == stack[top].defaultNs) {
s = string.Empty;
}
return s;
}
// Gets an XmlSpace representing the current xml:space scope.
public override XmlSpace XmlSpace {
get {
for (int i = top; i > 0; i--) {
XmlSpace xs = stack[i].xmlSpace;
if (xs != XmlSpace.None)
return xs;
}
return XmlSpace.None;
}
}
// Gets the current xml:lang scope.
public override string XmlLang {
get {
for (int i = top; i > 0; i--) {
String xlang = stack[i].xmlLang;
if (xlang != null)
return xlang;
}
return null;
}
}
// Writes out the specified name, ensuring it is a valid NmToken
// according to the XML specification (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public override void WriteNmToken(string name) {
try {
AutoComplete(Token.Content);
if (name == null || name.Length == 0) {
throw new ArgumentException(Res.GetString(Res.Xml_EmptyName));
}
if (!ValidateNames.IsNmtokenNoNamespaces(name)) {
throw new ArgumentException(Res.GetString(Res.Xml_InvalidNameChars, name));
}
textWriter.Write(name);
}
catch {
currentState = State.Error;
throw;
}
}
//
// Private implementation methods
//
void StartDocument(int standalone) {
try {
if (this.currentState != State.Start) {
throw new InvalidOperationException(Res.GetString(Res.Xml_NotTheFirst));
}
this.stateTable = stateTableDocument;
this.currentState = State.Prolog;
StringBuilder bufBld = new StringBuilder(128);
bufBld.Append("version=" + quoteChar + "1.0" + quoteChar);
if (this.encoding != null) {
bufBld.Append(" encoding=");
bufBld.Append(quoteChar);
bufBld.Append(this.encoding.WebName);
bufBld.Append(quoteChar);
}
if (standalone >= 0) {
bufBld.Append(" standalone=");
bufBld.Append(quoteChar);
bufBld.Append(standalone == 0 ? "no" : "yes");
bufBld.Append(quoteChar);
}
InternalWriteProcessingInstruction("xml", bufBld.ToString());
}
catch {
currentState = State.Error;
throw;
}
}
void AutoComplete(Token token) {
if (this.currentState == State.Closed) {
throw new InvalidOperationException(Res.GetString(Res.Xml_Closed));
}
else if (this.currentState == State.Error) {
throw new InvalidOperationException(Res.GetString(Res.Xml_WrongToken, tokenName[(int)token], stateName[(int)State.Error]));
}
State newState = this.stateTable[(int)token * 8 + (int)this.currentState];
if (newState == State.Error) {
throw new InvalidOperationException(Res.GetString(Res.Xml_WrongToken, tokenName[(int)token], stateName[(int)this.currentState]));
}
switch (token) {
case Token.Doctype:
if (this.indented && this.currentState != State.Start) {
Indent(false);
}
break;
case Token.StartElement:
case Token.Comment:
case Token.PI:
case Token.CData:
if (this.currentState == State.Attribute) {
WriteEndAttributeQuote();
WriteEndStartTag(false);
}
else if (this.currentState == State.Element) {
WriteEndStartTag(false);
}
if (token == Token.CData) {
stack[top].mixed = true;
}
else if (this.indented && this.currentState != State.Start) {
Indent(false);
}
break;
case Token.EndElement:
case Token.LongEndElement:
if (this.flush) {
FlushEncoders();
}
if (this.currentState == State.Attribute) {
WriteEndAttributeQuote();
}
if (this.currentState == State.Content) {
token = Token.LongEndElement;
}
else {
WriteEndStartTag(token == Token.EndElement);
}
if (stateTableDocument == this.stateTable && top == 1) {
newState = State.Epilog;
}
break;
case Token.StartAttribute:
if (this.flush) {
FlushEncoders();
}
if (this.currentState == State.Attribute) {
WriteEndAttributeQuote();
textWriter.Write(' ');
}
else if (this.currentState == State.Element) {
textWriter.Write(' ');
}
break;
case Token.EndAttribute:
if (this.flush) {
FlushEncoders();
}
WriteEndAttributeQuote();
break;
case Token.Whitespace:
case Token.Content:
case Token.RawData:
case Token.Base64:
if (token != Token.Base64 && this.flush) {
FlushEncoders();
}
if (this.currentState == State.Element && this.lastToken != Token.Content) {
WriteEndStartTag(false);
}
if (newState == State.Content) {
stack[top].mixed = true;
}
break;
default:
throw new InvalidOperationException(Res.GetString(Res.Xml_InvalidOperation));
}
this.currentState = newState;
this.lastToken = token;
}
void AutoCompleteAll() {
if (this.flush) {
FlushEncoders();
}
while (top > 0) {
WriteEndElement();
}
}
void InternalWriteEndElement(bool longFormat) {
try {
if (top <= 0) {
throw new InvalidOperationException(Res.GetString(Res.Xml_NoStartTag));
}
// if we are in the element, we need to close it.
AutoComplete(longFormat ? Token.LongEndElement : Token.EndElement);
if (this.lastToken == Token.LongEndElement) {
if (this.indented) {
Indent(true);
}
textWriter.Write('<');
textWriter.Write('/');
if (this.namespaces && stack[top].prefix != null) {
textWriter.Write(stack[top].prefix);
textWriter.Write(':');
}
textWriter.Write(stack[top].name);
textWriter.Write('>');
}
// pop namespaces
int prevNsTop = stack[top].prevNsTop;
if (useNsHashtable && prevNsTop < nsTop) {
PopNamespaces(prevNsTop + 1, nsTop);
}
nsTop = prevNsTop;
top--;
}
catch {
currentState = State.Error;
throw;
}
}
void WriteEndStartTag(bool empty) {
xmlEncoder.StartAttribute(false);
for (int i = nsTop; i > stack[top].prevNsTop; i--) {
if (!nsStack[i].declared) {
textWriter.Write(" xmlns");
textWriter.Write(':');
textWriter.Write(nsStack[i].prefix);
textWriter.Write('=');
textWriter.Write(this.quoteChar);
xmlEncoder.Write(nsStack[i].ns);
textWriter.Write(this.quoteChar);
}
}
// Default
if ((stack[top].defaultNs != stack[top - 1].defaultNs) &&
(stack[top].defaultNsState == NamespaceState.DeclaredButNotWrittenOut)) {
textWriter.Write(" xmlns");
textWriter.Write('=');
textWriter.Write(this.quoteChar);
xmlEncoder.Write(stack[top].defaultNs);
textWriter.Write(this.quoteChar);
stack[top].defaultNsState = NamespaceState.DeclaredAndWrittenOut;
}
xmlEncoder.EndAttribute();
if (empty) {
textWriter.Write(" /");
}
textWriter.Write('>');
}
void WriteEndAttributeQuote() {
if (this.specialAttr != SpecialAttr.None) {
// Ok, now to handle xmlspace, etc.
HandleSpecialAttribute();
}
xmlEncoder.EndAttribute();
textWriter.Write(this.curQuoteChar);
}
void Indent(bool beforeEndElement) {
// pretty printing.
if (top == 0) {
textWriter.WriteLine();
}
else if (!stack[top].mixed) {
textWriter.WriteLine();
int i = beforeEndElement ? top - 1 : top;
for (i *= this.indentation; i > 0; i--) {
textWriter.Write(this.indentChar);
}
}
}
// pushes new namespace scope, and returns generated prefix, if one
// was needed to resolve conflicts.
void PushNamespace(string prefix, string ns, bool declared) {
if (XmlReservedNs.NsXmlNs == ns) {
throw new ArgumentException(Res.GetString(Res.Xml_CanNotBindToReservedNamespace));
}
if (prefix == null) {
switch (stack[top].defaultNsState) {
case NamespaceState.DeclaredButNotWrittenOut:
Debug.Assert (declared == true, "Unexpected situation!!");
// the first namespace that the user gave us is what we
// like to keep.
break;
case NamespaceState.Uninitialized:
case NamespaceState.NotDeclaredButInScope:
// we now got a brand new namespace that we need to remember
stack[top].defaultNs = ns;
break;
default:
Debug.Assert(false, "Should have never come here");
return;
}
stack[top].defaultNsState = (declared ? NamespaceState.DeclaredAndWrittenOut : NamespaceState.DeclaredButNotWrittenOut);
}
else {
if (prefix.Length != 0 && ns.Length == 0) {
throw new ArgumentException(Res.GetString(Res.Xml_PrefixForEmptyNs));
}
int existingNsIndex = LookupNamespace(prefix);
if (existingNsIndex != -1 && nsStack[existingNsIndex].ns == ns) {
// it is already in scope.
if (declared) {
nsStack[existingNsIndex].declared = true;
}
}
else {
// see if prefix conflicts for the current element
if (declared) {
if (existingNsIndex != -1 && existingNsIndex > stack[top].prevNsTop) {
nsStack[existingNsIndex].declared = true; // old one is silenced now
}
}
AddNamespace(prefix, ns, declared);
}
}
}
void AddNamespace(string prefix, string ns, bool declared) {
int nsIndex = ++nsTop;
if ( nsIndex == nsStack.Length ) {
Namespace[] newStack = new Namespace[nsIndex * 2];
Array.Copy(nsStack, newStack, nsIndex);
nsStack = newStack;
}
nsStack[nsIndex].Set(prefix, ns, declared);
if (useNsHashtable) {
AddToNamespaceHashtable(nsIndex);
}
else if (nsIndex == MaxNamespacesWalkCount) {
// add all
nsHashtable = new Dictionary<string, int>(new SecureStringHasher());
for (int i = 0; i <= nsIndex; i++) {
AddToNamespaceHashtable(i);
}
useNsHashtable = true;
}
}
void AddToNamespaceHashtable(int namespaceIndex) {
string prefix = nsStack[namespaceIndex].prefix;
int existingNsIndex;
if ( nsHashtable.TryGetValue(prefix, out existingNsIndex)) {
nsStack[namespaceIndex].prevNsIndex = existingNsIndex;
}
nsHashtable[prefix] = namespaceIndex;
}
private void PopNamespaces(int indexFrom, int indexTo) {
Debug.Assert(useNsHashtable);
for (int i = indexTo; i >= indexFrom; i--) {
Debug.Assert(nsHashtable.ContainsKey(nsStack[i].prefix));
if (nsStack[i].prevNsIndex == -1) {
nsHashtable.Remove(nsStack[i].prefix);
}
else {
nsHashtable[nsStack[i].prefix] = nsStack[i].prevNsIndex;
}
}
}
string GeneratePrefix() {
int temp = stack[top].prefixCount++ + 1;
return "d" + top.ToString("d", CultureInfo.InvariantCulture)
+ "p" + temp.ToString("d", CultureInfo.InvariantCulture);
}
void InternalWriteProcessingInstruction(string name, string text) {
textWriter.Write("<?");
ValidateName(name, false);
textWriter.Write(name);
textWriter.Write(' ');
if (null != text) {
xmlEncoder.WriteRawWithSurrogateChecking(text);
}
textWriter.Write("?>");
}
int LookupNamespace( string prefix ) {
if ( useNsHashtable ) {
int nsIndex;
if ( nsHashtable.TryGetValue( prefix, out nsIndex ) ) {
return nsIndex;
}
}
else {
for ( int i = nsTop; i >= 0; i-- ) {
if ( nsStack[i].prefix == prefix ) {
return i;
}
}
}
return -1;
}
int LookupNamespaceInCurrentScope( string prefix ) {
if ( useNsHashtable ) {
int nsIndex;
if ( nsHashtable.TryGetValue( prefix, out nsIndex ) ) {
if ( nsIndex > stack[top].prevNsTop ) {
return nsIndex;
}
}
}
else {
for ( int i = nsTop; i > stack[top].prevNsTop; i-- ) {
if ( nsStack[i].prefix == prefix ) {
return i;
}
}
}
return -1;
}
string FindPrefix(string ns) {
for (int i = nsTop; i >= 0; i--) {
if (nsStack[i].ns == ns) {
if (LookupNamespace(nsStack[i].prefix) == i) {
return nsStack[i].prefix;
}
}
}
return null;
}
// There are three kind of strings we write out - Name, LocalName and Prefix.
// Both LocalName and Prefix can be represented with NCName == false and Name
// can be represented as NCName == true
void InternalWriteName(string name, bool isNCName) {
ValidateName(name, isNCName);
textWriter.Write(name);
}
// This method is used for validation of the DOCTYPE, processing instruction and entity names plus names
// written out by the user via WriteName and WriteQualifiedName.
// Unfortunatelly the names of elements and attributes are not validated by the XmlTextWriter.
// Also this method does not check wheather the character after ':' is a valid start name character. It accepts
// all valid name characters at that position. This can't be changed because of backwards compatibility.
private unsafe void ValidateName(string name, bool isNCName) {
if (name == null || name.Length == 0) {
throw new ArgumentException(Res.GetString(Res.Xml_EmptyName));
}
int nameLength = name.Length;
// Namespaces supported
if (namespaces) {
// We can't use ValidateNames.ParseQName here because of backwards compatibility bug we need to preserve.
// The bug is that the character after ':' is validated only as a NCName characters instead of NCStartName.
int colonPosition = -1;
// Parse NCName (may be prefix, may be local name)
int position = ValidateNames.ParseNCName(name);
Continue:
if (position == nameLength) {
return;
}
// we have prefix:localName
if (name[position] == ':') {
if (!isNCName) {
// first colon in qname
if (colonPosition == -1) {
// make sure it is not the first or last characters
if (position > 0 && position + 1 < nameLength) {
colonPosition = position;
// Because of the back-compat bug (described above) parse the rest as Nmtoken
position++;
position += ValidateNames.ParseNmtoken(name, position);
goto Continue;
}
}
}
}
}
// Namespaces not supported
else {
if (ValidateNames.IsNameNoNamespaces(name)) {
return;
}
}
throw new ArgumentException(Res.GetString(Res.Xml_InvalidNameChars, name));
}
void HandleSpecialAttribute() {
string value = xmlEncoder.AttributeValue;
switch (this.specialAttr) {
case SpecialAttr.XmlLang:
stack[top].xmlLang = value;
break;
case SpecialAttr.XmlSpace:
// validate XmlSpace attribute
value = XmlConvert.TrimString(value);
if (value == "default") {
stack[top].xmlSpace = XmlSpace.Default;
}
else if (value == "preserve") {
stack[top].xmlSpace = XmlSpace.Preserve;
}
else {
throw new ArgumentException(Res.GetString(Res.Xml_InvalidXmlSpace, value));
}
break;
case SpecialAttr.XmlNs:
VerifyPrefixXml(this.prefixForXmlNs, value);
PushNamespace(this.prefixForXmlNs, value, true);
break;
}
}
void VerifyPrefixXml(string prefix, string ns) {
if (prefix != null && prefix.Length == 3) {
if (
(prefix[0] == 'x' || prefix[0] == 'X') &&
(prefix[1] == 'm' || prefix[1] == 'M') &&
(prefix[2] == 'l' || prefix[2] == 'L')
) {
if (XmlReservedNs.NsXml != ns) {
throw new ArgumentException(Res.GetString(Res.Xml_InvalidPrefix));
}
}
}
}
void PushStack() {
if (top == stack.Length - 1) {
TagInfo[] na = new TagInfo[stack.Length + 10];
if (top > 0) Array.Copy(stack,na,top + 1);
stack = na;
}
top++; // Move up stack
stack[top].Init(nsTop);
}
void FlushEncoders()
{
if (null != this.base64Encoder) {
// The Flush will call WriteRaw to write out the rest of the encoded characters
this.base64Encoder.Flush();
}
this.flush = false;
}
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using PrimerProForms;
using PrimerProObjects;
using GenLib;
namespace PrimerProSearch
{
/// <summary>
///
/// </summary>
public class AdvancedSearch : Search
{
//Search parameters
private string m_Sequence1Grf;
private ConsonantFeatures m_Sequence1Cns;
private VowelFeatures m_Sequence1Vwl;
private string m_Sequence2Grf;
private ConsonantFeatures m_Sequence2Cns;
private VowelFeatures m_Sequence2Vwl;
private string m_Sequence3Grf;
private ConsonantFeatures m_Sequence3Cns;
private VowelFeatures m_Sequence3Vwl;
private string m_Sequence4Grf;
private ConsonantFeatures m_Sequence4Cns;
private VowelFeatures m_Sequence4Vwl;
private bool m_UseGraphemeTaughts;
private bool m_BrowseView;
private SearchOptions m_SearchOptions;
private string m_Title;
private Settings m_Settings;
private PSTable m_PSTable;
private GraphemeInventory m_GI;
private GraphemeTaughtOrder m_GTO;
private Font m_DefaultFont; //Default Font
private Color m_HighlightColor; //Highlight Color
// Search Definition Tags
private const string kTarget = "target";
private const string kFeature = "feature";
private const string kC = "_C";
private const string kV = "_V";
private const string kGraphemesTaught = "UseGrapemesTaught";
private const string kBrowseView = "BrowseView";
//private const string kTitle = "Advanced Grapheme Search";
public AdvancedSearch(int number, Settings s)
: base(number, SearchDefinition.kAdvanced)
{
m_Sequence1Grf = "";
m_Sequence1Cns = null;
m_Sequence1Vwl = null;
m_Sequence2Grf = "";
m_Sequence2Cns = null;
m_Sequence2Vwl = null;
m_Sequence3Grf = "";
m_Sequence3Cns = null;
m_Sequence3Vwl = null;
m_Sequence4Grf = "";
m_Sequence4Cns = null;
m_Sequence4Vwl = null;
m_SearchOptions = null;
m_Settings = s;
//m_Title = AdvancedSearch.kTitle;
m_Title = m_Settings.LocalizationTable.GetMessage("AdvancedSearchT");
if (m_Title == "")
m_Title = "Advanced Grapheme Search";
m_PSTable = m_Settings.PSTable;
m_GI = m_Settings.GraphemeInventory;
m_GTO = m_Settings.GraphemesTaught;
m_DefaultFont = m_Settings.OptionSettings.GetDefaultFont();
m_HighlightColor = m_Settings.OptionSettings.HighlightColor;
}
public bool UseGraphemesTaught
{
get { return m_UseGraphemeTaughts; }
set { m_UseGraphemeTaughts = value; }
}
public bool BrowseView
{
get { return m_BrowseView; }
set { m_BrowseView = value; }
}
public string Sequence1Grf
{
get {return m_Sequence1Grf;}
set {m_Sequence1Grf = value;}
}
public ConsonantFeatures Sequence1Cns
{
get {return m_Sequence1Cns;}
set {m_Sequence1Cns = value;}
}
public VowelFeatures Sequence1Vwl
{
get {return m_Sequence1Vwl;}
set {m_Sequence1Vwl = value;}
}
public string Sequence2Grf
{
get {return m_Sequence2Grf;}
set {m_Sequence2Grf = value;}
}
public ConsonantFeatures Sequence2Cns
{
get {return m_Sequence2Cns;}
set {m_Sequence2Cns = value;}
}
public VowelFeatures Sequence2Vwl
{
get {return m_Sequence2Vwl;}
set {m_Sequence2Vwl = value;}
}
public string Sequence3Grf
{
get {return m_Sequence3Grf;}
set {m_Sequence3Grf = value;}
}
public ConsonantFeatures Sequence3Cns
{
get {return m_Sequence3Cns;}
set {m_Sequence3Cns = value;}
}
public VowelFeatures Sequence3Vwl
{
get {return m_Sequence3Vwl;}
set {m_Sequence3Vwl = value;}
}
public string Sequence4Grf
{
get {return m_Sequence4Grf;}
set {m_Sequence4Grf = value;}
}
public ConsonantFeatures Sequence4Cns
{
get {return m_Sequence4Cns;}
set {m_Sequence4Cns = value;}
}
public VowelFeatures Sequence4Vwl
{
get {return m_Sequence4Vwl;}
set {m_Sequence4Vwl = value;}
}
public SearchOptions SearchOptions
{
get {return m_SearchOptions;}
set {m_SearchOptions = value;}
}
public string Title
{
get {return m_Title;}
set {m_Title = value;}
}
public PSTable PSTable
{
get {return m_PSTable;}
}
public GraphemeInventory GI
{
get { return m_GI; }
}
public GraphemeTaughtOrder GTO
{
get { return m_GTO; }
}
public int GetSequenceLength()
{
int n = 0;
if ( (this.Sequence1Grf == "") && (this.Sequence1Cns == null)
&& (this.Sequence1Vwl == null) )
{
n = 0;
}
else if ( (this.Sequence2Grf == "") && (this.Sequence2Cns == null)
&& (this.Sequence2Vwl == null) )
{
n = 1;
}
else if ( (this.Sequence3Grf == "") && (this.Sequence3Cns == null)
&& (this.Sequence3Vwl == null) )
{
n = 2;
}
else if ( (this.Sequence4Grf == "") && (this.Sequence4Cns == null)
&& (this.Sequence4Vwl == null) )
{
n = 3;
}
else n = 4;
return n;
}
public bool SetupSearch()
{
bool flag = false;
//FormAdvanced fpb = new FormAdvanced(m_GI, m_PSTable, m_PSTable, m_DefaultFont);
FormAdvanced form = new FormAdvanced(m_GI, m_PSTable, m_DefaultFont, m_Settings.LocalizationTable);
DialogResult dr;
dr = form.ShowDialog();
if (dr == DialogResult.OK)
{
this.Sequence1Cns = form.Sequence1CnsFeatures;
this.Sequence1Grf = form.Sequence1Grapheme;
this.Sequence1Vwl = form.Sequence1VwlFeatures;
this.Sequence2Cns = form.Sequence2CnsFeatures;
this.Sequence2Grf = form.Sequence2Grapheme;
this.Sequence2Vwl = form.Sequence2VwlFeatures;
this.Sequence3Cns = form.Sequence3CnsFeatures;
this.Sequence3Grf = form.Sequence3Grapheme;
this.Sequence3Vwl = form.Sequence3VwlFeatures;
this.Sequence4Cns = form.Sequence4CnsFeatures;
this.Sequence4Grf = form.Sequence4Grapheme;
this.Sequence4Vwl = form.Sequence4VwlFeatures;
this.UseGraphemesTaught = form.UseGraphemesTaught;
this.BrowseView = form.BrowseView;
this.SearchOptions = form.SearchOptions;
if ((this.Sequence1Grf != "") || (this.Sequence1Cns != null)
|| (this.Sequence1Vwl != null))
{
SearchDefinition sd = new SearchDefinition(SearchDefinition.kAdvanced);
SearchDefinitionParm sdp = null;
this.SearchDefinition = sd;
if (this.Sequence1Grf != "")
{
sdp = new SearchDefinitionParm(AdvancedSearch.kTarget, this.Sequence1Grf);
sd.AddSearchParm(sdp);
}
else if (this.Sequence1Cns != null)
{
sd = AddSearchParmForConsonantFeatures(sd, Sequence1Cns);
}
else if (this.Sequence1Vwl != null)
{
sd = AddSearchParmForVowelFeatures(sd, Sequence1Vwl);
}
if (this.Sequence2Grf != "")
{
sdp = new SearchDefinitionParm(AdvancedSearch.kTarget, this.Sequence2Grf);
sd.AddSearchParm(sdp);
}
else if (this.Sequence2Cns != null)
{
sd = AddSearchParmForConsonantFeatures(sd, Sequence2Cns);
}
else if (this.Sequence2Vwl != null)
{
sd = AddSearchParmForVowelFeatures(sd, Sequence2Vwl);
}
if (this.Sequence3Grf != "")
{
sdp = new SearchDefinitionParm(AdvancedSearch.kTarget, this.Sequence3Grf);
sd.AddSearchParm(sdp);
}
else if (this.Sequence3Cns != null)
{
sd = AddSearchParmForConsonantFeatures(sd, Sequence3Cns);
}
else if (this.Sequence3Vwl != null)
{
sd = AddSearchParmForVowelFeatures(sd, Sequence3Vwl);
}
if (this.Sequence4Grf != "")
{
sdp = new SearchDefinitionParm(AdvancedSearch.kTarget, this.Sequence4Grf);
sd.AddSearchParm(sdp);
}
else if (this.Sequence4Cns != null)
{
sd = AddSearchParmForConsonantFeatures(sd, Sequence4Cns);
}
else if (this.Sequence4Vwl != null)
{
sd = AddSearchParmForVowelFeatures(sd, Sequence4Vwl);
}
if (this.UseGraphemesTaught)
{
sdp = new SearchDefinitionParm(AdvancedSearch.kGraphemesTaught);
sd.AddSearchParm(sdp);
}
if (this.BrowseView)
{
sdp = new SearchDefinitionParm(AdvancedSearch.kBrowseView);
sd.AddSearchParm(sdp);
}
if (m_SearchOptions != null)
sd.AddSearchOptions(m_SearchOptions);
this.SearchDefinition = sd;
flag = true;
}
//else MessageBox.Show("Grapheme not specified");
else
{
string strMsg = m_Settings.LocalizationTable.GetMessage("AdvancedSearch1");
if (strMsg == "")
strMsg = "Grapheme not specified";
MessageBox.Show(strMsg);
}
}
return flag;
}
public bool SetupSearch(SearchDefinition sd)
{
bool flag = true;
SearchOptions so = new SearchOptions(m_PSTable);
SearchDefinitionParm sdp = null;
string strTag = "";
string strContent = "";
char chType = ' '; // Grapheme/Consonant/Vowel
int nSequence = 0; // Sequence number
this.SearchDefinition = sd;
for (int i = 0; i < sd.SearchParmsCount(); i++)
{
sdp = sd.GetSearchParmAt(i);
strTag = sdp.GetTag();
strContent = sdp.GetContent();
if (strTag == AdvancedSearch.kTarget)
{
nSequence++;
switch (strContent)
{
case AdvancedSearch.kGraphemesTaught:
this.UseGraphemesTaught = false;
this.BrowseView = false;
break;
case AdvancedSearch.kC:
chType = 'C';
switch (nSequence)
{
case 1:
this.Sequence1Cns = new ConsonantFeatures();
break;
case 2:
this.Sequence2Cns = new ConsonantFeatures();
break;
case 3:
this.Sequence3Cns = new ConsonantFeatures();
break;
case 4:
this.Sequence4Cns = new ConsonantFeatures();
break;
default:
break;
}
break;
case AdvancedSearch.kV:
chType = 'V';
switch (nSequence)
{
case 1:
this.Sequence1Vwl = new VowelFeatures();
break;
case 2:
this.Sequence2Vwl = new VowelFeatures();
break;
case 3:
this.Sequence3Vwl = new VowelFeatures();
break;
case 4:
this.Sequence4Vwl = new VowelFeatures();
break;
default:
break;
}
break;
default:
chType = ' ';
switch (nSequence)
{
case 1:
this.Sequence1Grf = strContent;
break;
case 2:
this.Sequence2Grf = strContent;
break;
case 3:
this.Sequence3Grf = strContent;
break;
case 4:
this.Sequence4Grf = strContent;
break;
default:
break;
}
break;
}
}
if (strTag == AdvancedSearch.kFeature)
{
switch (chType)
{
case 'C':
SetConsonantFeature(nSequence, strContent);
break;
case 'V':
SetVowelFeature(nSequence, strContent);
break;
default:
break;
}
}
}
this.SearchOptions = sd.MakeSearchOptions(so);
this.SearchDefinition = sd;
return flag;
}
public string BuildResults()
{
string strText = "";
string str = "";
string strSN = Search.TagSN + this.SearchNumber.ToString().Trim();
strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine;
strText += this.Title + Environment.NewLine + Environment.NewLine;
strText += this.SearchResults;
strText += Environment.NewLine;
//strText += this.SearchCount.ToString() + " entries found" + Environment.NewLine;
str = m_Settings.LocalizationTable.GetMessage("Search2");
if (str == "")
str = "entries found";
strText += this.SearchCount.ToString() + Constants.Space + str + Environment.NewLine;
strText += Search.TagOpener + Search.TagForwardSlash + strSN
+ Search.TagCloser;
return strText;
}
public AdvancedSearch ExecuteAdvancedSearch(WordList wl)
{
bool fUseGraphemesTaught = this.UseGraphemesTaught;
ArrayList alGTO = new ArrayList();
if (this.GTO != null)
alGTO = this.GTO.Graphemes;
SearchOptions so = this.SearchOptions;
int nCount = 0;
string strResult = wl.GetDisplayHeadings() + Environment.NewLine;
Word wrd = null;
int nWord = wl.WordCount();
for (int i = 0; i < nWord; i++)
{
wrd = wl.GetWord(i);
if (so == null)
{
if (fUseGraphemesTaught)
{
if (this.MatchesWord(wrd) && wrd.IsBuildableWord(alGTO))
{
nCount++;
strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine;
}
}
else
{
if (this.MatchesWord(wrd))
{
nCount++;
strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine;
}
}
}
else
{
if (so.MatchesWord(wrd))
{
if (so.IsRootOnly)
{
if (this.MatchesRoot(wrd))
{
nCount++;
strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine;
}
}
else
{
if (fUseGraphemesTaught)
{
if (this.MatchesWord(wrd) && wrd.IsBuildableWord(alGTO))
{
nCount++;
strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine;
}
}
else
{
if (this.MatchesWord(wrd))
{
nCount++;
strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine;
}
}
}
}
}
}
if (nCount > 0)
{
this.SearchResults = strResult;
this.SearchCount = nCount;
}
else
{
//this.SearchResults = "***No Results***";
this.SearchResults = m_Settings.LocalizationTable.GetMessage("Search1");
if (this.SearchResults == "")
this.SearchResults = "***No Results***";
this.SearchCount = 0;
}
return this;
}
public AdvancedSearch BrowseAdvancedSearch(WordList wl)
{
string str = "";
bool fUseGraphemesTaught = this.UseGraphemesTaught;
int nCount = 0;
ArrayList al = null;
Color clr = m_HighlightColor;
Font fnt = m_DefaultFont;
Word wrd = null;
ArrayList alGTO = new ArrayList();
if (this.GTO != null)
alGTO = this.GTO.Graphemes;
SearchOptions so = this.SearchOptions;
FormBrowse form = new FormBrowse();
//form.Text = m_Title + " - Browse View";
str = m_Settings.LocalizationTable.GetMessage("SearchB");
if (str == "")
str = "Browse View";
form.Text = m_Title + " - " + str;
al = wl.GetDisplayHeadingsAsArray();
form.AddColHeaders(al, clr, fnt);
for (int i = 0; i < wl.WordCount(); i++)
{
wrd = wl.GetWord(i);
if (so == null)
{
if (fUseGraphemesTaught)
{
if ((this.MatchesWord(wrd)) && (wrd.IsBuildableWord(alGTO)))
{
nCount++;
al = wrd.GetWordInfoAsArray();
form.AddRow(al);
}
}
else
{
if (this.MatchesWord(wrd))
{
nCount++;
al = wrd.GetWordInfoAsArray();
form.AddRow(al);
}
}
}
else
{
so = this.SearchDefinition.MakeSearchOptions(so);
if (so.MatchesWord(wrd))
{
if (so.IsRootOnly)
{
if (fUseGraphemesTaught)
{
if ((this.MatchesRoot(wrd)) && (wrd.IsBuildableWord(alGTO)))
{
nCount++;
al = wrd.GetWordInfoAsArray();
form.AddRow(al);
}
}
else
{
if (this.MatchesRoot(wrd))
{
nCount++;
al = wrd.GetWordInfoAsArray();
form.AddRow(al);
}
}
}
else
{
if (fUseGraphemesTaught)
{
if ((this.MatchesWord(wrd)) && (wrd.IsBuildableWord(alGTO)))
{
nCount++;
al = wrd.GetWordInfoAsArray();
form.AddRow(al);
}
}
else
{
if (this.MatchesWord(wrd))
{
nCount++;
al = wrd.GetWordInfoAsArray();
form.AddRow(al);
}
}
}
}
}
}
//form.Text += " - " + nCount.ToString() + " entries";
str = m_Settings.LocalizationTable.GetMessage("Search3");
if (str == "")
str = "entries";
form.Text += " - " + nCount.ToString() + Constants.Space + str;
form.Show();
return this;
}
private SearchDefinition AddSearchParmForConsonantFeatures(SearchDefinition sd, ConsonantFeatures cf)
{
SearchDefinitionParm sdp = null;
string strTag = AdvancedSearch.kFeature;
sdp = new SearchDefinitionParm(AdvancedSearch.kTarget, AdvancedSearch.kC);
sd.AddSearchParm(sdp);
if (cf.PointOfArticulation != "")
{
sdp = new SearchDefinitionParm(strTag, cf.PointOfArticulation);
sd.AddSearchParm(sdp);
}
if (cf.MannerOfArticulation != "")
{
sdp = new SearchDefinitionParm(strTag, cf.MannerOfArticulation);
sd.AddSearchParm(sdp);
}
if (cf.Voiced)
{
sdp = new SearchDefinitionParm(strTag, ConsonantFeatures.kVoiced);
sd.AddSearchParm(sdp);
}
if (cf.Prenasalized)
{
sdp = new SearchDefinitionParm(strTag, ConsonantFeatures.kPrenasalized);
sd.AddSearchParm(sdp);
}
if (cf.Labialized)
{
sdp = new SearchDefinitionParm(strTag, ConsonantFeatures.kLabialized);
sd.AddSearchParm(sdp);
}
if (cf.Palatalized)
{
sdp = new SearchDefinitionParm(strTag, ConsonantFeatures.kPalatalized);
sd.AddSearchParm(sdp);
}
if (cf.Velarized)
{
sdp = new SearchDefinitionParm(strTag, ConsonantFeatures.kVelarized);
sd.AddSearchParm(sdp);
}
if (cf.Syllabic)
{
sdp = new SearchDefinitionParm(strTag, ConsonantFeatures.kSyllabic);
sd.AddSearchParm(sdp);
}
if (cf.Aspirated)
{
sdp = new SearchDefinitionParm(strTag, ConsonantFeatures.kAspirated);
sd.AddSearchParm(sdp);
}
if (cf.Long)
{
sdp = new SearchDefinitionParm(strTag, ConsonantFeatures.kLong);
sd.AddSearchParm(sdp);
}
if (cf.Glottalized)
{
sdp = new SearchDefinitionParm(strTag, ConsonantFeatures.kGlottalized);
sd.AddSearchParm(sdp);
}
if (cf.Combination)
{
sdp = new SearchDefinitionParm(strTag, ConsonantFeatures.kCombination);
sd.AddSearchParm(sdp);
}
return sd;
}
private SearchDefinition AddSearchParmForVowelFeatures(SearchDefinition sd, VowelFeatures vf)
{
SearchDefinitionParm sdp = null;
string strTag = AdvancedSearch.kFeature;
sdp = new SearchDefinitionParm(AdvancedSearch.kTarget, AdvancedSearch.kV);
sd.AddSearchParm(sdp);
if (vf.Backness != "")
{
sdp = new SearchDefinitionParm(strTag, vf.Backness);
sd.AddSearchParm(sdp);
}
if (vf.Height != "")
{
sdp = new SearchDefinitionParm(strTag, vf.Height);
sd.AddSearchParm(sdp);
}
if (vf.Round)
{
sdp = new SearchDefinitionParm(strTag, VowelFeatures.kRound);
sd.AddSearchParm(sdp);
}
if (vf.PlusAtr)
{
sdp = new SearchDefinitionParm(strTag, VowelFeatures.kPlusAtr);
sd.AddSearchParm(sdp);
}
if (vf.Long)
{
sdp = new SearchDefinitionParm(strTag, VowelFeatures.kLong);
sd.AddSearchParm(sdp);
}
if (vf.Nasal)
{
sdp = new SearchDefinitionParm(strTag, VowelFeatures.kNasal);
sd.AddSearchParm(sdp);
}
return sd;
}
private void SetConsonantFeature(int nSequence, string strFeature)
{
switch (nSequence)
{
case 1:
if (strFeature == ConsonantFeatures.kBilabial)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLabiodental)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kDental)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kAlveolar)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPostalveolar)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kRetroflex)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPalatal)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kVelar)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLabialvelar)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kUvular)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPharyngeal)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kGlottal)
{
this.Sequence1Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPlosive)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kNasal)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kTrill)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kFlap)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kFricative)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kAffricate)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLateralFricative)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLateralApproximant)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kApproximant)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kImplosive)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kEjective)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kClick)
{
this.Sequence1Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kVoiced)
{
this.Sequence1Cns.Voiced = true;
}
else if (strFeature == ConsonantFeatures.kPrenasalized)
{
this.Sequence1Cns.Prenasalized = true;
}
else if (strFeature == ConsonantFeatures.kLabialized)
{
this.Sequence1Cns.Labialized = true;
}
else if (strFeature == ConsonantFeatures.kPalatalized)
{
this.Sequence1Cns.Palatalized = true;
}
else if (strFeature == ConsonantFeatures.kVelarized)
{
this.Sequence1Cns.Velarized = true;
}
else if (strFeature == ConsonantFeatures.kSyllabic)
{
this.Sequence1Cns.Syllabic = true;
}
else if (strFeature == ConsonantFeatures.kAspirated)
{
this.Sequence1Cns.Aspirated = true;
}
else if (strFeature == ConsonantFeatures.kLong)
{
this.Sequence1Cns.Long = true;
}
else if (strFeature == ConsonantFeatures.kGlottalized)
{
this.Sequence1Cns.Glottalized = true;
}
else if (strFeature == ConsonantFeatures.kCombination)
{
this.Sequence1Cns.Combination = true;
}
break;
case 2:
if (strFeature == ConsonantFeatures.kBilabial)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLabiodental)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kDental)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kAlveolar)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPostalveolar)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kRetroflex)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPalatal)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kVelar)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLabialvelar)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kUvular)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPharyngeal)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kGlottal)
{
this.Sequence2Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPlosive)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kNasal)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kTrill)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kFlap)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kFricative)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kAffricate)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLateralFricative)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLateralApproximant)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kApproximant)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kImplosive)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kEjective)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kClick)
{
this.Sequence2Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kVoiced)
{
this.Sequence2Cns.Voiced = true;
}
else if (strFeature == ConsonantFeatures.kPrenasalized)
{
this.Sequence2Cns.Prenasalized = true;
}
else if (strFeature == ConsonantFeatures.kLabialized)
{
this.Sequence2Cns.Labialized = true;
}
else if (strFeature == ConsonantFeatures.kPalatalized)
{
this.Sequence2Cns.Palatalized = true;
}
else if (strFeature == ConsonantFeatures.kVelarized)
{
this.Sequence2Cns.Velarized = true;
}
else if (strFeature == ConsonantFeatures.kSyllabic)
{
this.Sequence2Cns.Syllabic = true;
}
else if (strFeature == ConsonantFeatures.kAspirated)
{
this.Sequence2Cns.Aspirated = true;
}
else if (strFeature == ConsonantFeatures.kLong)
{
this.Sequence2Cns.Long = true;
}
else if (strFeature == ConsonantFeatures.kGlottalized)
{
this.Sequence2Cns.Glottalized = true;
}
else if (strFeature == ConsonantFeatures.kCombination)
{
this.Sequence2Cns.Combination = true;
}
break;
case 3:
if (strFeature == ConsonantFeatures.kBilabial)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLabiodental)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kDental)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kAlveolar)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPostalveolar)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kRetroflex)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPalatal)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kVelar)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLabialvelar)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kUvular)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPharyngeal)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kGlottal)
{
this.Sequence3Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPlosive)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kNasal)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kTrill)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kFlap)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kFricative)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kAffricate)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLateralFricative)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLateralApproximant)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kApproximant)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kImplosive)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kEjective)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kClick)
{
this.Sequence3Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kVoiced)
{
this.Sequence3Cns.Voiced = true;
}
else if (strFeature == ConsonantFeatures.kPrenasalized)
{
this.Sequence3Cns.Prenasalized = true;
}
else if (strFeature == ConsonantFeatures.kLabialized)
{
this.Sequence3Cns.Labialized = true;
}
else if (strFeature == ConsonantFeatures.kPalatalized)
{
this.Sequence3Cns.Palatalized = true;
}
else if (strFeature == ConsonantFeatures.kVelarized)
{
this.Sequence3Cns.Velarized = true;
}
else if (strFeature == ConsonantFeatures.kSyllabic)
{
this.Sequence3Cns.Syllabic = true;
}
else if (strFeature == ConsonantFeatures.kAspirated)
{
this.Sequence3Cns.Aspirated = true;
}
else if (strFeature == ConsonantFeatures.kLong)
{
this.Sequence3Cns.Long = true;
}
else if (strFeature == ConsonantFeatures.kGlottalized)
{
this.Sequence3Cns.Glottalized = true;
}
else if (strFeature == ConsonantFeatures.kCombination)
{
this.Sequence3Cns.Combination = true;
}
break;
case 4:
if (strFeature == ConsonantFeatures.kBilabial)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLabiodental)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kDental)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kAlveolar)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPostalveolar)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kRetroflex)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPalatal)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kVelar)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLabialvelar)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kUvular)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPharyngeal)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kGlottal)
{
this.Sequence4Cns.PointOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kPlosive)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kNasal)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kTrill)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kFlap)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kFricative)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kAffricate)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLateralFricative)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kLateralApproximant)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kApproximant)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kImplosive)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kEjective)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kClick)
{
this.Sequence4Cns.MannerOfArticulation = strFeature;
}
else if (strFeature == ConsonantFeatures.kVoiced)
{
this.Sequence4Cns.Voiced = true;
}
else if (strFeature == ConsonantFeatures.kPrenasalized)
{
this.Sequence4Cns.Prenasalized = true;
}
else if (strFeature == ConsonantFeatures.kLabialized)
{
this.Sequence4Cns.Labialized = true;
}
else if (strFeature == ConsonantFeatures.kPalatalized)
{
this.Sequence4Cns.Palatalized = true;
}
else if (strFeature == ConsonantFeatures.kVelarized)
{
this.Sequence4Cns.Velarized = true;
}
else if (strFeature == ConsonantFeatures.kSyllabic)
{
this.Sequence4Cns.Syllabic = true;
}
else if (strFeature == ConsonantFeatures.kAspirated)
{
this.Sequence4Cns.Aspirated = true;
}
else if (strFeature == ConsonantFeatures.kLong)
{
this.Sequence4Cns.Long = true;
}
else if (strFeature == ConsonantFeatures.kGlottalized)
{
this.Sequence4Cns.Glottalized = true;
}
else if (strFeature == ConsonantFeatures.kCombination)
{
this.Sequence4Cns.Combination = true;
}
break;
default:
break;
}
}
private void SetVowelFeature(int nSequence, string strFeature)
{
switch (nSequence)
{
case 1:
if (strFeature == VowelFeatures.kBack)
{
this.Sequence1Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kCentral)
{
this.Sequence1Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kFront)
{
this.Sequence1Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kHigh)
{
this.Sequence1Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kMid)
{
this.Sequence1Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kLow)
{
this.Sequence1Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kLong)
{
this.Sequence1Vwl.Long = true;
}
else if (strFeature == VowelFeatures.kNasal)
{
this.Sequence1Vwl.Nasal = true;
}
else if (strFeature == VowelFeatures.kPlusAtr)
{
this.Sequence1Vwl.PlusAtr = true;
}
else if (strFeature == VowelFeatures.kRound)
{
this.Sequence1Vwl.Round = true;
}
else if (strFeature == VowelFeatures.kDipthong)
{
this.Sequence1Vwl.Diphthong = true;
}
else if (strFeature == VowelFeatures.kVoiceless)
{
this.Sequence1Vwl.Voiceless = true;
}
break;
case 2:
if (strFeature == VowelFeatures.kBack)
{
this.Sequence2Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kCentral)
{
this.Sequence2Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kFront)
{
this.Sequence2Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kHigh)
{
this.Sequence2Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kMid)
{
this.Sequence2Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kLow)
{
this.Sequence2Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kLong)
{
this.Sequence2Vwl.Long = true;
}
else if (strFeature == VowelFeatures.kNasal)
{
this.Sequence2Vwl.Nasal = true;
}
else if (strFeature == VowelFeatures.kPlusAtr)
{
this.Sequence2Vwl.PlusAtr = true;
}
else if (strFeature == VowelFeatures.kRound)
{
this.Sequence2Vwl.Round = true;
}
else if (strFeature == VowelFeatures.kDipthong)
{
this.Sequence2Vwl.Diphthong = true;
}
else if (strFeature == VowelFeatures.kVoiceless)
{
this.Sequence2Vwl.Voiceless = true;
}
break;
case 3:
if (strFeature == VowelFeatures.kBack)
{
this.Sequence3Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kCentral)
{
this.Sequence3Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kFront)
{
this.Sequence3Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kHigh)
{
this.Sequence3Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kMid)
{
this.Sequence3Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kLow)
{
this.Sequence3Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kLong)
{
this.Sequence3Vwl.Long = true;
}
else if (strFeature == VowelFeatures.kNasal)
{
this.Sequence3Vwl.Nasal = true;
}
else if (strFeature == VowelFeatures.kPlusAtr)
{
this.Sequence3Vwl.PlusAtr = true;
}
else if (strFeature == VowelFeatures.kRound)
{
this.Sequence3Vwl.Round = true;
}
else if (strFeature == VowelFeatures.kDipthong)
{
this.Sequence3Vwl.Diphthong = true;
}
else if (strFeature == VowelFeatures.kVoiceless)
{
this.Sequence3Vwl.Voiceless = true;
}
break;
case 4:
if (strFeature == VowelFeatures.kBack)
{
this.Sequence4Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kCentral)
{
this.Sequence4Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kFront)
{
this.Sequence4Vwl.Backness = strFeature;
}
else if (strFeature == VowelFeatures.kHigh)
{
this.Sequence4Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kMid)
{
this.Sequence4Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kLow)
{
this.Sequence4Vwl.Height = strFeature;
}
else if (strFeature == VowelFeatures.kLong)
{
this.Sequence4Vwl.Long = true;
}
else if (strFeature == VowelFeatures.kNasal)
{
this.Sequence4Vwl.Nasal = true;
}
else if (strFeature == VowelFeatures.kPlusAtr)
{
this.Sequence4Vwl.PlusAtr = true;
}
else if (strFeature == VowelFeatures.kRound)
{
this.Sequence4Vwl.Round = true;
}
else if (strFeature == VowelFeatures.kDipthong)
{
this.Sequence4Vwl.Diphthong = true;
}
else if (strFeature == VowelFeatures.kVoiceless)
{
this.Sequence4Vwl.Voiceless = true;
}
break;
default:
break;
}
}
public bool MatchesWord(Word wrd)
{
bool flag = false;
Grapheme grf = null;
string strGrf = "";
ConsonantFeatures cf = null;
VowelFeatures vf = null;
int nSeqLen = this.GetSequenceLength();
for (int i = 0; i < wrd.GraphemeCount(); i++)
{
bool fMatch = false;
for (int j = 0; j < this.GetSequenceLength(); j++)
{
fMatch = false;
grf = wrd.GetGraphemeWithoutTone(i + j);
if (grf == null)
break;
switch (j)
{
case 0:
strGrf = this.Sequence1Grf;
cf = this.Sequence1Cns;
vf = this.Sequence1Vwl;
break;
case 1:
strGrf = this.Sequence2Grf;
cf = this.Sequence2Cns;
vf = this.Sequence2Vwl;
break;
case 2:
strGrf = this.Sequence3Grf;
cf = this.Sequence3Cns;
vf = this.Sequence3Vwl;
break;
case 3:
strGrf = this.Sequence4Grf;
cf = this.Sequence4Cns;
vf = this.Sequence4Vwl;
break;
}
GraphemeInventory gi = m_Settings.GraphemeInventory;
if ((strGrf != "") && ((strGrf == grf.Symbol) || (strGrf == grf.UpperCase)))
fMatch = true;
if (cf != null)
{
int n = gi.FindConsonantIndex(grf.Symbol);
if (n >= 0)
{
Consonant cns = gi.GetConsonant(n);
if (cns.MatchesFeatures(cf))
fMatch = true;
}
}
if (vf != null)
{
int n = gi.FindVowelIndex(grf.Symbol);
if (n >= 0)
{
Vowel vwl = gi.GetVowel(n);
if (vwl.MatchesFeatures(vf))
fMatch = true;
}
}
if (!fMatch)
break;
}
if (fMatch)
{
flag = true;
break;
}
}
return flag;
}
public bool MatchesRoot(Word wrd)
{
bool flag = false;
Grapheme grf = null;
string strGrf = "";
ConsonantFeatures cf = null;
VowelFeatures vf = null;
for (int i = 0; i < wrd.Root.GraphemeCount(); i++)
{
bool fMatch = false;
for (int j = 0; j < this.GetSequenceLength(); j++)
{
fMatch = false;
grf = wrd.Root.GetGraphemeWithoutTone(i + j);
if (grf == null)
break;
switch (j)
{
case 0:
strGrf = this.Sequence1Grf;
cf = this.Sequence1Cns;
vf = this.Sequence1Vwl;
break;
case 1:
strGrf = this.Sequence2Grf;
cf = this.Sequence2Cns;
vf = this.Sequence2Vwl;
break;
case 2:
strGrf = this.Sequence3Grf;
cf = this.Sequence3Cns;
vf = this.Sequence3Vwl;
break;
case 3:
strGrf = this.Sequence4Grf;
cf = this.Sequence4Cns;
vf = this.Sequence4Vwl;
break;
}
GraphemeInventory gi = m_Settings.GraphemeInventory;
if ((strGrf != "") && ((strGrf == grf.Symbol) || (strGrf == grf.UpperCase)))
fMatch = true;
if (cf != null)
{
int n = gi.FindConsonantIndex(grf.Symbol);
if (n >= 0)
{
Consonant cns = gi.GetConsonant(n);
if (cns.MatchesFeatures(cf))
fMatch = true;
}
}
if (vf != null)
{
int n = gi.FindVowelIndex(grf.Symbol);
if (n >= 0)
{
Vowel vwl = gi.GetVowel(n);
if (vwl.MatchesFeatures(vf))
fMatch = true;
}
}
if (!fMatch)
break;
}
if (fMatch)
{
flag = true;
break;
}
}
return flag;
}
}
}
| |
using UnityEngine;
namespace LavaLeak.Diplomata.Helpers
{
/// <summary>
/// A helper to manipulate any Array.
/// </summary>
public static class ArrayHelper
{
/// <summary>
/// Return one array with a element added in the last position.
/// </summary>
/// <param name="array">The array of elements.</param>
/// <param name="element">The element to add.</param>
/// <typeparam name="T">The type of the array, auto setted by the parameters.</typeparam>
/// <returns>The new array with the element.</returns>
public static T[] Add<T>(T[] array, T element)
{
// TODO: Test this first statement.
// If array is null return a not null array.
if (array == null)
{
array = new T[0];
}
// Reset the array with a new empty position.
var tempArray = new T[array.Length];
for (var i = 0; i < tempArray.Length; i++)
{
tempArray[i] = array[i];
}
// TODO: Test if this loop block is necessary.
array = new T[tempArray.Length + 1];
for (var i = 0; i < tempArray.Length; i++)
{
array[i] = tempArray[i];
}
array[array.Length - 1] = element;
return array;
}
/// <summary>
/// Return a array without the element to remove.
/// </summary>
/// <param name="array">The array of elements.</param>
/// <param name="element">The element to remove.</param>
/// <typeparam name="T">The type of the array, auto setted by the parameters.</typeparam>
/// <returns>The array without the element.</returns>
public static T[] Remove<T>(T[] array, T element)
{
// Create a new array with one less position.
var returnedArray = new T[array.Length - 1];
// Flag to use if element was found or don't.
var unfound = true;
// Initialize to set the positions of to the new array.
var j = 0;
// Loop of the referenced array.
for (var i = 0; i < array.Length; i++)
{
if (array[i].Equals(element))
{
unfound = false;
}
else
{
returnedArray[j] = array[i];
j++;
}
}
// Check if the element is in the array.
if (unfound)
{
Debug.LogWarning("Object not found in this array.");
return array;
}
// Return the array without the element.
else
{
return returnedArray;
}
}
/// <summary>
/// Return a array with the position swapped.
/// </summary>
/// <param name="array">The array of elements.</param>
/// <param name="from">Original position.</param>
/// <param name="to">Target position.</param>
/// <typeparam name="T">The type of the array, auto setted by the parameters.</typeparam>
/// <returns>The array copy with elements positions swapped.</returns>
public static T[] Swap<T>(T[] array, int from, int to)
{
// Check if the positions are in the array range.
if (from < array.Length && to < array.Length && from >= 0 && to >= 0)
{
// Create a new array with the same length of the reference.
T[] returnedArray = new T[array.Length];
// Make a loop with the referenced array.
for (int i = 0; i < array.Length; i++)
{
if (i != from && i != to)
{
returnedArray[i] = array[i];
}
// Make the swaps.
if (i == from)
{
returnedArray[to] = array[from];
}
if (i == to)
{
returnedArray[from] = array[to];
}
}
return returnedArray;
}
else
{
Debug.LogWarning(from + " and " + to + " are indexes out of range (0 - " + (array.Length - 1) + ").");
return array;
}
}
/// <summary>
/// Make a real copy of a array, not a reference.
/// </summary>
/// <param name="copyOf">The array to copy.</param>
/// <typeparam name="T">The type of the array, auto setted by the parameters.</typeparam>
/// <returns>The copy of the array.</returns>
public static T[] Copy<T>(T[] copyOf)
{
// Create a array with the same length of the referenced
T[] array = new T[copyOf.Length];
// Do a loop to deep copy every element
for (int i = 0; i < copyOf.Length; i++)
{
array[i] = CopyHelper.DeepCopy(copyOf[i]);
}
return array;
}
/// <summary>
/// Get the index of a element.
/// </summary>
/// <param name="array">The array of elements.</param>
/// <param name="element">The element to find the index.</param>
/// <typeparam name="T">The element and array type.</typeparam>
/// <returns>The index.</returns>
public static int GetIndex<T>(T[] array, T element)
{
// TODO: Check if the anonymous type is a problem.
for (int i = 0; i < array.Length; i++)
{
if (array[i].Equals(element))
{
return i;
}
}
Debug.LogWarning("Cannot find this index. returned: -1");
return -1;
}
/// <summary>
/// Check if the array constains a element.
/// </summary>
/// <param name="array">The array of elements.</param>
/// <param name="element">The element to check if contains.</param>
/// <typeparam name="T">The type of the array, auto setted by the parameters.</typeparam>
/// <returns>A flag with the answer.</returns>
public static bool Contains<T>(T[] array, T element)
{
bool response = false;
if (element != null)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] != null)
{
if (array[i].Equals(element))
{
response = true;
break;
}
}
}
}
return response;
}
/// <summary>
/// Return a empty array.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <returns></returns>
public static T[] Empty<T>()
{
T[] array = new T[0];
return array;
}
/// <summary>
/// Check if the element is the last element of the array.
/// </summary>
/// <param name="array">The array to check.</param>
/// <param name="element">The element to check.</param>
/// <typeparam name="T">The type of the array, auto setted by the parameters.</typeparam>
/// <returns>Return a boolean flag, is true if is the last.</returns>
public static bool IsLast<T>(T[] array, T element)
{
if (array == null || element == null) return false;
return array[array.Length - 1].Equals(element);
}
/// <summary>
/// Merge array of the same type.
/// </summary>
/// <param name="arrays">Arrays to merge.</param>
/// <typeparam name="T">The type of the array, auto setted by the parameters.</typeparam>
/// <returns>Return a array merged.</returns>
public static T[] Merge<T>(params T[][] arrays)
{
var mergedArray = new T[0];
foreach (T[] array in arrays)
{
foreach (var element in array)
{
mergedArray = Add(mergedArray, element);
}
}
return mergedArray;
}
}
}
| |
#region License
// Copyright 2014 MorseCode Software
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MorseCode.RxMvvm.Observable.Property.Internal
{
using System;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
using MorseCode.RxMvvm.Common;
using MorseCode.RxMvvm.Common.DiscriminatedUnion;
using MorseCode.RxMvvm.Common.StaticReflection;
using MorseCode.RxMvvm.Reactive;
[Serializable]
internal class LazyReadOnlyProperty<T> : ReadableObservablePropertyBase<IDiscriminatedUnion<object, T, Exception>>, ILazyReadOnlyProperty<T>, ISerializable
{
#region Fields
private readonly IObservable<T> changeObservable;
private readonly IObservable<IDiscriminatedUnion<object, T, Exception>> changeOrExceptionObservable;
private readonly IObservable<Exception> exceptionObservable;
private readonly object hasLoadBeenCalledLock = new object();
private readonly IObservable<bool> isCalculatedObservable;
private readonly BehaviorSubject<bool> isCalculatedSubject;
private readonly IObservable<bool> isCalculatingObservable;
private readonly BehaviorSubject<bool> isCalculatingSubject;
private readonly bool isLongRunningCalculation;
private readonly IObservable<T> setObservable;
private readonly Lazy<Task<T>> value;
private readonly Func<Task<T>> valueFactory;
private readonly IObservable<IDiscriminatedUnion<object, T, Exception>> valueObservable;
private readonly BehaviorSubject<IDiscriminatedUnion<object, T, Exception>> valueSubject;
private bool hasLoadBeenCalled;
#endregion
#region Constructors and Destructors
internal LazyReadOnlyProperty(Func<Task<T>> valueFactory, bool isLongRunningCalculation)
{
Contract.Requires<ArgumentNullException>(valueFactory != null, "valueFactory");
Contract.Ensures(this.value != null);
Contract.Ensures(this.valueFactory != null);
Contract.Ensures(this.changeObservable != null);
Contract.Ensures(this.changeOrExceptionObservable != null);
Contract.Ensures(this.exceptionObservable != null);
Contract.Ensures(this.isCalculatedObservable != null);
Contract.Ensures(this.isCalculatedSubject != null);
Contract.Ensures(this.isCalculatingObservable != null);
Contract.Ensures(this.isCalculatingSubject != null);
Contract.Ensures(this.setObservable != null);
Contract.Ensures(this.valueObservable != null);
Contract.Ensures(this.valueSubject != null);
this.valueFactory = valueFactory;
this.isLongRunningCalculation = isLongRunningCalculation;
this.isCalculatedSubject = new BehaviorSubject<bool>(false);
this.isCalculatingSubject = new BehaviorSubject<bool>(false);
this.valueSubject = new BehaviorSubject<IDiscriminatedUnion<object, T, Exception>>(DiscriminatedUnion.First<object, T, Exception>(default(T)));
this.value = new Lazy<Task<T>>(valueFactory);
this.valueObservable = this.valueSubject.Do(_ => this.Load());
if (this.valueObservable == null)
{
throw new InvalidOperationException("Result of " + StaticReflection.GetInScopeMethodInfo(() => Observable.Do(null, (Action<object>)null)).Name + " cannot be null.");
}
this.isCalculatedObservable = this.isCalculatedSubject.DistinctUntilChanged();
if (this.isCalculatedObservable == null)
{
throw new InvalidOperationException("Result of " + StaticReflection<IObservable<T>>.GetMethodInfo(o => o.DistinctUntilChanged()).Name + " cannot be null.");
}
this.isCalculatingObservable = this.isCalculatingSubject.DistinctUntilChanged();
if (this.isCalculatingObservable == null)
{
throw new InvalidOperationException("Result of " + StaticReflection<IObservable<T>>.GetMethodInfo(o => o.DistinctUntilChanged()).Name + " cannot be null.");
}
this.setObservable = this.valueObservable.TakeFirst();
this.changeObservable = this.setObservable.DistinctUntilChanged();
if (this.changeObservable == null)
{
throw new InvalidOperationException("Result of " + StaticReflection<IObservable<T>>.GetMethodInfo(o => o.DistinctUntilChanged()).Name + " cannot be null.");
}
this.exceptionObservable = this.valueObservable.TakeSecond();
this.changeOrExceptionObservable = this.changeObservable.Select(DiscriminatedUnion.First<object, T, Exception>).Merge(this.exceptionObservable.Select(DiscriminatedUnion.Second<object, T, Exception>));
if (this.changeOrExceptionObservable == null)
{
throw new InvalidOperationException("Result of " + StaticReflection<IObservable<IDiscriminatedUnion<object, T, Exception>>>.GetMethodInfo(o => o.Merge(null)).Name + " cannot be null.");
}
}
/// <summary>
/// Initializes a new instance of the <see cref="LazyReadOnlyProperty{T}"/> class from serialized data.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The serialization context.
/// </param>
[ContractVerification(false)]
// ReSharper disable UnusedParameter.Local
protected LazyReadOnlyProperty(SerializationInfo info, StreamingContext context) // ReSharper restore UnusedParameter.Local
: this((Func<Task<T>>)(info.GetValue("v", typeof(Func<Task<T>>)) ?? default(T)), (bool)(info.GetValue("l", typeof(bool)) ?? default(T)))
{
}
#endregion
#region Public Properties
public Exception CalculationException
{
get
{
return this.GetValue().Switch(v => null, e => e);
}
}
public bool IsCalculated
{
get
{
return this.isCalculatedSubject.Value;
}
}
public bool IsCalculating
{
get
{
return this.isCalculatingSubject.Value;
}
}
public new T Value
{
get
{
return this.GetValue().Switch(v => v, e => default(T));
}
}
public IDiscriminatedUnion<object, T, Exception> ValueOrException
{
get
{
return this.GetValue();
}
}
#endregion
#region Explicit Interface Properties
Exception ILazyReadOnlyProperty<T>.CalculationException
{
get
{
return this.CalculationException;
}
}
bool ILazyReadOnlyProperty<T>.IsCalculated
{
get
{
return this.IsCalculated;
}
}
bool ILazyReadOnlyProperty<T>.IsCalculating
{
get
{
return this.IsCalculating;
}
}
IObservable<Exception> ILazyReadOnlyProperty<T>.OnCalculationException
{
get
{
return this.exceptionObservable;
}
}
IObservable<bool> ILazyReadOnlyProperty<T>.OnIsCalculatedChanged
{
get
{
return this.isCalculatedObservable;
}
}
IObservable<bool> ILazyReadOnlyProperty<T>.OnIsCalculatingChanged
{
get
{
return this.isCalculatingObservable;
}
}
IObservable<T> ILazyReadOnlyProperty<T>.OnValueOrDefaultChanged
{
get
{
IObservable<T> result = this.GetValueOrDefault(this.OnChanged).DistinctUntilChanged();
if (result == null)
{
throw new InvalidOperationException("Result of " + StaticReflection<IObservable<T>>.GetMethodInfo(o => o.DistinctUntilChanged()).Name + " cannot be null.");
}
return result;
}
}
IObservable<T> ILazyReadOnlyProperty<T>.OnValueOrDefaultSet
{
get
{
return this.GetValueOrDefault(this.OnSet);
}
}
T ILazyReadOnlyProperty<T>.Value
{
get
{
return this.Value;
}
}
IDiscriminatedUnion<object, T, Exception> ILazyReadOnlyProperty<T>.ValueOrException
{
get
{
return this.ValueOrException;
}
}
#endregion
#region Properties
/// <summary>
/// Gets the on changed observable.
/// </summary>
protected override IObservable<IDiscriminatedUnion<object, T, Exception>> OnChanged
{
get
{
return this.changeOrExceptionObservable;
}
}
/// <summary>
/// Gets the on set observable.
/// </summary>
protected override IObservable<IDiscriminatedUnion<object, T, Exception>> OnSet
{
get
{
return this.valueObservable;
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Gets the object data to serialize.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The serialization context.
/// </param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("v", this.valueFactory);
info.AddValue("l", this.isLongRunningCalculation);
}
#endregion
#region Explicit Interface Methods
void ILazyReadOnlyProperty<T>.EagerLoad()
{
this.Load();
}
T ILazyReadOnlyProperty<T>.GetValueOrThrowException()
{
if (this.GetValue() == null)
{
throw new InvalidOperationException("Latest value or exception discriminated union cannot be null.");
}
return this.GetValue().GetValueOrThrowException();
}
#endregion
#region Methods
protected override void Dispose()
{
base.Dispose();
this.valueSubject.Dispose();
this.isCalculatedSubject.Dispose();
this.isCalculatingSubject.Dispose();
}
/// <summary>
/// Gets the value of the property.
/// </summary>
/// <returns>
/// The value of the property.
/// </returns>
protected override IDiscriminatedUnion<object, T, Exception> GetValue()
{
Contract.Ensures(Contract.Result<IDiscriminatedUnion<object, T, Exception>>() != null);
if (!this.value.IsValueCreated)
{
this.Load();
if (RxMvvmConfiguration.IsInDesignMode())
{
while (!this.IsCalculated)
{
Thread.Sleep(20);
}
}
}
if (this.valueSubject.Value == null)
{
throw new InvalidOperationException("Latest value or exception discriminated union cannot be null.");
}
return this.valueSubject.Value;
}
/// <summary>
/// Raises the <see cref="INotifyPropertyChanged.PropertyChanged"/> event for the <see cref="ILazyReadOnlyProperty{T}.CalculationException"/> property.
/// </summary>
protected virtual void OnCalculationExceptionChanged()
{
this.OnPropertyChanged(new PropertyChangedEventArgs(LazyReadOnlyPropertyUtility.CalculationExceptionPropertyName));
}
/// <summary>
/// Raises the <see cref="INotifyPropertyChanged.PropertyChanged"/> event for the <see cref="ILazyReadOnlyProperty{T}.IsCalculated"/> property.
/// </summary>
protected virtual void OnIsCalculatedChanged()
{
this.OnPropertyChanged(new PropertyChangedEventArgs(LazyReadOnlyPropertyUtility.IsCalculatedPropertyName));
}
/// <summary>
/// Raises the <see cref="INotifyPropertyChanged.PropertyChanged"/> event for the <see cref="ILazyReadOnlyProperty{T}.IsCalculating"/> property.
/// </summary>
protected virtual void OnIsCalculatingChanged()
{
this.OnPropertyChanged(new PropertyChangedEventArgs(LazyReadOnlyPropertyUtility.IsCalculatingPropertyName));
}
/// <summary>
/// Raises the <see cref="INotifyPropertyChanged.PropertyChanged"/> event for the <see cref="ILazyReadOnlyProperty{T}.ValueOrException"/> property.
/// </summary>
protected virtual void OnValueOrExceptionChanged()
{
this.OnPropertyChanged(new PropertyChangedEventArgs(LazyReadOnlyPropertyUtility.ValueOrExceptionPropertyName));
}
[ContractInvariantMethod]
private void CodeContractsInvariants()
{
Contract.Invariant(this.value != null);
Contract.Invariant(this.valueFactory != null);
Contract.Invariant(this.changeObservable != null);
Contract.Invariant(this.changeOrExceptionObservable != null);
Contract.Invariant(this.exceptionObservable != null);
Contract.Invariant(this.isCalculatedObservable != null);
Contract.Invariant(this.isCalculatedSubject != null);
Contract.Invariant(this.isCalculatingObservable != null);
Contract.Invariant(this.isCalculatingSubject != null);
Contract.Invariant(this.setObservable != null);
Contract.Invariant(this.valueObservable != null);
Contract.Invariant(this.valueSubject != null);
}
private IObservable<T> GetValueOrDefault(IObservable<IDiscriminatedUnion<object, T, Exception>> o)
{
Contract.Requires<ArgumentNullException>(o != null, "o");
Contract.Ensures(Contract.Result<IObservable<T>>() != null);
IObservable<T> result = o.Select(d => d.Switch(v => v, e => default(T)));
if (result == null)
{
throw new InvalidOperationException("Result of " + StaticReflection<IObservable<T>>.GetMethodInfo(o2 => o2.Select<T, object>(o3 => null)).Name + " cannot be null.");
}
return result;
}
private void Load()
{
if (!this.value.IsValueCreated)
{
lock (this.hasLoadBeenCalledLock)
{
if (this.hasLoadBeenCalled)
{
return;
}
this.hasLoadBeenCalled = true;
}
IScheduler scheduler = this.isLongRunningCalculation ? RxMvvmConfiguration.GetLongRunningCalculationScheduler() : RxMvvmConfiguration.GetCalculationScheduler();
scheduler.Schedule(async () =>
{
IScheduler notifyPropertyChangedScheduler = RxMvvmConfiguration.GetNotifyPropertyChangedScheduler();
this.isCalculatingSubject.OnNext(true);
if (notifyPropertyChangedScheduler != null)
{
notifyPropertyChangedScheduler.Schedule(this.OnIsCalculatingChanged);
}
IDiscriminatedUnion<object, T, Exception> v;
try
{
v = DiscriminatedUnion.First<object, T, Exception>(await this.value.Value.ConfigureAwait(false));
}
catch (Exception e)
{
v = DiscriminatedUnion.Second<object, T, Exception>(e);
}
this.valueSubject.OnNext(v);
if (notifyPropertyChangedScheduler != null)
{
v.Switch(
o =>
{
if (!ReferenceEquals(o, null) && !o.Equals(default(T)))
{
notifyPropertyChangedScheduler.Schedule(this.OnValueOrExceptionChanged);
notifyPropertyChangedScheduler.Schedule(this.OnValueChanged);
}
},
e =>
{
notifyPropertyChangedScheduler.Schedule(this.OnValueOrExceptionChanged);
notifyPropertyChangedScheduler.Schedule(this.OnCalculationExceptionChanged);
});
}
this.isCalculatedSubject.OnNext(true);
if (notifyPropertyChangedScheduler != null)
{
notifyPropertyChangedScheduler.Schedule(this.OnIsCalculatedChanged);
}
this.isCalculatingSubject.OnNext(false);
if (notifyPropertyChangedScheduler != null)
{
notifyPropertyChangedScheduler.Schedule(this.OnIsCalculatingChanged);
}
});
}
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using Free.Controls.TreeView.Tree.NodeControls;
namespace Free.Controls.TreeView.Tree
{
public partial class TreeViewAdv
{
Brush highlightBrush=SystemBrushes.Highlight;
public Brush HighlightBrush
{
get { return highlightBrush; }
set { highlightBrush=value; }
}
public void AutoSizeColumn(TreeColumn column)
{
if(!Columns.Contains(column))
throw new ArgumentException("column");
DrawContext context=new DrawContext();
context.Graphics=Graphics.FromImage(new Bitmap(1, 1));
context.Font=this.Font;
int res=0;
for(int row=0; row<RowCount; row++)
{
if(row<RowMap.Count)
{
int w=0;
TreeNodeAdv node=RowMap[row];
foreach(NodeControl nc in NodeControls)
{
if(nc.ParentColumn==column)
w+=nc.GetActualSize(node, _measureContext).Width;
}
res=Math.Max(res, w);
}
}
if(res>0)
column.Width=res;
}
private void CreatePens()
{
CreateLinePen();
CreateMarkPen();
}
private void CreateMarkPen()
{
GraphicsPath path=new GraphicsPath();
path.AddLines(new Point[] { new Point(0, 0), new Point(1, 1), new Point(-1, 1), new Point(0, 0) });
CustomLineCap cap=new CustomLineCap(null, path);
cap.WidthScale=1.0f;
_markPen=new Pen(_dragDropMarkColor, _dragDropMarkWidth);
_markPen.CustomStartCap=cap;
_markPen.CustomEndCap=cap;
}
private void CreateLinePen()
{
_linePen=new Pen(_lineColor);
_linePen.DashStyle=DashStyle.Dot;
}
protected override void OnPaint(PaintEventArgs e)
{
BeginPerformanceCount();
PerformanceAnalyzer.Start("OnPaint");
DrawContext context=new DrawContext();
context.Graphics=e.Graphics;
context.Font=this.Font;
context.Enabled=Enabled;
int y=0;
int gridHeight=0;
if(UseColumns)
{
DrawColumnHeaders(e.Graphics);
y+=ColumnHeaderHeight;
if(Columns.Count==0||e.ClipRectangle.Height<=y)
return;
}
int firstRowY=_rowLayout.GetRowBounds(FirstVisibleRow).Y;
y-=firstRowY;
e.Graphics.ResetTransform();
e.Graphics.TranslateTransform(-OffsetX, y);
Rectangle displayRect=DisplayRectangle;
for(int row=FirstVisibleRow; row<RowCount; row++)
{
Rectangle rowRect=_rowLayout.GetRowBounds(row);
gridHeight+=rowRect.Height;
if(rowRect.Y+y>displayRect.Bottom)
break;
else
DrawRow(e, ref context, row, rowRect);
}
if((GridLineStyle&GridLineStyle.Vertical)==GridLineStyle.Vertical&&UseColumns)
DrawVerticalGridLines(e.Graphics, firstRowY);
if(_dropPosition.Node!=null&&DragMode&&HighlightDropPosition)
DrawDropMark(e.Graphics);
e.Graphics.ResetTransform();
DrawScrollBarsBox(e.Graphics);
if(DragMode&&_dragBitmap!=null)
e.Graphics.DrawImage(_dragBitmap, PointToClient(MousePosition));
PerformanceAnalyzer.Finish("OnPaint");
EndPerformanceCount(e);
}
private void DrawRow(PaintEventArgs e, ref DrawContext context, int row, Rectangle rowRect)
{
TreeNodeAdv node=RowMap[row];
context.DrawSelection=DrawSelectionMode.None;
context.CurrentEditorOwner=CurrentEditorOwner;
if(DragMode)
{
if((_dropPosition.Node==node)&&_dropPosition.Position==NodePosition.Inside&&HighlightDropPosition)
context.DrawSelection=DrawSelectionMode.Active;
}
else
{
if(node.IsSelected&&Focused)
context.DrawSelection=DrawSelectionMode.Active;
else if(node.IsSelected&&!Focused&&!HideSelection)
context.DrawSelection=DrawSelectionMode.Inactive;
}
context.DrawFocus=Focused&&CurrentNode==node;
OnRowDraw(e, node, context, row, rowRect);
if(FullRowSelect)
{
context.DrawFocus=false;
if(context.DrawSelection==DrawSelectionMode.Active||context.DrawSelection==DrawSelectionMode.Inactive)
{
Rectangle focusRect=new Rectangle(OffsetX, rowRect.Y, ClientRectangle.Width, rowRect.Height);
if(context.DrawSelection==DrawSelectionMode.Active)
{
e.Graphics.FillRectangle(highlightBrush, focusRect);
context.DrawSelection=DrawSelectionMode.FullRowSelect;
}
else
{
e.Graphics.FillRectangle(SystemBrushes.InactiveBorder, focusRect);
context.DrawSelection=DrawSelectionMode.None;
}
}
}
if((GridLineStyle&GridLineStyle.Horizontal)==GridLineStyle.Horizontal)
e.Graphics.DrawLine(SystemPens.InactiveBorder, 0, rowRect.Bottom, e.Graphics.ClipBounds.Right, rowRect.Bottom);
if(ShowLines)
DrawLines(e.Graphics, node, rowRect);
DrawNode(node, context);
}
private void DrawVerticalGridLines(Graphics gr, int y)
{
int x=0;
foreach(TreeColumn c in Columns)
{
if(c.IsVisible)
{
x+=c.Width;
gr.DrawLine(SystemPens.InactiveBorder, x-1, y, x-1, gr.ClipBounds.Bottom);
}
}
}
private void DrawColumnHeaders(Graphics gr)
{
PerformanceAnalyzer.Start("DrawColumnHeaders");
ReorderColumnState reorder=Input as ReorderColumnState;
int x=0;
TreeColumn.DrawBackground(gr, new Rectangle(0, 0, ClientRectangle.Width+2, ColumnHeaderHeight-1), false, false);
gr.TranslateTransform(-OffsetX, 0);
foreach(TreeColumn c in Columns)
{
if(c.IsVisible)
{
if(x>=OffsetX&&x-OffsetX<this.Bounds.Width)// skip invisible columns
{
Rectangle rect=new Rectangle(x, 0, c.Width, ColumnHeaderHeight-1);
gr.SetClip(rect);
bool pressed=((Input is ClickColumnState||reorder!=null)&&((Input as ColumnState).Column==c));
c.Draw(gr, rect, Font, pressed, _hotColumn==c);
gr.ResetClip();
if(reorder!=null&&reorder.DropColumn==c)
TreeColumn.DrawDropMark(gr, rect);
}
x+=c.Width;
}
}
if(reorder!=null)
{
if(reorder.DropColumn==null)
TreeColumn.DrawDropMark(gr, new Rectangle(x, 0, 0, ColumnHeaderHeight));
gr.DrawImage(reorder.GhostImage, new Point(reorder.Location.X+reorder.DragOffset, reorder.Location.Y));
}
PerformanceAnalyzer.Finish("DrawColumnHeaders");
}
public void DrawNode(TreeNodeAdv node, DrawContext context)
{
foreach(NodeControlInfo item in GetNodeControls(node))
{
if(item.Bounds.Right>=OffsetX&&item.Bounds.X-OffsetX<this.Bounds.Width)// skip invisible nodes
{
context.Bounds=item.Bounds;
context.Graphics.SetClip(context.Bounds);
item.Control.Draw(node, context);
context.Graphics.ResetClip();
}
}
}
private void DrawScrollBarsBox(Graphics gr)
{
Rectangle r1=DisplayRectangle;
Rectangle r2=ClientRectangle;
gr.FillRectangle(SystemBrushes.Control,
new Rectangle(r1.Right, r1.Bottom, r2.Width-r1.Width, r2.Height-r1.Height));
}
private void DrawDropMark(Graphics gr)
{
if(_dropPosition.Position==NodePosition.Inside)
return;
Rectangle rect=GetNodeBounds(_dropPosition.Node);
int right=DisplayRectangle.Right-LeftMargin+OffsetX;
int y=rect.Y;
if(_dropPosition.Position==NodePosition.After)
y=rect.Bottom;
gr.DrawLine(_markPen, rect.X, y, right, y);
}
private void DrawLines(Graphics gr, TreeNodeAdv node, Rectangle rowRect)
{
if(UseColumns&&Columns.Count>0)
gr.SetClip(new Rectangle(0, rowRect.Y, Columns[0].Width, rowRect.Bottom));
TreeNodeAdv curNode=node;
while(curNode!=_root&&curNode!=null)
{
int level=curNode.Level;
int x=(level-1)*_indent+NodePlusMinus.ImageSize/2+LeftMargin;
int width=NodePlusMinus.Width-NodePlusMinus.ImageSize/2;
int y=rowRect.Y;
int y2=y+rowRect.Height;
if(curNode==node)
{
int midy=y+rowRect.Height/2;
gr.DrawLine(_linePen, x, midy, x+width, midy);
if(curNode.NextNode==null)
y2=y+rowRect.Height/2;
}
if(node.Row==0)
y=rowRect.Height/2;
if(curNode.NextNode!=null||curNode==node)
gr.DrawLine(_linePen, x, y, x, y2);
curNode=curNode.Parent;
}
gr.ResetClip();
}
#region Performance
private double _totalTime;
private int _paintCount;
[Conditional("PERF_TEST")]
private void BeginPerformanceCount()
{
_paintCount++;
TimeCounter.Start();
}
[Conditional("PERF_TEST")]
private void EndPerformanceCount(PaintEventArgs e)
{
double time=TimeCounter.Finish();
_totalTime+=time;
//string debugText = string.Format("FPS {0:0.0}; Avg. FPS {1:0.0}",
// 1 / time, 1 / (_totalTime / _paintCount));
//e.Graphics.FillRectangle(Brushes.White, new Rectangle(DisplayRectangle.Width - 150, DisplayRectangle.Height - 20, 150, 20));
//e.Graphics.DrawString(debugText, Control.DefaultFont, Brushes.Gray,
// new PointF(DisplayRectangle.Width - 150, DisplayRectangle.Height - 20));
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A train station.
/// </summary>
public class TrainStation_Core : TypeCore, ICivicStructure
{
public TrainStation_Core()
{
this._TypeId = 271;
this._Id = "TrainStation";
this._Schema_Org_Url = "http://schema.org/TrainStation";
string label = "";
GetLabel(out label, "TrainStation", typeof(TrainStation_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,62};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{62};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WebPartChrome.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls.WebParts {
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Web.Handlers;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Util;
public class WebPartChrome {
private const string titleSeparator = " - ";
private const string descriptionSeparator = " - ";
private WebPartManager _manager;
private WebPartConnectionCollection _connections;
private WebPartZoneBase _zone;
// PERF: Cache these, since they are used on every call to FilterVerbs
private Page _page;
private bool _designMode;
private bool _personalizationEnabled;
private PersonalizationScope _personalizationScope;
// PERF: Cache these, since they are needed for every WebPart in the zone
private Style _chromeStyleWithBorder;
private Style _chromeStyleNoBorder;
private Style _titleTextStyle;
private Style _titleStyleWithoutFontOrAlign;
private int _cssStyleIndex;
public WebPartChrome(WebPartZoneBase zone, WebPartManager manager) {
if (zone == null) {
throw new ArgumentNullException("zone");
}
_zone = zone;
_page = zone.Page;
_designMode = zone.DesignMode;
_manager = manager;
if (_designMode) {
// Consider personalization to be enabled at design-time
_personalizationEnabled = true;
}
else {
_personalizationEnabled = (manager != null && manager.Personalization.IsModifiable);
}
if (manager != null) {
_personalizationScope = manager.Personalization.Scope;
}
else {
// Consider scope to be shared at design-time
_personalizationScope = PersonalizationScope.Shared;
}
}
// PERF: Cache the Connections collection on demand
private WebPartConnectionCollection Connections {
get {
if (_connections == null) {
_connections = _manager.Connections;
}
return _connections;
}
}
protected bool DragDropEnabled {
get {
return Zone.DragDropEnabled;
}
}
protected WebPartManager WebPartManager {
get {
return _manager;
}
}
protected WebPartZoneBase Zone {
get {
return _zone;
}
}
private Style CreateChromeStyleNoBorder(Style partChromeStyle) {
Style style = new Style();
style.CopyFrom(Zone.PartChromeStyle);
if (style.BorderStyle != BorderStyle.NotSet) {
style.BorderStyle = BorderStyle.NotSet;
}
if (style.BorderWidth != Unit.Empty) {
style.BorderWidth = Unit.Empty;
}
if (style.BorderColor != Color.Empty) {
style.BorderColor = Color.Empty;
}
return style;
}
private Style CreateChromeStyleWithBorder(Style partChromeStyle) {
Style style = new Style();
style.CopyFrom(partChromeStyle);
if (style.BorderStyle == BorderStyle.NotSet) {
style.BorderStyle = BorderStyle.Solid;
}
if (style.BorderWidth == Unit.Empty) {
style.BorderWidth = Unit.Pixel(1);
}
if (style.BorderColor == Color.Empty) {
style.BorderColor = Color.Black;
}
return style;
}
private Style CreateTitleTextStyle(Style partTitleStyle) {
Style style = new Style();
if (partTitleStyle.ForeColor != Color.Empty) {
style.ForeColor = partTitleStyle.ForeColor;
}
style.Font.CopyFrom(partTitleStyle.Font);
return style;
}
private Style CreateTitleStyleWithoutFontOrAlign(Style partTitleStyle) {
// Need to remove font info from TitleStyle. We only want the font
// info to apply to the title text, not the whole title bar table.
// (NDPWhidbey 27755)
// Use plain style so we don't copy alignment or wrap from TableItemStyle
Style style = new Style();
style.CopyFrom(partTitleStyle);
style.Font.Reset();
if (style.ForeColor != Color.Empty) {
style.ForeColor = Color.Empty;
}
return style;
}
protected virtual Style CreateWebPartChromeStyle(WebPart webPart, PartChromeType chromeType) {
if (webPart == null) {
throw new ArgumentNullException("webPart");
}
if ((chromeType < PartChromeType.Default) || (chromeType > PartChromeType.BorderOnly)) {
throw new ArgumentOutOfRangeException("chromeType");
}
// PERF: Cache these, since they are needed for every WebPart in the zone, and only vary
// if one of the WebParts is selected
Style webPartChromeStyle;
if (chromeType == PartChromeType.BorderOnly || chromeType == PartChromeType.TitleAndBorder) {
if (_chromeStyleWithBorder == null) {
_chromeStyleWithBorder = CreateChromeStyleWithBorder(Zone.PartChromeStyle);
}
webPartChromeStyle = _chromeStyleWithBorder;
}
else {
if (_chromeStyleNoBorder == null) {
_chromeStyleNoBorder = CreateChromeStyleNoBorder(Zone.PartChromeStyle);
}
webPartChromeStyle = _chromeStyleNoBorder;
}
// add SelectedPartChromeStyle
if (WebPartManager != null && webPart == WebPartManager.SelectedWebPart) {
Style style = new Style();
style.CopyFrom(webPartChromeStyle);
style.CopyFrom(Zone.SelectedPartChromeStyle);
return style;
}
else {
return webPartChromeStyle;
}
}
private string GenerateDescriptionText(WebPart webPart) {
string descriptionText = webPart.DisplayTitle;
string description = webPart.Description;
if (!String.IsNullOrEmpty(description)) {
descriptionText += descriptionSeparator + description;
}
return descriptionText;
}
private string GenerateTitleText(WebPart webPart) {
string titleText = webPart.DisplayTitle;
string subtitle = webPart.Subtitle;
if (!String.IsNullOrEmpty(subtitle)) {
titleText += titleSeparator + subtitle;
}
return titleText;
}
protected string GetWebPartChromeClientID(WebPart webPart) {
if (webPart == null) {
throw new ArgumentNullException("webPart");
}
return webPart.WholePartID;
}
protected string GetWebPartTitleClientID(WebPart webPart) {
if (webPart == null) {
throw new ArgumentNullException("webPart");
}
return webPart.TitleBarID;
}
protected virtual WebPartVerbCollection GetWebPartVerbs(WebPart webPart) {
if (webPart == null) {
throw new ArgumentNullException("webPart");
}
return Zone.VerbsForWebPart(webPart);
}
protected virtual WebPartVerbCollection FilterWebPartVerbs(WebPartVerbCollection verbs, WebPart webPart) {
if (verbs == null) {
throw new ArgumentNullException("verbs");
}
if (webPart == null) {
throw new ArgumentNullException("webPart");
}
WebPartVerbCollection filteredVerbs = new WebPartVerbCollection();
foreach (WebPartVerb verb in verbs) {
if (ShouldRenderVerb(verb, webPart)) {
filteredVerbs.Add(verb);
}
}
return filteredVerbs;
}
private void RegisterStyle(Style style) {
Debug.Assert(_page.SupportsStyleSheets);
// The style should not have already been registered
Debug.Assert(style.RegisteredCssClass.Length == 0);
if (!style.IsEmpty) {
string name = Zone.ClientID + "_" + _cssStyleIndex++.ToString(NumberFormatInfo.InvariantInfo);
_page.Header.StyleSheet.CreateStyleRule(style, Zone, "." + name);
style.SetRegisteredCssClass(name);
}
}
public virtual void PerformPreRender() {
if (_page != null && _page.SupportsStyleSheets) {
Style partChromeStyle = Zone.PartChromeStyle;
Style partTitleStyle = Zone.PartTitleStyle;
_chromeStyleWithBorder = CreateChromeStyleWithBorder(partChromeStyle);
RegisterStyle(_chromeStyleWithBorder);
_chromeStyleNoBorder = CreateChromeStyleNoBorder(partChromeStyle);
RegisterStyle(_chromeStyleNoBorder);
_titleTextStyle = CreateTitleTextStyle(partTitleStyle);
RegisterStyle(_titleTextStyle);
_titleStyleWithoutFontOrAlign = CreateTitleStyleWithoutFontOrAlign(partTitleStyle);
RegisterStyle(_titleStyleWithoutFontOrAlign);
if (Zone.RenderClientScript && (Zone.WebPartVerbRenderMode == WebPartVerbRenderMode.Menu) && Zone.Menu != null) {
Zone.Menu.RegisterStyles();
}
}
}
protected virtual void RenderPartContents(HtmlTextWriter writer, WebPart webPart) {
if (!String.IsNullOrEmpty(webPart.ConnectErrorMessage)) {
if (!Zone.ErrorStyle.IsEmpty) {
Zone.ErrorStyle.AddAttributesToRender(writer, Zone);
}
writer.RenderBeginTag(HtmlTextWriterTag.Div);
writer.WriteEncodedText(webPart.ConnectErrorMessage);
writer.RenderEndTag(); // Div
}
else {
webPart.RenderControl(writer);
}
}
// Made non-virtual, since it may be confusing to override this method when it's style
// is rendered by RenderWebPart.
private void RenderTitleBar(HtmlTextWriter writer, WebPart webPart) {
// Can't apply title style here, since the border would be inside the cell padding
// of the parent td.
// titleStyle.AddAttributesToRender(writer, this);
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
// Want table to span full width of part for drag and drop
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
int colspan = 1;
bool showTitleIcons = Zone.ShowTitleIcons;
string titleIconImageUrl = null;
if (showTitleIcons) {
titleIconImageUrl = webPart.TitleIconImageUrl;
if (!String.IsNullOrEmpty(titleIconImageUrl)) {
colspan++;
writer.RenderBeginTag(HtmlTextWriterTag.Td);
RenderTitleIcon(writer, webPart);
writer.RenderEndTag(); // Td
}
}
// title text
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
TableItemStyle titleStyle = Zone.PartTitleStyle;
// Render align and wrap from the TableItemStyle (copied from TableItemStyle.cs)
if (titleStyle.Wrap == false) {
writer.AddStyleAttribute(HtmlTextWriterStyle.WhiteSpace, "nowrap");
}
HorizontalAlign hAlign = titleStyle.HorizontalAlign;
if (hAlign != HorizontalAlign.NotSet) {
TypeConverter hac = TypeDescriptor.GetConverter(typeof(HorizontalAlign));
writer.AddAttribute(HtmlTextWriterAttribute.Align, hac.ConvertToString(hAlign).ToLower(CultureInfo.InvariantCulture));
}
VerticalAlign vAlign = titleStyle.VerticalAlign;
if (vAlign != VerticalAlign.NotSet) {
TypeConverter vac = TypeDescriptor.GetConverter(typeof(VerticalAlign));
writer.AddAttribute(HtmlTextWriterAttribute.Valign, vac.ConvertToString(vAlign).ToLower(CultureInfo.InvariantCulture));
}
if (Zone.RenderClientScript) {
writer.AddAttribute(HtmlTextWriterAttribute.Id, GetWebPartTitleClientID(webPart));
}
writer.RenderBeginTag(HtmlTextWriterTag.Td);
if (showTitleIcons) {
if (!String.IsNullOrEmpty(titleIconImageUrl)) {
// Render so there is a space between the icon and the title text
// Can't be rendered in RenderTitleIcon(), since we want the space to be a valid drag target
writer.Write(" ");
}
}
RenderTitleText(writer, webPart);
writer.RenderEndTag(); // Td
RenderVerbsInTitleBar(writer, webPart, colspan);
writer.RenderEndTag(); // Tr
writer.RenderEndTag(); // Table
}
private void RenderTitleIcon(HtmlTextWriter writer, WebPart webPart) {
//
writer.AddAttribute(HtmlTextWriterAttribute.Src, Zone.ResolveClientUrl(webPart.TitleIconImageUrl) );
// Use "DisplayTitle - Description" as the alt tag (VSWhidbey 376241)
writer.AddAttribute(HtmlTextWriterAttribute.Alt, GenerateDescriptionText(webPart));
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag(); // Img
}
// PERF: Implement RenderTitleText() without using server controls
private void RenderTitleText(HtmlTextWriter writer, WebPart webPart) {
// PERF: Cache this, since it is needed for every WebPart in the zone
if (_titleTextStyle == null) {
_titleTextStyle = CreateTitleTextStyle(Zone.PartTitleStyle);
}
if (!_titleTextStyle.IsEmpty) {
_titleTextStyle.AddAttributesToRender(writer, Zone);
}
// Render "DisplayTitle - Description" as tooltip (VSWhidbey 367041)
writer.AddAttribute(HtmlTextWriterAttribute.Title, GenerateDescriptionText(webPart), true);
//
string url = webPart.TitleUrl;
string text = GenerateTitleText(webPart);
if (!String.IsNullOrEmpty(url) && !DragDropEnabled) {
writer.AddAttribute(HtmlTextWriterAttribute.Href, Zone.ResolveClientUrl(url));
writer.RenderBeginTag(HtmlTextWriterTag.A);
}
else {
writer.RenderBeginTag(HtmlTextWriterTag.Span);
}
writer.WriteEncodedText(text);
writer.RenderEndTag(); // A || Span
// PERF: Always render even if no verbs will be rendered
writer.Write(" ");
}
private void RenderVerb(HtmlTextWriter writer, WebPart webPart, WebPartVerb verb) {
WebControl verbControl;
bool isEnabled = Zone.IsEnabled && verb.Enabled;
ButtonType verbButtonType = Zone.TitleBarVerbButtonType;
if (verb == Zone.HelpVerb) {
//
string resolvedHelpUrl = Zone.ResolveClientUrl(webPart.HelpUrl);
//
if (verbButtonType == ButtonType.Button) {
ZoneButton button = new ZoneButton(Zone, null);
if (isEnabled) {
if (Zone.RenderClientScript) {
button.OnClientClick = "__wpm.ShowHelp('" +
Util.QuoteJScriptString(resolvedHelpUrl) +
"', " +
((int)webPart.HelpMode).ToString(CultureInfo.InvariantCulture) +
");return;";
}
else {
if (webPart.HelpMode != WebPartHelpMode.Navigate) {
button.OnClientClick = "window.open('" +
Util.QuoteJScriptString(resolvedHelpUrl) +
"', '_blank', 'scrollbars=yes,resizable=yes,status=no,toolbar=no,menubar=no,location=no');return;";
}
else {
button.OnClientClick = "window.location.href='" +
Util.QuoteJScriptString(resolvedHelpUrl) +
"';return;";
}
}
}
button.Text = verb.Text;
verbControl = button;
}
else {
HyperLink hyperLink = new HyperLink();
switch (webPart.HelpMode) {
case WebPartHelpMode.Modal:
if (!Zone.RenderClientScript) {
goto case WebPartHelpMode.Modeless;
}
hyperLink.NavigateUrl = "javascript:__wpm.ShowHelp('" +
Util.QuoteJScriptString(resolvedHelpUrl) +
"', 0)";
break;
case WebPartHelpMode.Modeless:
hyperLink.NavigateUrl = resolvedHelpUrl;
hyperLink.Target = "_blank";
break;
case WebPartHelpMode.Navigate:
hyperLink.NavigateUrl = resolvedHelpUrl;
break;
}
hyperLink.Text = verb.Text;
if (verbButtonType == ButtonType.Image) {
hyperLink.ImageUrl = verb.ImageUrl;
}
verbControl = hyperLink;
}
}
else if (verb == Zone.ExportVerb) {
string exportUrl = _manager.GetExportUrl(webPart);
if (verbButtonType == ButtonType.Button) {
ZoneButton button = new ZoneButton(Zone, String.Empty);
button.Text = verb.Text;
if (isEnabled) {
if ((webPart.ExportMode == WebPartExportMode.All) &&
(_personalizationScope == PersonalizationScope.User)) {
if (Zone.RenderClientScript) {
button.OnClientClick = "__wpm.ExportWebPart('" +
Util.QuoteJScriptString(exportUrl) +
"', true, false);return false;";
}
else {
button.OnClientClick = "if(__wpmExportWarning.length == 0 || "
+ "confirm(__wpmExportWarning)){window.location='" +
Util.QuoteJScriptString(exportUrl) +
"';}return false;";
}
}
else {
button.OnClientClick = "window.location='" +
Util.QuoteJScriptString(exportUrl) +
"';return false;";
}
}
verbControl = button;
}
else {
// Special case for export which must be a plain HyperLink
// (href=javascript:void(0) would ruin any redirecting script)
HyperLink link = new HyperLink();
link.Text = verb.Text;
if (verbButtonType == ButtonType.Image) {
link.ImageUrl = verb.ImageUrl;
}
link.NavigateUrl = exportUrl;
if (webPart.ExportMode == WebPartExportMode.All) {
// Confirm before exporting
if (Zone.RenderClientScript) {
link.Attributes.Add("onclick", "return __wpm.ExportWebPart('', true, true)");
}
else {
string onclick = "return (__wpmExportWarning.length == 0 || confirm(__wpmExportWarning))";
link.Attributes.Add("onclick", onclick);
}
}
verbControl = link;
}
}
else {
string eventArgument = verb.GetEventArgument(webPart.ID);
string clientClickHandler = verb.ClientClickHandler;
if (verbButtonType == ButtonType.Button) {
ZoneButton button = new ZoneButton(Zone, eventArgument);
button.Text = verb.Text;
if (!String.IsNullOrEmpty(clientClickHandler) && isEnabled) {
button.OnClientClick = clientClickHandler;
}
verbControl = button;
}
else {
ZoneLinkButton linkButton = new ZoneLinkButton(Zone, eventArgument);
linkButton.Text = verb.Text;
if (verbButtonType == ButtonType.Image) {
linkButton.ImageUrl = verb.ImageUrl;
}
if (!String.IsNullOrEmpty(clientClickHandler) && isEnabled) {
linkButton.OnClientClick = clientClickHandler;
}
verbControl = linkButton;
}
if (_manager != null && isEnabled) {
if (verb == Zone.CloseVerb) {
// PERF: First check if this WebPart even has provider connection points
ProviderConnectionPointCollection connectionPoints = _manager.GetProviderConnectionPoints(webPart);
if (connectionPoints != null && connectionPoints.Count > 0 &&
Connections.ContainsProvider(webPart)) {
string onclick = "if (__wpmCloseProviderWarning.length >= 0 && " +
"!confirm(__wpmCloseProviderWarning)) { return false; }";
verbControl.Attributes.Add("onclick", onclick);
}
}
else if (verb == Zone.DeleteVerb) {
string onclick = "if (__wpmDeleteWarning.length >= 0 && !confirm(__wpmDeleteWarning)) { return false; }";
verbControl.Attributes.Add("onclick", onclick);
}
}
}
verbControl.ApplyStyle(Zone.TitleBarVerbStyle);
verbControl.ToolTip = String.Format(CultureInfo.CurrentCulture, verb.Description, webPart.DisplayTitle);
verbControl.Enabled = verb.Enabled;
verbControl.Page = _page;
verbControl.RenderControl(writer);
}
private void RenderVerbs(HtmlTextWriter writer, WebPart webPart, WebPartVerbCollection verbs) {
if (verbs == null) {
throw new ArgumentNullException("verbs");
}
WebPartVerb priorVerb = null;
foreach (WebPartVerb verb in verbs) {
// If you are rendering as a linkbutton, OR the prior verb rendered as a linkbutton,
// render an " " prior to yourself. This ensures that all linkbuttons are preceeded
// and followed by a space.
if (priorVerb != null && (VerbRenderedAsLinkButton(verb) || VerbRenderedAsLinkButton(priorVerb))) {
writer.Write(" ");
}
RenderVerb(writer, webPart, verb);
priorVerb = verb;
}
}
private void RenderVerbsInTitleBar(HtmlTextWriter writer, WebPart webPart, int colspan) {
WebPartVerbCollection verbs = GetWebPartVerbs(webPart);
verbs = FilterWebPartVerbs(verbs, webPart);
if (verbs != null && verbs.Count > 0) {
writer.AddStyleAttribute(HtmlTextWriterStyle.WhiteSpace, "nowrap");
colspan++;
writer.RenderBeginTag(HtmlTextWriterTag.Td);
if (Zone.RenderClientScript && (Zone.WebPartVerbRenderMode == WebPartVerbRenderMode.Menu) && Zone.Menu != null) {
if (_designMode) {
Zone.Menu.Render(writer, webPart.WholePartID + "Verbs");
}
else {
// If Zone.RenderClientScript, then WebPartManager must not be null
Debug.Assert(WebPartManager != null);
Zone.Menu.Render(writer, verbs, webPart.WholePartID + "Verbs", webPart, WebPartManager);
}
}
else {
RenderVerbs(writer, webPart, verbs);
}
writer.RenderEndTag(); // Td
}
}
public virtual void RenderWebPart(HtmlTextWriter writer, WebPart webPart) {
if (webPart == null) {
throw new ArgumentNullException("webPart");
}
bool vertical = (Zone.LayoutOrientation == Orientation.Vertical);
PartChromeType chromeType = Zone.GetEffectiveChromeType(webPart);
Style partChromeStyle = CreateWebPartChromeStyle(webPart, chromeType);
//
if (!partChromeStyle.IsEmpty) {
partChromeStyle.AddAttributesToRender(writer, Zone);
}
// Render CellPadding=2 so there is a 2 pixel gap between the border and the title/body
// of the WebPart. Can't render CellSpacing=2, since we want the backcolor of the title
// bar to fill the title bar, and backcolor is not rendered in the CellSpacing.
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "2");
writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
if (vertical) {
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100%");
}
else if (webPart.ChromeState != PartChromeState.Minimized) {
writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "100%");
}
if (Zone.RenderClientScript) {
writer.AddAttribute(HtmlTextWriterAttribute.Id, GetWebPartChromeClientID(webPart));
}
if (!_designMode && webPart.Hidden && WebPartManager != null &&
!WebPartManager.DisplayMode.ShowHiddenWebParts) {
writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none");
}
writer.RenderBeginTag(HtmlTextWriterTag.Table);
if (chromeType == PartChromeType.TitleOnly || chromeType == PartChromeType.TitleAndBorder) {
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
// PERF: Cache this, since it is needed for every WebPart in the zone
if (_titleStyleWithoutFontOrAlign == null) {
_titleStyleWithoutFontOrAlign = CreateTitleStyleWithoutFontOrAlign(Zone.PartTitleStyle);
}
// Need to apply title style here (at least backcolor and border) so the backcolor
// and border include the cell padding on the td.
// Should not apply font style here, since we don't want verbs to use this
// font style. In IE compat mode, the font style would not be inherited anyway,
// But in IE strict mode the font style would be inherited.
if (!_titleStyleWithoutFontOrAlign.IsEmpty) {
_titleStyleWithoutFontOrAlign.AddAttributesToRender(writer, Zone);
}
writer.RenderBeginTag(HtmlTextWriterTag.Td);
RenderTitleBar(writer, webPart);
writer.RenderEndTag(); // Td
writer.RenderEndTag(); // Tr
}
// Render the contents of minimized WebParts with display:none, instead of not rendering
// the contents at all. The contents may need to be rendered for client-side connections
// or other client-side features. Also allows child controls to maintain their postback
// values between requests while the WebPart is minimized.
if (webPart.ChromeState == PartChromeState.Minimized) {
writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none");
}
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
if (!vertical) {
writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "100%");
writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
}
Style partStyle = Zone.PartStyle;
if (!partStyle.IsEmpty) {
partStyle.AddAttributesToRender(writer, Zone);
}
// Add some extra padding around the WebPart contents (VSWhidbey 324397)
writer.AddStyleAttribute(HtmlTextWriterStyle.Padding, Zone.PartChromePadding.ToString());
writer.RenderBeginTag(HtmlTextWriterTag.Td);
RenderPartContents(writer, webPart);
writer.RenderEndTag(); // Td
writer.RenderEndTag(); // Tr
writer.RenderEndTag(); // Table
}
private bool ShouldRenderVerb(WebPartVerb verb, WebPart webPart) {
// PERF: Consider caching the Zone.*Verb properties
// Can have null verbs in the CreateVerbs or WebPart.Verbs collections
if (verb == null) {
return false;
}
if (!verb.Visible) {
return false;
}
if (verb == Zone.CloseVerb) {
if (!_personalizationEnabled || !webPart.AllowClose || !Zone.AllowLayoutChange) {
return false;
}
}
if (verb == Zone.ConnectVerb) {
if (WebPartManager != null) {
if ((WebPartManager.DisplayMode != WebPartManager.ConnectDisplayMode) ||
(webPart == WebPartManager.SelectedWebPart) ||
!webPart.AllowConnect) {
return false;
}
// Don't render Connect verb if web part has no connection points
ConsumerConnectionPointCollection consumerConnectionPoints =
WebPartManager.GetEnabledConsumerConnectionPoints(webPart);
ProviderConnectionPointCollection providerConnectionPoints =
WebPartManager.GetEnabledProviderConnectionPoints(webPart);
if ((consumerConnectionPoints == null || consumerConnectionPoints.Count == 0) &&
(providerConnectionPoints == null || providerConnectionPoints.Count == 0)) {
return false;
}
}
}
if (verb == Zone.DeleteVerb) {
if (!_personalizationEnabled ||
!Zone.AllowLayoutChange ||
webPart.IsStatic ||
(webPart.IsShared && _personalizationScope == PersonalizationScope.User) ||
(WebPartManager != null && !WebPartManager.DisplayMode.AllowPageDesign)) {
return false;
}
}
if (verb == Zone.EditVerb) {
if (WebPartManager != null &&
((WebPartManager.DisplayMode != WebPartManager.EditDisplayMode) ||
(webPart == WebPartManager.SelectedWebPart))) {
return false;
}
}
if (verb == Zone.HelpVerb) {
if (String.IsNullOrEmpty(webPart.HelpUrl)) {
return false;
}
}
if (verb == Zone.MinimizeVerb) {
if (!_personalizationEnabled ||
webPart.ChromeState == PartChromeState.Minimized ||
!webPart.AllowMinimize ||
!Zone.AllowLayoutChange) {
return false;
}
}
if (verb == Zone.RestoreVerb) {
if (!_personalizationEnabled ||
webPart.ChromeState == PartChromeState.Normal ||
!Zone.AllowLayoutChange) {
return false;
}
}
if (verb == Zone.ExportVerb) {
if (!_personalizationEnabled ||
webPart.ExportMode == WebPartExportMode.None) {
return false;
}
}
return true;
}
private bool VerbRenderedAsLinkButton(WebPartVerb verb) {
if (Zone.TitleBarVerbButtonType == ButtonType.Link) {
return true;
}
if (String.IsNullOrEmpty(verb.ImageUrl)) {
return true;
}
return false;
}
}
}
| |
// Copyright 2014, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: [email protected] (Anash P. Oommen)
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.Util.v201411;
using Google.Api.Ads.Dfp.v201411;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Configuration;
using System.Collections;
namespace Google.Api.Ads.Dfp.Tests.v201411 {
/// <summary>
/// A utility class to assist the testing of v201411 services.
/// </summary>
public class TestUtils {
public User GetCurrentUser(DfpUser user) {
return GetUserByEmail(user, new DfpAppConfig().Email);
}
public User GetTrafficker(DfpUser user) {
return GetUserByEmail(user, "[email protected]");
}
public User GetSalesperson(DfpUser user) {
return GetUserByEmail(user, "[email protected]");
}
public User GetUserByEmail(DfpUser user, string email) {
UserService userService = (UserService) user.GetService(DfpService.v201411.UserService);
// Create a Statement to get all users sorted by name.
Statement statement = new Statement();
statement.query = string.Format("where email = '{0}' LIMIT 1", email);
UserPage page = userService.getUsersByStatement(statement);
if (page.results != null && page.results.Length > 0) {
return page.results[0];
} else {
return null;
}
}
public Role GetRole(DfpUser user, string roleName) {
UserService userService = (UserService)user.GetService(DfpService.v201411.UserService);
// Get all roles.
Role[] roles = userService.getAllRoles();
foreach (Role role in roles) {
if (role.name == roleName) {
return role;
}
}
return null;
}
/// <summary>
/// Create a test company for running further tests.
/// </summary>
/// <returns>A test company for running further tests.</returns>
public Company CreateCompany(DfpUser user, CompanyType companyType) {
CompanyService companyService = (CompanyService) user.GetService(
DfpService.v201411.CompanyService);
Company company = new Company();
company.name = string.Format("Company #{0}", GetTimeStamp());
company.type = companyType;
return companyService.createCompanies(new Company[] {company})[0];
}
public Order CreateOrder(DfpUser user, long advertiserId, long salespersonId,
long traffickerId) {
// Get the OrderService.
OrderService orderService = (OrderService) user.GetService(DfpService.v201411.OrderService);
Order order = new Order();
order.name = string.Format("Order #{0}", GetTimeStamp());
order.advertiserId = advertiserId;
order.salespersonId = salespersonId;
order.traffickerId = traffickerId;
return orderService.createOrders(new Order[] {order})[0];
}
public LineItem CreateLineItem(DfpUser user, long orderId, string adUnitId) {
LineItemService lineItemService =
(LineItemService) user.GetService(DfpService.v201411.LineItemService);
long placementId = CreatePlacement(user, new string[] {adUnitId}).id;
// Create inventory targeting.
InventoryTargeting inventoryTargeting = new InventoryTargeting();
inventoryTargeting.targetedPlacementIds = new long[] {placementId};
// Create geographical targeting.
GeoTargeting geoTargeting = new GeoTargeting();
// Include the US and Quebec, Canada.
Location countryLocation = new Location();
countryLocation.id = 2840L;
Location regionLocation = new Location();
regionLocation.id = 20123L;
geoTargeting.targetedLocations = new Location[] {countryLocation, regionLocation};
// Exclude Chicago and the New York metro area.
Location cityLocation = new Location();
cityLocation.id = 1016367L;
Location metroLocation = new Location();
metroLocation.id = 200501L;
geoTargeting.excludedLocations = new Location[] {cityLocation, metroLocation};
// Exclude domains that are not under the network's control.
UserDomainTargeting userDomainTargeting = new UserDomainTargeting();
userDomainTargeting.domains = new String[] {"usa.gov"};
userDomainTargeting.targeted = false;
// Create day-part targeting.
DayPartTargeting dayPartTargeting = new DayPartTargeting();
dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;
// Target only the weekend in the browser's timezone.
DayPart saturdayDayPart = new DayPart();
saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201411.DayOfWeek.SATURDAY;
saturdayDayPart.startTime = new TimeOfDay();
saturdayDayPart.startTime.hour = 0;
saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;
saturdayDayPart.endTime = new TimeOfDay();
saturdayDayPart.endTime.hour = 24;
saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;
DayPart sundayDayPart = new DayPart();
sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201411.DayOfWeek.SUNDAY;
sundayDayPart.startTime = new TimeOfDay();
sundayDayPart.startTime.hour = 0;
sundayDayPart.startTime.minute = MinuteOfHour.ZERO;
sundayDayPart.endTime = new TimeOfDay();
sundayDayPart.endTime.hour = 24;
sundayDayPart.endTime.minute = MinuteOfHour.ZERO;
dayPartTargeting.dayParts = new DayPart[] {saturdayDayPart, sundayDayPart};
// Create technology targeting.
TechnologyTargeting technologyTargeting = new TechnologyTargeting();
// Create browser targeting.
BrowserTargeting browserTargeting = new BrowserTargeting();
browserTargeting.isTargeted = true;
// Target just the Chrome browser.
Technology browserTechnology = new Technology();
browserTechnology.id = 500072L;
browserTargeting.browsers = new Technology[] {browserTechnology};
technologyTargeting.browserTargeting = browserTargeting;
LineItem lineItem = new LineItem();
lineItem.name = "Line item #" + new TestUtils().GetTimeStamp();
lineItem.orderId = orderId;
lineItem.targeting = new Targeting();
lineItem.targeting.inventoryTargeting = inventoryTargeting;
lineItem.targeting.geoTargeting = geoTargeting;
lineItem.targeting.userDomainTargeting = userDomainTargeting;
lineItem.targeting.dayPartTargeting = dayPartTargeting;
lineItem.targeting.technologyTargeting = technologyTargeting;
lineItem.lineItemType = LineItemType.STANDARD;
lineItem.allowOverbook = true;
// Set the creative rotation type to even.
lineItem.creativeRotationType = CreativeRotationType.EVEN;
// Set the size of creatives that can be associated with this line item.
Size size = new Size();
size.width = 300;
size.height = 250;
size.isAspectRatio = false;
// Create the creative placeholder.
CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
creativePlaceholder.size = size;
lineItem.creativePlaceholders = new CreativePlaceholder[] {creativePlaceholder};
// Set the length of the line item to run.
//lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1));
// Set the cost per unit to $2.
lineItem.costType = CostType.CPM;
lineItem.costPerUnit = new Money();
lineItem.costPerUnit.currencyCode = "USD";
lineItem.costPerUnit.microAmount = 2000000L;
// Set the number of units bought to 500,000 so that the budget is
// $1,000.
Goal goal = new Goal();
goal.units = 500000L;
goal.unitType = UnitType.IMPRESSIONS;
lineItem.primaryGoal = goal;
return lineItemService.createLineItems(new LineItem[] {lineItem})[0];
}
/// <summary>
/// Create a test company for running further tests.
/// </summary>
/// <returns>A creative for running further tests.</returns>
public Creative CreateCreative(DfpUser user, long advertiserId) {
CreativeService creativeService = (CreativeService)user.GetService(
DfpService.v201411.CreativeService);
// Create creative size.
Size size = new Size();
size.width = 300;
size.height = 250;
// Create an image creative.
ImageCreative imageCreative = new ImageCreative();
imageCreative.name = string.Format("Image creative #{0}", GetTimeStamp());
imageCreative.advertiserId = advertiserId;
imageCreative.destinationUrl = "http://www.google.com";
imageCreative.size = size;
// Create image asset.
CreativeAsset creativeAsset = new CreativeAsset();
creativeAsset.fileName = "image.jpg";
creativeAsset.assetByteArray = MediaUtilities.GetAssetDataFromUrl(
"http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg");
creativeAsset.size = size;
imageCreative.primaryImageAsset = creativeAsset;
return creativeService.createCreatives(new Creative[] {imageCreative})[0];
}
public LineItemCreativeAssociation CreateLica(DfpUser user, long lineItemId, long creativeId) {
LineItemCreativeAssociationService licaService =
(LineItemCreativeAssociationService)user.GetService(
DfpService.v201411.LineItemCreativeAssociationService);
LineItemCreativeAssociation lica = new LineItemCreativeAssociation();
lica.creativeId = creativeId;
lica.lineItemId = lineItemId;
return licaService.createLineItemCreativeAssociations(
new LineItemCreativeAssociation[] {lica})[0];
}
public AdUnit CreateAdUnit(DfpUser user) {
InventoryService inventoryService =
(InventoryService) user.GetService(DfpService.v201411.InventoryService);
AdUnit adUnit = new AdUnit();
adUnit.name = string.Format("Ad_Unit_{0}", GetTimeStamp());
adUnit.parentId = FindRootAdUnit(user).id;
// Set the size of possible creatives that can match this ad unit.
Size size = new Size();
size.width = 300;
size.height = 250;
// Create ad unit size.
AdUnitSize adUnitSize = new AdUnitSize();
adUnitSize.size = size;
adUnitSize.environmentType = EnvironmentType.BROWSER;
adUnit.adUnitSizes = new AdUnitSize[] {adUnitSize};
return inventoryService.createAdUnits(new AdUnit[] {adUnit})[0];
}
public AdUnit FindRootAdUnit(DfpUser user) {
// Get InventoryService.
InventoryService inventoryService =
(InventoryService)user.GetService(DfpService.v201411.InventoryService);
// Create a Statement to only select the root ad unit.
Statement statement = new Statement();
statement.query = "WHERE parentId IS NULL LIMIT 500";
// Get ad units by Statement.
AdUnitPage page = inventoryService.getAdUnitsByStatement(statement);
return page.results[0];
}
public Placement CreatePlacement(DfpUser user, string[] targetedAdUnitIds) {
// Get InventoryService.
PlacementService placementService =
(PlacementService) user.GetService(DfpService.v201411.PlacementService);
Placement placement = new Placement();
placement.name = string.Format("Test placement #{0}", this.GetTimeStamp());
placement.description = "Test placement";
placement.targetedAdUnitIds = targetedAdUnitIds;
return placementService.createPlacements(new Placement[] {placement})[0];
}
public ReportJob CreateReport(DfpUser user) {
// Get ReportService.
ReportService reportService =
(ReportService) user.GetService(DfpService.v201411.ReportService);
ReportJob reportJob = new ReportJob();
reportJob.reportQuery = new ReportQuery();
reportJob.reportQuery.dimensions = new Dimension[] {Dimension.ORDER_ID, Dimension.ORDER_NAME};
reportJob.reportQuery.columns = new Column[] {Column.AD_SERVER_IMPRESSIONS,
Column.AD_SERVER_CLICKS, Column.AD_SERVER_CTR, Column.AD_SERVER_CPM_AND_CPC_REVENUE,
Column.AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM};
reportJob.reportQuery.dateRangeType = DateRangeType.LAST_MONTH;
return reportService.runReportJob(reportJob);
}
/// <summary>
/// Gets the current timestamp as a string.
/// </summary>
/// <returns>The current timestamp as a string.</returns>
public string GetTimeStamp() {
Thread.Sleep(500);
return (System.DateTime.UtcNow - new System.DateTime(1970, 1, 1)).Ticks.
ToString();
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;
using SubSonic.Utilities;
using VistaDB.Provider;
using VistaDB.DDA;
using VistaDB.Extra;
using VistaDB;
using System.Diagnostics;
using System.Collections.Generic;
namespace SubSonic
{
/// <summary>
/// VistaDB Data Provider
/// </summary>
public class VistaDBDataProvider: DataProvider
{
//private DataTable _types = null;
private DataTable _columns = null;
private DataTable _foreignkeys;
// VistaDB FAQ:
// Q: Queries with table name in the form of [dbname].[tablename] give invalid table name error.
// A: That's right. We don't support multiple schemas in single database. The only allowed db name space is [dbo].
// Q: How can you tell if an identity is auto increment or not.
// A: You can tell if an identity is auto increment based upon whether it has a seed and a step expression.
// Q: System tables not the same as sql server, so many sql server schema queries don't work.
// A: We do not have plans to add all of the system tables from SQL Server.
// They do not make sense in most contexts. If you have specific needs ask and we may
// be able to provide something. Remember this is an in process database, SQL Server needs most
// of those because of the server context.
// Q: SCOPE_IDENTITY() not supported in VistaDB. You have to use @@IDENTITY.
// A: Correct. Our identity is unique per connection (once again because we are in proc).
// Q: I want to implement paging with VistaDB. Is a pseudo column like SQL 2005's ROW_NUMBER available?
// A: DDA part allows you to read RowId for the records. That's the analog of what you are asking for.
// These numbers are persistent in table. They are not re-used in row delete operations.
// Only packdatabase operation is followed by re-orderding and re-assigning new values to them.
/// <summary>
/// Creates the connection.
/// </summary>
/// <returns></returns>
public override DbConnection CreateConnection()
{
return CreateConnection(DefaultConnectionString);
}
/// <summary>
/// Creates the connection.
/// </summary>
/// <param name="newConnectionString">The new connection string.</param>
/// <returns></returns>
public override DbConnection CreateConnection(string newConnectionString)
{
VistaDBConnection retVal = new VistaDBConnection(newConnectionString);
retVal.Open();
return retVal;
}
/// <summary>
/// Adds the params.
/// </summary>
/// <param name="cmd">The CMD.</param>
/// <param name="qry">The qry.</param>
private static void AddParams(VistaDBCommand cmd, QueryCommand qry)
{
if (qry.Parameters != null)
{
foreach (QueryParameter param in qry.Parameters)
{
VistaDBParameter sqlParam = new VistaDBParameter(param.ParameterName, Utility.GetSqlDBType(param.DataType));
sqlParam.Direction = param.Mode;
//output parameters need to define a size
//our default is 50
if (sqlParam.Direction == ParameterDirection.Output || sqlParam.Direction == ParameterDirection.InputOutput)
{
sqlParam.Size = param.Size;
}
//fix for NULLs as parameter values
if (param.ParameterValue == null || Utility.IsMatch(param.ParameterValue.ToString(), "null"))
{
sqlParam.Value = DBNull.Value;
}
else if (param.DataType == DbType.Guid)
{
string paramValue = param.ParameterValue.ToString();
if (!String.IsNullOrEmpty(paramValue))
{
if (!Utility.IsMatch(paramValue, SqlSchemaVariable.DEFAULT))
{
sqlParam.Value = new Guid(param.ParameterValue.ToString());
}
}
else
{
sqlParam.Value = DBNull.Value;
}
}
else
{
sqlParam.Value = param.ParameterValue;
}
cmd.Parameters.Add(sqlParam);
}
}
}
/// <summary>
/// Checkouts the output params.
/// </summary>
/// <param name="cmd">The CMD.</param>
/// <param name="qry">The qry.</param>
private static void CheckoutOutputParams(VistaDBCommand cmd, QueryCommand qry)
{
if (qry.CommandType == CommandType.StoredProcedure && qry.HasOutputParams())
{
//loop the params, getting the values and setting them for the return
foreach (QueryParameter param in qry.Parameters)
{
if (param.Mode == ParameterDirection.InputOutput || param.Mode == ParameterDirection.Output || param.Mode == ParameterDirection.ReturnValue)
{
object oVal = cmd.Parameters[param.ParameterName].Value;
param.ParameterValue = oVal;
qry.OutputValues.Add(oVal);
}
}
}
}
/// <summary>
/// Sets the parameter.
/// </summary>
/// <param name="rdr">The RDR.</param>
/// <param name="par">The par.</param>
public override void SetParameter(IDataReader rdr, StoredProcedure.Parameter par)
{
par.DBType = GetDbType(rdr[SqlSchemaVariable.DATA_TYPE].ToString());
string sMode = rdr[SqlSchemaVariable.MODE].ToString();
if (sMode == SqlSchemaVariable.MODE_INOUT)
par.Mode = ParameterDirection.InputOutput;
par.Name = rdr[SqlSchemaVariable.NAME].ToString();
}
/// <summary>
/// Gets the parameter prefix.
/// </summary>
/// <returns></returns>
public override string GetParameterPrefix()
{
return SqlSchemaVariable.PARAMETER_PREFIX;
}
/// <summary>
/// Delimits the name of the db.
/// </summary>
/// <param name="columnName">Name of the column.</param>
/// <returns></returns>
public override string DelimitDbName(string columnName)
{
if(!String.IsNullOrEmpty(columnName) && !columnName.StartsWith("[") && !columnName.EndsWith("]"))
{
return "[" + columnName + "]";
}
return String.Empty;
}
/// <summary>
/// Gets the reader.
/// </summary>
/// <param name="qry">The qry.</param>
/// <returns></returns>
public override IDataReader GetReader(QueryCommand qry)
{
AutomaticConnectionScope automaticConnectionScope = new AutomaticConnectionScope(this);
VistaDBCommand cmd = new VistaDBCommand(qry.CommandSql);
cmd.CommandType = qry.CommandType;
cmd.CommandTimeout = qry.CommandTimeout;
AddParams(cmd, qry);
cmd.Connection = (VistaDBConnection)automaticConnectionScope.Connection;
//let this bubble up
IDataReader rdr;
//Thanks jcoenen!
try
{
// if it is a shared connection, we shouldn't be telling the reader to close it when it is done
if (automaticConnectionScope.IsUsingSharedConnection)
rdr = cmd.ExecuteReader();
else
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (SqlException)
{
// AutoConnectionScope will figure out what to do with the connection
automaticConnectionScope.Dispose();
//rethrow retaining stack trace.
throw;
}
CheckoutOutputParams(cmd, qry);
return rdr;
}
/// <summary>
/// Gets the data set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="qry">The qry.</param>
/// <returns></returns>
public override T GetDataSet<T>(QueryCommand qry)
{
T ds = new T();
if (qry.CommandType == CommandType.Text)
{
qry.CommandSql = qry.CommandSql;
}
VistaDBCommand cmd = new VistaDBCommand(qry.CommandSql);
cmd.CommandType = qry.CommandType;
cmd.CommandTimeout = qry.CommandTimeout;
VistaDBDataAdapter da = new VistaDBDataAdapter(cmd);
AddTableMappings(da, ds);
using (AutomaticConnectionScope conn = new AutomaticConnectionScope(this))
{
cmd.Connection = (VistaDBConnection)conn.Connection;
AddParams(cmd, qry);
da.Fill(ds);
CheckoutOutputParams(cmd, qry);
return ds;
}
}
//-----------------------------------------------------------------------------------------------------------------------//
public override object ExecuteScalar(QueryCommand qry)
{
//using (VistaDBConnection conn = new VistaDBConnection(connectionString))
using (AutomaticConnectionScope automaticConnectionScope = new AutomaticConnectionScope(this))
{
VistaDBCommand cmd = new VistaDBCommand(qry.CommandSql);
cmd.CommandType = qry.CommandType;
cmd.CommandTimeout = qry.CommandTimeout;
AddParams(cmd, qry);
cmd.Connection = (VistaDBConnection)automaticConnectionScope.Connection;
object result = cmd.ExecuteScalar();
CheckoutOutputParams(cmd, qry);
return result;
}
}
//-----------------------------------------------------------------------------------------------------------------------//
public override int ExecuteQuery(QueryCommand qry)
{
using (AutomaticConnectionScope automaticConnectionScope = new AutomaticConnectionScope(this))
{
VistaDBCommand cmd = new VistaDBCommand(qry.CommandSql);
cmd.CommandType = qry.CommandType;
cmd.CommandTimeout = qry.CommandTimeout;
AddParams(cmd, qry);
cmd.Connection = (VistaDBConnection)automaticConnectionScope.Connection;
int result = cmd.ExecuteNonQuery();
CheckoutOutputParams(cmd, qry);
return result;
}
}
//-----------------------------------------------------------------------------------------------------------------------//
private bool IsPrimaryKey(string columnName, IVistaDBTableSchema schema)
{
foreach(IVistaDBIndexInformation info in schema.Indexes)
{
string[] keys = info.KeyExpression.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
ArrayList s = new ArrayList(keys);
if(s.Contains(columnName))
{
if(info.Primary)
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------------------------------------------------//
private bool IsForeignKey(string columnName, IVistaDBTableSchema schema)
{
foreach(IVistaDBRelationshipInformation info in schema.ForeignKeys)
{
string[] keys = info.ForeignKey.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
ArrayList s = new ArrayList(keys);
if(s.Contains(columnName))
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------------------------------------------------//
private bool IsAutoIncrement(string columnName, IVistaDBTableSchema schema)
{
foreach(IVistaDBIdentityInformation info in schema.Identities)
{
if(info.ColumnName == columnName)
{
// TODO: assume it's autoincrement?
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------------------------------------------------//
private string GetColumnDefault(string columnName, IVistaDBTableSchema schema)
{
foreach(IVistaDBDefaultValueInformation info in schema.Defaults)
{
if(info.ColumnName == columnName)
{
return info.Expression;
}
}
return string.Empty;
}
//-----------------------------------------------------------------------------------------------------------------------//
/// <summary>
/// Load and cache all foreign keys
/// </summary>
/// <returns></returns>
private DataTable AllForeignKeys
{
get
{
using(VistaDBConnection con = (VistaDBConnection)CreateConnection())
_foreignkeys = con.GetSchema("FOREIGNKEYS");
return _foreignkeys;
}
}
//-----------------------------------------------------------------------------------------------------------------------//
private DataTable AllColumns
{
get
{
using(VistaDBConnection con = (VistaDBConnection)CreateConnection())
_columns = con.GetSchema("COLUMNS");
return _columns;
}
}
//-----------------------------------------------------------------------------------------------------------------------//
private DataTable GetViewColumns(string viewName)
{
DataTable table = new DataTable();
using(VistaDBConnection conn = (VistaDBConnection)CreateConnection())
{
VistaDBCommand cmd = new VistaDBCommand("SELECT * FROM GetViewColumns('" + viewName + "');");
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
VistaDBDataAdapter da = new VistaDBDataAdapter(cmd);
da.Fill(table);
return table;
}
}
/*
Table: Columns ColumnName: TABLE_CATALOG
Table: Columns ColumnName: TABLE_SCHEMA
Table: Columns ColumnName: TABLE_NAME
Table: Columns ColumnName: COLUMN_NAME
Table: Columns ColumnName: COLUMN_GUID
Table: Columns ColumnName: COLUMN_PROPID
Table: Columns ColumnName: ORDINAL_POSITION
Table: Columns ColumnName: COLUMN_HASDEFAULT
Table: Columns ColumnName: COLUMN_DEFAULT
Table: Columns ColumnName: IS_NULLABLE
Table: Columns ColumnName: DATA_TYPE
Table: Columns ColumnName: TYPE_GUID
Table: Columns ColumnName: CHARACTER_MAXIMUM_LENGTH
Table: Columns ColumnName: CHARACTER_OCTET_LENGTH
Table: Columns ColumnName: NUMERIC_PRECISION
Table: Columns ColumnName: NUMERIC_SCALE
Table: Columns ColumnName: DATETIME_PRECISION
Table: Columns ColumnName: CHARACTER_SET_CATALOG
Table: Columns ColumnName: CHARACTER_SET_SCHEMA
Table: Columns ColumnName: CHARACTER_SET_NAME
Table: Columns ColumnName: COLLATION_CATALOG
Table: Columns ColumnName: COLLATION_SCHEMA
Table: Columns ColumnName: COLLATION_NAME
Table: Columns ColumnName: DOMAIN_CATALOG
Table: Columns ColumnName: DOMAIN_NAME
Table: Columns ColumnName: DESCRIPTION
Table: Columns ColumnName: PRIMARY_KEY
Table: Columns ColumnName: COLUMN_CAPTION
Table: Columns ColumnName: COLUMN_ENCRYPTED
Table: Columns ColumnName: COLUMN_PACKED
Table: ForeignKeys ColumnName: CONSTRAINT_CATALOG
Table: ForeignKeys ColumnName: CONSTRAINT_SCHEMA
Table: ForeignKeys ColumnName: CONSTRAINT_NAME
Table: ForeignKeys ColumnName: TABLE_CATALOG
Table: ForeignKeys ColumnName: TABLE_SCHEMA
Table: ForeignKeys ColumnName: TABLE_NAME
Table: ForeignKeys ColumnName: CONSTRAINT_TYPE
Table: ForeignKeys ColumnName: IS_DEFERRABLE
Table: ForeignKeys ColumnName: INITIALLY_DEFERRED
Table: ForeignKeys ColumnName: FKEY_TO_CATALOG
Table: ForeignKeys ColumnName: FKEY_TO_SCHEMA
Table: ForeignKeys ColumnName: FKEY_TO_TABLE
*/
/// <summary>
/// Gets the table schema.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="tableType">Type of the table.</param>
/// <returns></returns>
public override TableSchema.Table GetTableSchema(string tableName, TableType tableType)
{
Debug.WriteLine("GetTableSchema: tableName = " + tableName);
TableSchema.Table table = new TableSchema.Table(tableName, tableType, this);
table.Name = tableName;
table.Columns = new TableSchema.TableColumnCollection();
table.ForeignKeys = new TableSchema.ForeignKeyTableCollection();
table.SchemaName = string.Empty;
// This will get called on views as well as tables.
// Attempt to create schema for views.
ArrayList viewNames = new ArrayList(GetViewNameList());
if(viewNames.Contains(tableName))
{
// TODO: Check view for IS_UPDATABLE and IS_CORRECT
DataTable viewColumnTable = GetViewColumns(tableName);
//Add all the columns
foreach(DataRow row in viewColumnTable.Rows)
{
TableSchema.TableColumn column = new TableSchema.TableColumn(table);
column.ColumnName = row["COLUMN_NAME"].ToString();
column.IsPrimaryKey = Convert.ToBoolean(row["IS_KEY"]);
// TODO: foreign keys?
column.IsForeignKey = false;
string nativeDataType = row["DATA_TYPE_NAME"].ToString().ToLower();
column.DataType = GetDbType(nativeDataType);
if(column.DataType == DbType.String)
column.MaxLength = Convert.ToInt32(row["COLUMN_SIZE"]);
column.AutoIncrement = false;
if(row["IDENTITY_STEP"] != DBNull.Value)
column.AutoIncrement = Convert.ToInt32(row["IDENTITY_STEP"]) > 0 && Convert.ToBoolean(row["IS_KEY"]);
column.IsNullable = Convert.ToBoolean(row["ALLOW_NULL"]);
column.IsReadOnly = false;
column.DefaultSetting = row["DEFAULT_VALUE"].ToString();
table.Columns.Add(column);
}
return table;
}
else
{
// TODO: Cludge for now. Connection string only has "Data Source=File.vdb3".
string filename = DefaultConnectionString.Substring(DefaultConnectionString.IndexOf("=") + 1);
IVistaDBDatabase db = VistaDBEngine.Connections.OpenDDA().OpenDatabase(filename, VistaDBDatabaseOpenMode.NonexclusiveReadWrite, null);
IVistaDBTableSchema schema = db.TableSchema(tableName);
IVistaDBRelationshipList foreignKeyList = schema.ForeignKeys;
foreach (IVistaDBRelationshipInformation info in foreignKeyList)
{
//Debug.WriteLine(
// " Name: " + info.Name +
// " ForeignKey: " + info.ForeignKey +
// " ForeignTable: " + info.ForeignTable +
// " PrimaryTable: " + info.PrimaryTable +
// " DeleteIntegrity: " + info.DeleteIntegrity.ToString() +
// " UpdateIntegrity: " + info.UpdateIntegrity.ToString());
// TODO: fix this for compound foreign keys.
TableSchema.ForeignKeyTable fk = new TableSchema.ForeignKeyTable(this);
string foreignKey = info.ForeignKey;
if (foreignKey.Contains(";"))
{
foreignKey = foreignKey.Substring(0, foreignKey.IndexOf(";"));
}
fk.ColumnName = foreignKey;
fk.TableName = info.PrimaryTable;
fk.TableType = TableType.Table;
table.ForeignKeys.Add(fk);
}
//Add all the columns
for (int n = 0; n < schema.ColumnCount; n++)
{
TableSchema.TableColumn column = new TableSchema.TableColumn(table);
column.ColumnName = schema[n].Name;
column.IsNullable = schema[n].AllowNull;
column.IsReadOnly = schema[n].ReadOnly;
column.IsPrimaryKey = IsPrimaryKey(column.ColumnName, schema);
column.IsForeignKey = IsForeignKey(column.ColumnName, schema);
column.AutoIncrement = IsAutoIncrement(column.ColumnName, schema);
column.DataType = GetDbType(schema[n].Type.ToString().ToLower());
// System will know the size for non-strings?
if (column.DataType == DbType.String)
column.MaxLength = schema[n].MaxLength;
column.DefaultSetting = GetColumnDefault(column.ColumnName, schema);
table.Columns.Add(column);
}
return table;
}
} // GetTableSchema
/// <summary>
/// Gets the SP params.
/// Not currently supported for VistaDB. No stored procedures.
/// </summary>
/// <param name="spName">Name of the sp.</param>
/// <returns></returns>
public override IDataReader GetSPParams(string spName)
{
return null;
}
/// <summary>
/// Gets the SP list.
/// Not currently supported for VistaDB. No stored procedures.
/// </summary>
/// <returns></returns>
public override string[] GetSPList()
{
return new string[] {};
}
/*
Query to list the database schema (meta information):
SELECT * FROM [DATABASE SCHEMA];
SELECT * FROM GetViews();
SELECT * FROM GetViewColumns('NewView1');
VistDB TypeID Values:
Tables = 1
Table Indexes = 2
Table Columns = 3
Table Constraint = 4
DefaultValue = 5
Table Identity = 6
Relationship = 7
Trigger = 8
Database Description = 9
View = 10
CLR Procs = 11
Assembly containing CLR Procs = 12
*/
/// <summary>
/// Gets the view name list.
/// </summary>
/// <returns></returns>
public override string[] GetViewNameList()
{
// TODO: support views.
//ViewNames = new string[] {};
//return ViewNames;
if(ViewNames == null || !CurrentConnectionStringIsDefault)
{
// Get the views in VistaDB:
QueryCommand cmd = new QueryCommand("SELECT * FROM GetViews()", Name);
StringBuilder sList = new StringBuilder();
using(IDataReader rdr = GetReader(cmd))
{
while(rdr.Read())
{
string viewName = rdr["VIEW_NAME"].ToString();
if(String.IsNullOrEmpty(ViewStartsWith) || viewName.StartsWith(ViewStartsWith))
{
sList.Append(viewName);
sList.Append("|");
}
}
rdr.Close();
}
string strList = sList.ToString();
string[] tempViewNames = strList.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
Array.Sort(tempViewNames);
if(CurrentConnectionStringIsDefault)
{
ViewNames = tempViewNames;
}
else
{
return tempViewNames;
}
}
return ViewNames;
}
/// <summary>
/// Gets the table name list.
/// </summary>
/// <returns></returns>
public override string[] GetTableNameList()
{
if (TableNames == null || !CurrentConnectionStringIsDefault)
{
IVistaDBDatabase db;
VistaDBDataTable table;
string filename = DefaultConnectionString.Substring(DefaultConnectionString.IndexOf("=")+1);
db = VistaDBEngine.Connections.OpenDDA().OpenDatabase(filename, VistaDBDatabaseOpenMode.NonexclusiveReadWrite, null);
ArrayList tables = db.EnumTables();
tables.Sort();
List<string> names = new List<string>();
foreach(string tableName in tables)
{
IVistaDBTableSchema s = db.TableSchema(tableName);
Debug.WriteLine(tableName + ": s.ColumnCount = " + s.ColumnCount);
names.Add(tableName);
}
if(CurrentConnectionStringIsDefault)
{
TableNames = names.ToArray();
}
else
{
return names.ToArray();
}
}
return TableNames;
}
/// <summary>
/// Gets the primary key table names.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <returns></returns>
public override ArrayList GetPrimaryKeyTableNames(string tableName)
{
return new ArrayList();
}
/// <summary>
/// Gets the primary key tables.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <returns></returns>
public override TableSchema.Table[] GetPrimaryKeyTables(string tableName)
{
return null;
}
/// <summary>
/// Gets the name of the foreign key table.
/// </summary>
/// <param name="fkColumnName">Name of the fk column.</param>
/// <param name="tableName">Name of the table.</param>
/// <returns></returns>
public override string GetForeignKeyTableName(string fkColumnName, string tableName)
{
return string.Empty;
}
/// <summary>
/// Gets the name of the foreign key table.
/// </summary>
/// <param name="fkColumnName">Name of the fk column.</param>
/// <returns></returns>
public override string GetForeignKeyTableName(string fkColumnName)
{
return string.Empty;
}
/// <summary>
/// Gets the foreign key tables.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <returns></returns>
public override string[] GetForeignKeyTables(string tableName)
{
return new string[] { "" };
//throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets the table name by primary key.
/// </summary>
/// <param name="pkName">Name of the pk.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public override string GetTableNameByPrimaryKey(string pkName, string providerName)
{
// TODO: Look in to the use of this method and program if possible.
return string.Empty;
}
/// <summary>
/// Gets the database version.
/// </summary>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
protected override string GetDatabaseVersion(string providerName)
{
QueryCommand cmd = new QueryCommand("SELECT @@version", providerName);
object oResult = DataService.ExecuteScalar(cmd);
if(oResult != null)
return oResult.ToString();
return "Unknown";
}
/// <summary>
/// Gets the type of the db.
/// </summary>
/// <param name="sqlType">Type of the SQL.</param>
/// <returns></returns>
public override DbType GetDbType(string sqlType)
{
switch (sqlType)
{
case "varchar":
return DbType.String;
case "nvarchar":
return DbType.String;
case "int":
return DbType.Int32;
case "uniqueidentifier":
return DbType.Guid;
case "datetime":
return DbType.DateTime;
case "bigint":
return DbType.Int64;
case "binary":
return DbType.Binary;
case "bit":
return DbType.Boolean;
case "char":
return DbType.AnsiStringFixedLength;
case "decimal":
return DbType.Decimal;
case "float":
return DbType.Double;
case "image":
return DbType.Binary;
case "money":
return DbType.Currency;
case "nchar":
return DbType.String;
case "ntext":
return DbType.String;
case "numeric":
return DbType.Decimal;
case "real":
return DbType.Decimal;
case "smalldatetime":
return DbType.DateTime;
case "smallint":
return DbType.Int16;
case "smallmoney":
return DbType.Currency;
case "sql_variant":
return DbType.String;
case "sysname":
return DbType.String;
case "text":
return DbType.String;
case "timestamp":
return DbType.Binary;
case "tinyint":
return DbType.Byte;
case "varbinary":
return DbType.Binary;
default:
return DbType.String;
}
}
//-----------------------------------------------------------------------------------------------------------------------//
public override IDbCommand GetCommand(QueryCommand qry)
{
VistaDBCommand cmd = new VistaDBCommand(qry.CommandSql);
AddParams(cmd, qry);
return cmd;
}
//-----------------------------------------------------------------------------------------------------------------------//
/// <summary>
/// Executes a transaction using the passed-commands
/// </summary>
/// <param name="commands"></param>
public override void ExecuteTransaction(QueryCommandCollection commands)
{
//make sure we have at least one
if (commands.Count > 0)
{
VistaDBCommand cmd = null;
//a using statement will make sure we close off the connection
using (AutomaticConnectionScope conn = new AutomaticConnectionScope(this))
{
//open up the connection and start the transaction
if (conn.Connection.State == ConnectionState.Closed)
conn.Connection.Open();
VistaDBTransaction trans = (VistaDBTransaction)conn.Connection.BeginTransaction();
foreach (QueryCommand qry in commands)
{
if (qry.CommandType == CommandType.Text)
{
//qry.CommandSql = "/* ExecuteTransaction() */ " + qry.CommandSql;
qry.CommandSql = qry.CommandSql;
}
cmd = new VistaDBCommand(qry.CommandSql, (VistaDBConnection)conn.Connection); //, trans);
cmd.CommandType = qry.CommandType;
cmd.Transaction = trans;
AddParams(cmd, qry);
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException x)
{
//if there's an error, roll everything back
trans.Rollback();
//clean up
conn.Connection.Close();
cmd.Dispose();
//throw the error retaining the stack.
throw new Exception(x.Message);
}
}
//if we get to this point, we're good to go
trans.Commit();
//close off the connection
conn.Connection.Close();
if (cmd != null)
{
cmd.Dispose();
}
}
}
else
{
throw new Exception("No commands present");
}
}
#region SQL Builders
//-----------------------------------------------------------------------------------------------------------------------//
/// <summary>
/// Helper method to fix the TOP string of a given query.
/// </summary>
/// <param name="qry">Query to build the TOP string from.</param>
/// <returns></returns>
private string GetTop(Query qry)
{
string top = string.Empty;
// Paging doesn't seem to be supported in VistaDB.
if(qry.PageIndex == -1)
{
// By default VistaDB will return 100% of the results
// there is no need to apply a limit so we will
// return an empty string.
if(qry.Top == "100 PERCENT" || String.IsNullOrEmpty(qry.Top))
return top;
// If the Top property of the query contains either
// a % character or the word percent we need to do
// some extra work
if(qry.Top.Contains("%") || qry.Top.ToLower().Contains("percent"))
{
// strip everything but the numeric portion of
// the top property.
top = qry.Top.ToLower().Replace("%", string.Empty).Replace("percent", string.Empty).Trim();
// we will try/catch just incase something fails
// fails a conversion. This gives us an easy out
try
{
// Convert the percetage to a decimal
decimal percentTop = Convert.ToDecimal(top) / 100;
// Get the total count of records to
// be returned.
int count = GetRecordCount(qry);
// Using the new decimal and the amount
// of records to be returned calculate
// what percentage of the records are
// to be returned
top = Convert.ToString((int)(count * percentTop));
}
catch
{
// If something fails in the try lets
// just return an empty string and
// move on.
top = string.Empty;
}
}
else
{
// TODO: paging?
top = qry.Top;
}
}
else
{
// TODO: paging?
top = qry.Top;
}
return top;
}
/// <summary>
/// Creates a SELECT statement based on the Query object settings
/// this is only used with the SQL constructors below
/// it's not used in the command builders above, which need to set the parameters
/// right at the time of the command build
/// </summary>
/// <returns></returns>
public override string GetSelectSql(Query qry)
{
TableSchema.Table table = qry.Schema;
string distinct = qry.IsDistinct ? SqlFragment.DISTINCT : String.Empty;
//different rules for how to do TOP
//string select = "/* GetSelectSql(" + table.Name + ") */ " + SqlFragment.SELECT +
// distinct + SqlFragment.TOP + qry.Top + " ";
//string select = SqlFragment.SELECT + distinct + SqlFragment.TOP + qry.Top + " ";
// TODO: Fix this for VistaDB. There is no PERCENT?
string top = GetTop(qry);
string select;
if(top.Length == 0)
select = SqlFragment.SELECT + distinct + " ";
else
select = SqlFragment.SELECT + distinct + SqlFragment.TOP + top + " ";
StringBuilder order = new StringBuilder();
StringBuilder query = new StringBuilder();
string columns;
//append on the selectList, which is a property that can be set
//and is "*" by default
if (qry.SelectList != null && qry.SelectList.Trim().Length >= 2)
{
columns = qry.SelectList;
}
else
{
columns = GetQualifiedSelect(table);
}
string where = BuildWhere(qry);
//Finally, do the orderby
if (qry.OrderByCollection.Count > 0)
{
order.Append(SqlFragment.ORDER_BY);
for(int j = 0; j < qry.OrderByCollection.Count; j++)
{
string orderString = qry.OrderByCollection[j].OrderString;
if (!String.IsNullOrEmpty(orderString))
{
order.Append(orderString);
if (j + 1 != qry.OrderByCollection.Count)
{
order.Append(", ");
}
}
}
}
else
{
if (table.PrimaryKey != null)
{
order.Append(SqlFragment.ORDER_BY + OrderBy.Asc(table.PrimaryKey.ColumnName).OrderString);
}
}
if (qry.PageIndex < 0)
{
query.Append(select);
query.Append(columns);
query.Append(SqlFragment.FROM);
//query.Append(Utility.QualifyColumnName(table.SchemaName, table.Name, qry.Provider));
query.Append(Utility.QualifyColumnName("DBO", table.Name, qry.Provider));
query.Append(where);
query.Append(order);
query.Append(";");
}
else
{
if (table.PrimaryKey != null)
{
query.Append(string.Format(
PAGING_SQL,
table.PrimaryKey.ColumnName,
Utility.QualifyColumnName(table.SchemaName, table.Name, qry.Provider),
columns,
where,
order,
qry.PageIndex,
qry.PageSize,
Utility.GetSqlDBType(table.PrimaryKey.DataType)));
query.Append(";");
}
else
{
//pretend it's a view
query.Append(string.Format(
PAGING_VIEW_SQL,
Utility.QualifyColumnName(table.SchemaName, table.Name, qry.Provider),
where,
order,
qry.PageIndex,
qry.PageSize));
query.Append(";");
}
}
return query.ToString();
}
#region Paging sql
//thanks Jon G!
private const string PAGING_VIEW_SQL = @"
DECLARE @Page int
DECLARE @PageSize int
SET @Page = {3}
SET @PageSize = {4}
SET NOCOUNT ON
SELECT * INTO #temp FROM {0} WHERE 1 = 0
ALTER TABLE #temp ADD _indexID int PRIMARY KEY IDENTITY(1,1)
INSERT INTO #temp SELECT * FROM {0} {1} {2}
SELECT * FROM #temp
WHERE _indexID BETWEEN ((@Page - 1) * @PageSize + 1) AND (@Page * @PageSize)
--clean up
DROP TABLE #temp
";
private const string PAGING_SQL = @"
DECLARE @Page int
DECLARE @PageSize int
SET @Page = {5}
SET @PageSize = {6}
SET NOCOUNT ON
-- create a temp table to hold order ids
DECLARE @TempTable TABLE (IndexId int identity, _keyID {7})
-- insert the table ids and row numbers into the memory table
INSERT INTO @TempTable
(
_keyID
)
SELECT
{0}
FROM
{1}
{3}
{4}
-- select only those rows belonging to the proper page
SELECT
{2}
FROM {1}
INNER JOIN @TempTable t ON {1}.{0} = t._keyID
WHERE t.IndexId BETWEEN ((@Page - 1) * @PageSize + 1) AND (@Page * @PageSize)
{4}";
#endregion
/// <summary>
/// Returns a qualified list of columns ([Table].[Column])
/// </summary>
/// <returns></returns>
protected static string GetQualifiedSelect(TableSchema.Table table)
{
StringBuilder sb = new StringBuilder();
foreach (TableSchema.TableColumn tc in table.Columns)
{
// VistaDB doesn't support database names.
//sb.AppendFormat(", [{0}].[{1}].[{2}]", table.SchemaName, table.Name, tc.ColumnName);
sb.AppendFormat(", [{0}].[{1}]", table.Name, tc.ColumnName);
}
string result = sb.ToString();
if (result.Length > 1)
result = sb.ToString().Substring(1);
return result;
}
/// <summary>
/// Loops the TableColums[] array for the object, creating a SQL string
/// for use as an INSERT statement
/// </summary>
/// <returns></returns>
public override string GetInsertSql(Query qry)
{
TableSchema.Table table = qry.Schema;
//split the TablNames and loop out the SQL
//string insertSQL = "/* GetInsertSql(" + table.Name + ") */ " + SqlFragment.INSERT_INTO + Utility.QualifyColumnName(table.SchemaName, table.Name, qry.Provider);
string insertSQL = SqlFragment.INSERT_INTO + Utility.QualifyColumnName(table.SchemaName, table.Name, qry.Provider);
//string client = DataService.GetClientType();
string cols = String.Empty;
string pars = String.Empty;
//returns Guid from VS2005 only!
bool primaryKeyIsGuid = false;
string primaryKeyName = "";
bool isFirstColumn = true;
//if table columns are null toss an exception
foreach (TableSchema.TableColumn col in table.Columns)
{
string colName = col.ColumnName;
if( !( col.DataType == DbType.Guid &&
col.DefaultSetting != null &&
col.DefaultSetting == SqlSchemaVariable.DEFAULT ) )
{
if(!col.AutoIncrement && !col.IsReadOnly)
{
if(!isFirstColumn)
{
cols += ",";
pars += ",";
}
isFirstColumn = false;
cols += DelimitDbName(colName);
pars += Utility.PrefixParameter(colName, this);
}
if(col.IsPrimaryKey && col.DataType == DbType.Guid)
{
primaryKeyName = col.ColumnName;
primaryKeyIsGuid = true;
}
}
}
insertSQL += "(" + cols + ") ";
//Non Guid's
// SCOPE_IDENTITY() not supported in VistaDB.
//string getInsertValue = SqlFragment.SELECT + "SCOPE_IDENTITY()" + SqlFragment.AS + "newID;";
string getInsertValue = SqlFragment.SELECT + "@@IDENTITY" + SqlFragment.AS + "newID;";
// SQL Server 2005
if (primaryKeyIsGuid)
{
if (Utility.IsSql2005(this))
{
insertSQL += " OUTPUT INSERTED.[" + primaryKeyName + "]";
}
else
{
getInsertValue = " SELECT @" + primaryKeyName + " as newID;";
}
}
insertSQL += "VALUES(" + pars + ");";
insertSQL += getInsertValue;
// insertSQL = "INSERT INTO [Item_attribute]() VALUES();SELECT @@IDENTITY AS newID;"
return insertSQL;
}
#endregion
#region SQL Scripters
/// <summary>
/// Scripts the data.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="providerName">Name of the provider.</param>
/// <returns></returns>
public override string ScriptData(string tableName, string providerName)
{
StringBuilder fieldList = new StringBuilder();
StringBuilder insertStatement = new StringBuilder();
StringBuilder statements = new StringBuilder();
StringBuilder result = new StringBuilder();
StringBuilder disableConstraint = new StringBuilder();
disableConstraint.AppendLine("ALTER TABLE [" + tableName + "] NOCHECK CONSTRAINT ALL");
disableConstraint.AppendLine("GO");
StringBuilder enableConstraint = new StringBuilder();
enableConstraint.AppendLine("ALTER TABLE [" + tableName + "] CHECK CONSTRAINT ALL");
enableConstraint.AppendLine("GO");
//QueryCommand cmd = new QueryCommand("SELECT CONSTRAINT_NAME FROM DBO.KEY_COLUMN_USAGE WHERE TABLE_NAME='"+ tableName +"'");
//List<string> constraints = new List<string>();
//using (IDataReader rdr = GetReader(cmd))
//{
// while (rdr.Read())
// {
// constraints.Add(rdr["CONSTRAINT_NAME"].ToString());
// }
// if (!rdr.IsClosed)
// {
// rdr.Close();
// }
//}
insertStatement.Append("INSERT INTO [" + tableName + "] ");
//pull the schema for this table
TableSchema.Table table = Query.BuildTableSchema(tableName, providerName);
//build the insert list.
string lastColumnName = table.Columns[table.Columns.Count - 1].ColumnName;
foreach (TableSchema.TableColumn col in table.Columns)
{
fieldList.Append("[");
fieldList.Append(col.ColumnName);
fieldList.Append("]");
if (!Utility.IsMatch(col.ColumnName, lastColumnName))
fieldList.Append(", ");
}
//complete the insert statement
insertStatement.Append("(");
insertStatement.Append(fieldList);
insertStatement.AppendLine(")");
//get the table data
IDataReader rdr = new Query(table).ExecuteReader();
//bool isNumeric = false;
//TableSchema.TableColumn thisColumn=null;
while (rdr.Read())
{
StringBuilder thisStatement = new StringBuilder();
thisStatement.Append(insertStatement);
thisStatement.Append("VALUES(");
//loop the schema and pull out the values from the reader
foreach (TableSchema.TableColumn col in table.Columns)
{
object oData = rdr[col.ColumnName];
if (oData != null && oData != DBNull.Value)
{
if (col.DataType == DbType.Boolean)
{
bool bData = Convert.ToBoolean(oData);
thisStatement.Append(bData ? "1" : " 0");
}
else if (col.DataType == DbType.Byte || col.DataType == DbType.Binary)
{
thisStatement.Append("0x");
thisStatement.Append(Utility.ByteArrayToString((Byte[])oData).ToUpper());
}
else if (col.IsNumeric)
{
thisStatement.Append(oData);
}
else
{
thisStatement.Append("'");
thisStatement.Append(oData.ToString().Replace("'", "''"));
thisStatement.Append("'");
}
}
else
{
thisStatement.Append("NULL");
}
if (!Utility.IsMatch(col.ColumnName, lastColumnName))
thisStatement.Append(", ");
}
//add in a closing paren
thisStatement.AppendLine(")");
statements.Append(thisStatement);
}
rdr.Close();
//if identity is set for the PK, set IDENTITY INSERT to true
result.AppendLine(disableConstraint.ToString());
if (table.PrimaryKey != null)
{
if (table.PrimaryKey.AutoIncrement)
{
result.AppendLine("SET IDENTITY_INSERT [" + tableName + "] ON ");
}
}
result.AppendLine("PRINT 'Begin inserting data in " + tableName + "'");
result.Append(statements);
if (table.PrimaryKey != null)
{
if (table.PrimaryKey.AutoIncrement)
{
result.AppendLine("SET IDENTITY_INSERT [" + tableName + "] OFF ");
}
}
result.AppendLine(enableConstraint.ToString());
return result.ToString();
}
#endregion
#region DataProvider required override methods
/// <summary>
/// Gets the db command.
/// </summary>
/// <param name="qry">The qry.</param>
/// <returns></returns>
public override DbCommand GetDbCommand(QueryCommand qry)
{
DbCommand cmd;
//VistaDBConnection conn = new VistaDBConnection(connectionString);
AutomaticConnectionScope conn = new AutomaticConnectionScope(this);
cmd = conn.Connection.CreateCommand();
cmd.CommandText = qry.CommandSql;
cmd.CommandType = qry.CommandType;
foreach (QueryParameter par in qry.Parameters)
{
cmd.Parameters.Add(par);
}
return cmd;
}
/// <summary>
/// Gets the single record reader.
/// </summary>
/// <param name="qry">The qry.</param>
/// <returns></returns>
public override IDataReader GetSingleRecordReader(QueryCommand cmd)
{
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets the type of the named provider.
/// </summary>
/// <value>The type of the named provider.</value>
public override string NamedProviderType
{
get { return "AccessDataProvider"; }
}
/// <summary>
/// Force-reloads a provider's schema
/// </summary>
public override void ReloadSchema()
{
//Nothing to do here
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Datastream
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Unmanaged;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Data streamer internal interface to get rid of generics.
/// </summary>
internal interface IDataStreamer
{
/// <summary>
/// Callback invoked on topology size change.
/// </summary>
/// <param name="topVer">New topology version.</param>
/// <param name="topSize">New topology size.</param>
void TopologyChange(long topVer, int topSize);
}
/// <summary>
/// Data streamer implementation.
/// </summary>
internal class DataStreamerImpl<TK, TV> : PlatformDisposableTarget, IDataStreamer, IDataStreamer<TK, TV>
{
#pragma warning disable 0420
/** Policy: continue. */
internal const int PlcContinue = 0;
/** Policy: close. */
internal const int PlcClose = 1;
/** Policy: cancel and close. */
internal const int PlcCancelClose = 2;
/** Policy: flush. */
internal const int PlcFlush = 3;
/** Operation: update. */
private const int OpUpdate = 1;
/** Operation: set receiver. */
private const int OpReceiver = 2;
/** */
private const int OpAllowOverwrite = 3;
/** */
private const int OpSetAllowOverwrite = 4;
/** */
private const int OpSkipStore = 5;
/** */
private const int OpSetSkipStore = 6;
/** */
private const int OpPerNodeBufferSize = 7;
/** */
private const int OpSetPerNodeBufferSize = 8;
/** */
private const int OpPerNodeParallelOps = 9;
/** */
private const int OpSetPerNodeParallelOps = 10;
/** */
private const int OpListenTopology = 11;
/** Cache name. */
private readonly string _cacheName;
/** Lock. */
private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
/** Closed event. */
private readonly ManualResetEventSlim _closedEvt = new ManualResetEventSlim(false);
/** Close future. */
private readonly Future<object> _closeFut = new Future<object>();
/** GC handle to this streamer. */
private readonly long _hnd;
/** Topology version. */
private long _topVer;
/** Topology size. */
private int _topSize = 1;
/** Buffer send size. */
private volatile int _bufSndSize;
/** Current data streamer batch. */
private volatile DataStreamerBatch<TK, TV> _batch;
/** Flusher. */
private readonly Flusher<TK, TV> _flusher;
/** Receiver. */
private volatile IStreamReceiver<TK, TV> _rcv;
/** Receiver handle. */
private long _rcvHnd;
/** Receiver binary mode. */
private readonly bool _keepBinary;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="cacheName">Cache name.</param>
/// <param name="keepBinary">Binary flag.</param>
public DataStreamerImpl(IUnmanagedTarget target, Marshaller marsh, string cacheName, bool keepBinary)
: base(target, marsh)
{
_cacheName = cacheName;
_keepBinary = keepBinary;
// Create empty batch.
_batch = new DataStreamerBatch<TK, TV>();
// Allocate GC handle so that this data streamer could be easily dereferenced from native code.
WeakReference thisRef = new WeakReference(this);
_hnd = marsh.Ignite.HandleRegistry.Allocate(thisRef);
// Start topology listening. This call will ensure that buffer size member is updated.
DoOutInOp(OpListenTopology, _hnd);
// Membar to ensure fields initialization before leaving constructor.
Thread.MemoryBarrier();
// Start flusher after everything else is initialized.
_flusher = new Flusher<TK, TV>(thisRef);
_flusher.RunThread();
}
/** <inheritDoc /> */
public string CacheName
{
get { return _cacheName; }
}
/** <inheritDoc /> */
public bool AllowOverwrite
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return DoOutInOp(OpAllowOverwrite) == True;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetAllowOverwrite, value ? True : False);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public bool SkipStore
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return DoOutInOp(OpSkipStore) == True;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetSkipStore, value ? True : False);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeBufferSize
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return (int) DoOutInOp(OpPerNodeBufferSize);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetPerNodeBufferSize, value);
_bufSndSize = _topSize * value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeParallelOperations
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return (int) DoOutInOp(OpPerNodeParallelOps);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetPerNodeParallelOps, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public long AutoFlushFrequency
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return _flusher.Frequency;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
_flusher.Frequency = value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task Task
{
get
{
ThrowIfDisposed();
return _closeFut.Task;
}
}
/** <inheritDoc /> */
public IStreamReceiver<TK, TV> Receiver
{
get
{
ThrowIfDisposed();
return _rcv;
}
set
{
IgniteArgumentCheck.NotNull(value, "value");
var handleRegistry = Marshaller.Ignite.HandleRegistry;
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_rcv == value)
return;
var rcvHolder = new StreamReceiverHolder(value,
(rec, grid, cache, stream, keepBinary) =>
StreamReceiverHolder.InvokeReceiver((IStreamReceiver<TK, TV>) rec, grid, cache, stream,
keepBinary));
var rcvHnd0 = handleRegistry.Allocate(rcvHolder);
try
{
DoOutOp(OpReceiver, w =>
{
w.WriteLong(rcvHnd0);
w.WriteObject(rcvHolder);
});
}
catch (Exception)
{
handleRegistry.Release(rcvHnd0);
throw;
}
if (_rcv != null)
handleRegistry.Release(_rcvHnd);
_rcv = value;
_rcvHnd = rcvHnd0;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task AddData(TK key, TV val)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerEntry<TK, TV>(key, val), 1);
}
/** <inheritDoc /> */
public Task AddData(KeyValuePair<TK, TV> pair)
{
ThrowIfDisposed();
return Add0(new DataStreamerEntry<TK, TV>(pair.Key, pair.Value), 1);
}
/** <inheritDoc /> */
public Task AddData(ICollection<KeyValuePair<TK, TV>> entries)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(entries, "entries");
return Add0(entries, entries.Count);
}
/** <inheritDoc /> */
public Task RemoveData(TK key)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerRemoveEntry<TK>(key), 1);
}
/** <inheritDoc /> */
public void TryFlush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, false, PlcFlush);
}
/** <inheritDoc /> */
public void Flush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, true, PlcFlush);
else
{
// Batch is null, i.e. data streamer is closing. Wait for close to complete.
_closedEvt.Wait();
}
}
/** <inheritDoc /> */
public void Close(bool cancel)
{
_flusher.Stop();
while (true)
{
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 == null)
{
// Wait for concurrent close to finish.
_closedEvt.Wait();
return;
}
if (Flush0(batch0, true, cancel ? PlcCancelClose : PlcClose))
{
_closeFut.OnDone(null, null);
_rwLock.EnterWriteLock();
try
{
base.Dispose(true);
if (_rcv != null)
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd);
_closedEvt.Set();
}
finally
{
_rwLock.ExitWriteLock();
}
Marshaller.Ignite.HandleRegistry.Release(_hnd);
break;
}
}
}
/** <inheritDoc /> */
public IDataStreamer<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_keepBinary)
{
var result = this as IDataStreamer<TK1, TV1>;
if (result == null)
throw new InvalidOperationException(
"Can't change type of binary streamer. WithKeepBinary has been called on an instance of " +
"binary streamer with incompatible generic arguments.");
return result;
}
return new DataStreamerImpl<TK1, TV1>(UU.ProcessorDataStreamer(Marshaller.Ignite.InteropProcessor,
_cacheName, true), Marshaller, _cacheName, true);
}
/** <inheritDoc /> */
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void Dispose(bool disposing)
{
if (disposing)
Close(false); // Normal dispose: do not cancel
else
{
// Finalizer: just close Java streamer
try
{
if (_batch != null)
_batch.Send(this, PlcCancelClose);
}
// ReSharper disable once EmptyGeneralCatchClause
catch (Exception)
{
// Finalizers should never throw
}
Marshaller.Ignite.HandleRegistry.Release(_hnd, true);
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd, true);
}
base.Dispose(false);
}
/** <inheritDoc /> */
~DataStreamerImpl()
{
Dispose(false);
}
/** <inheritDoc /> */
public void TopologyChange(long topVer, int topSize)
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_topVer < topVer)
{
_topVer = topVer;
_topSize = topSize > 0 ? topSize : 1; // Do not set to 0 to avoid 0 buffer size.
_bufSndSize = (int) (_topSize * DoOutInOp(OpPerNodeBufferSize));
}
}
finally
{
_rwLock.ExitWriteLock();
}
}
/// <summary>
/// Internal add/remove routine.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="cnt">Items count.</param>
/// <returns>Future.</returns>
private Task Add0(object val, int cnt)
{
int bufSndSize0 = _bufSndSize;
Debug.Assert(bufSndSize0 > 0);
while (true)
{
var batch0 = _batch;
if (batch0 == null)
throw new InvalidOperationException("Data streamer is stopped.");
int size = batch0.Add(val, cnt);
if (size == -1)
{
// Batch is blocked, perform CAS.
Interlocked.CompareExchange(ref _batch,
new DataStreamerBatch<TK, TV>(batch0), batch0);
continue;
}
if (size >= bufSndSize0)
// Batch is too big, schedule flush.
Flush0(batch0, false, PlcContinue);
return batch0.Task;
}
}
/// <summary>
/// Internal flush routine.
/// </summary>
/// <param name="curBatch"></param>
/// <param name="wait">Whether to wait for flush to complete.</param>
/// <param name="plc">Whether this is the last batch.</param>
/// <returns>Whether this call was able to CAS previous batch</returns>
private bool Flush0(DataStreamerBatch<TK, TV> curBatch, bool wait, int plc)
{
// 1. Try setting new current batch to help further adders.
bool res = Interlocked.CompareExchange(ref _batch,
(plc == PlcContinue || plc == PlcFlush) ?
new DataStreamerBatch<TK, TV>(curBatch) : null, curBatch) == curBatch;
// 2. Perform actual send.
curBatch.Send(this, plc);
if (wait)
// 3. Wait for all futures to finish.
curBatch.AwaitCompletion();
return res;
}
/// <summary>
/// Start write.
/// </summary>
/// <returns>Writer.</returns>
internal void Update(Action<BinaryWriter> action)
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
DoOutOp(OpUpdate, action);
}
finally
{
_rwLock.ExitReadLock();
}
}
/// <summary>
/// Flusher.
/// </summary>
private class Flusher<TK1, TV1>
{
/** State: running. */
private const int StateRunning = 0;
/** State: stopping. */
private const int StateStopping = 1;
/** State: stopped. */
private const int StateStopped = 2;
/** Data streamer. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private readonly WeakReference _ldrRef;
/** Finish flag. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private int _state;
/** Flush frequency. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private long _freq;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ldrRef">Data streamer weak reference..</param>
public Flusher(WeakReference ldrRef)
{
_ldrRef = ldrRef;
lock (this)
{
_state = StateRunning;
}
}
/// <summary>
/// Main flusher routine.
/// </summary>
private void Run()
{
bool force = false;
long curFreq = 0;
try
{
while (true)
{
if (curFreq > 0 || force)
{
var ldr = _ldrRef.Target as DataStreamerImpl<TK1, TV1>;
if (ldr == null)
return;
ldr.TryFlush();
force = false;
}
lock (this)
{
// Stop immediately.
if (_state == StateStopping)
return;
if (curFreq == _freq)
{
// Frequency is unchanged
if (curFreq == 0)
// Just wait for a second and re-try.
Monitor.Wait(this, 1000);
else
{
// Calculate remaining time.
DateTime now = DateTime.Now;
long ticks;
try
{
ticks = now.AddMilliseconds(curFreq).Ticks - now.Ticks;
if (ticks > int.MaxValue)
ticks = int.MaxValue;
}
catch (ArgumentOutOfRangeException)
{
// Handle possible overflow.
ticks = int.MaxValue;
}
Monitor.Wait(this, TimeSpan.FromTicks(ticks));
}
}
else
{
if (curFreq != 0)
force = true;
curFreq = _freq;
}
}
}
}
finally
{
// Let streamer know about stop.
lock (this)
{
_state = StateStopped;
Monitor.PulseAll(this);
}
}
}
/// <summary>
/// Frequency.
/// </summary>
public long Frequency
{
get
{
return Interlocked.Read(ref _freq);
}
set
{
lock (this)
{
if (_freq != value)
{
_freq = value;
Monitor.PulseAll(this);
}
}
}
}
/// <summary>
/// Stop flusher.
/// </summary>
public void Stop()
{
lock (this)
{
if (_state == StateRunning)
{
_state = StateStopping;
Monitor.PulseAll(this);
}
while (_state != StateStopped)
Monitor.Wait(this);
}
}
/// <summary>
/// Runs the flusher thread.
/// </summary>
public void RunThread()
{
new Thread(Run).Start();
}
}
#pragma warning restore 0420
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing
{
using System.Configuration;
using System.Drawing.Configuration;
using System.IO;
using System.Reflection;
/// <summary>
/// Provides methods to select from multiple bitmaps depending on a "bitmapSuffix" config setting.
/// </summary>
internal static class BitmapSelector
{
/// <summary>
/// Gets the bitmap ID suffix defined in the application configuration, or string.Empty if
/// the suffix is not specified. Internal for unit tests
/// </summary>
/// <remarks>
/// For performance, the suffix is cached in a static variable so it only has to be read
/// once per appdomain.
/// </remarks>
private static string s_suffix;
internal static string Suffix
{
get
{
if (s_suffix == null)
{
s_suffix = string.Empty;
var section = ConfigurationManager.GetSection("system.drawing") as SystemDrawingSection;
if (section != null)
{
var value = section.BitmapSuffix;
if (value != null && value is string)
{
s_suffix = (string)value;
}
}
}
return s_suffix;
}
set
{
// So unit tests can clear the cached suffix
s_suffix = value;
}
}
/// <summary>
/// Appends the current suffix to <paramref name="filePath"/>. The suffix is appended
/// before the existing extension (if any). Internal for unit tests.
/// </summary>
/// <returns>
/// The new path with the suffix included. If there is no suffix defined or there are
/// invalid characters in the original path, the original path is returned.
/// </returns>
internal static string AppendSuffix(string filePath)
{
try
{
return Path.ChangeExtension(filePath, Suffix + Path.GetExtension(filePath));
}
catch (ArgumentException)
{ // there are invalid characters in the path
return filePath;
}
}
/// <summary>
/// Returns <paramref name="originalPath"/> with the current suffix appended (before the
/// existing extension) if the resulting file path exists; otherwise the original path is
/// returned.
/// </summary>
public static string GetFileName(string originalPath)
{
if (Suffix == string.Empty)
return originalPath;
string newPath = AppendSuffix(originalPath);
return File.Exists(newPath) ? newPath : originalPath;
}
// Calls assembly.GetManifestResourceStream in a try/catch and returns null if not found
private static Stream GetResourceStreamHelper(Assembly assembly, Type type, string name)
{
Stream stream = null;
try
{
stream = assembly.GetManifestResourceStream(type, name);
}
catch (FileNotFoundException)
{
}
return stream;
}
private static bool DoesAssemblyHaveCustomAttribute(Assembly assembly, string typeName)
{
return DoesAssemblyHaveCustomAttribute(assembly, assembly.GetType(typeName));
}
private static bool DoesAssemblyHaveCustomAttribute(Assembly assembly, Type attrType)
{
if (attrType != null)
{
var attr = assembly.GetCustomAttributes(attrType, false);
if (attr.Length > 0)
{
return true;
}
}
return false;
}
// internal for unit tests
internal static bool SatelliteAssemblyOptIn(Assembly assembly)
{
// Try 4.5 public attribute type first
if (DoesAssemblyHaveCustomAttribute(assembly, typeof(BitmapSuffixInSatelliteAssemblyAttribute)))
{
return true;
}
// Also load attribute type by name for dlls compiled against older frameworks
return DoesAssemblyHaveCustomAttribute(assembly, "System.Drawing.BitmapSuffixInSatelliteAssemblyAttribute");
}
// internal for unit tests
internal static bool SameAssemblyOptIn(Assembly assembly)
{
// Try 4.5 public attribute type first
if (DoesAssemblyHaveCustomAttribute(assembly, typeof(BitmapSuffixInSameAssemblyAttribute)))
{
return true;
}
// Also load attribute type by name for dlls compiled against older frameworks
return DoesAssemblyHaveCustomAttribute(assembly, "System.Drawing.BitmapSuffixInSameAssemblyAttribute");
}
/// <summary>
/// Returns a resource stream loaded from the appropriate location according to the current
/// suffix.
/// </summary>
/// <param name="assembly">The assembly from which the stream is loaded</param>
/// <param name="type">The type whose namespace is used to scope the manifest resource name</param>
/// <param name="originalName">The name of the manifest resource being requested</param>
/// <returns>
/// The manifest resource stream corresponding to <paramref name="originalName"/> with the
/// current suffix applied; or if that is not found, the stream corresponding to <paramref name="originalName"/>.
/// </returns>
public static Stream GetResourceStream(Assembly assembly, Type type, string originalName)
{
if (Suffix != string.Empty)
{
try
{
// Resource with suffix has highest priority
if (SameAssemblyOptIn(assembly))
{
string newName = AppendSuffix(originalName);
Stream stream = GetResourceStreamHelper(assembly, type, newName);
if (stream != null)
{
return stream;
}
}
}
catch
{
// Ignore failures and continue to try other options
}
try
{
// Satellite assembly has second priority, using the original name
if (SatelliteAssemblyOptIn(assembly))
{
AssemblyName assemblyName = assembly.GetName();
assemblyName.Name += Suffix;
assemblyName.ProcessorArchitecture = ProcessorArchitecture.None;
Assembly satellite = Assembly.Load(assemblyName);
if (satellite != null)
{
Stream stream = GetResourceStreamHelper(satellite, type, originalName);
if (stream != null)
{
return stream;
}
}
}
}
catch
{
// Ignore failures and continue to try other options
}
}
// Otherwise fall back to specified assembly and original name requested
return assembly.GetManifestResourceStream(type, originalName);
}
/// <summary>
/// Returns a resource stream loaded from the appropriate location according to the current
/// suffix.
/// </summary>
/// <param name="type">The type from whose assembly the stream is loaded and whose namespace is used to scope the resource name</param>
/// <param name="originalName">The name of the manifest resource being requested</param>
/// <returns>
/// The manifest resource stream corresponding to <paramref name="originalName"/> with the
/// current suffix applied; or if that is not found, the stream corresponding to <paramref name="originalName"/>.
/// </returns>
public static Stream GetResourceStream(Type type, string originalName)
{
return GetResourceStream(type.Module.Assembly, type, originalName);
}
/// <summary>
/// Returns an Icon created from a resource stream loaded from the appropriate location according to the current
/// suffix.
/// </summary>
/// <param name="type">The type from whose assembly the stream is loaded and whose namespace is used to scope the resource name</param>
/// <param name="originalName">The name of the manifest resource being requested</param>
/// <returns>
/// The icon created from a manifest resource stream corresponding to <paramref name="originalName"/> with the
/// current suffix applied; or if that is not found, the stream corresponding to <paramref name="originalName"/>.
/// </returns>
public static Icon CreateIcon(Type type, string originalName)
{
return new Icon(GetResourceStream(type, originalName));
}
/// <summary>
/// Returns an Bitmap created from a resource stream loaded from the appropriate location according to the current
/// suffix.
/// </summary>
/// <param name="type">The type from whose assembly the stream is loaded and whose namespace is used to scope the resource name</param>
/// <param name="originalName">The name of the manifest resource being requested</param>
/// <returns>
/// The bitmap created from a manifest resource stream corresponding to <paramref name="originalName"/> with the
/// current suffix applied; or if that is not found, the stream corresponding to <paramref name="originalName"/>.
/// </returns>
public static Bitmap CreateBitmap(Type type, string originalName)
{
return new Bitmap(GetResourceStream(type, originalName));
}
}
}
| |
// This code was generated by the Gardens Point Parser Generator
// Copyright (c) Wayne Kelly, John Gough, QUT 2005-2014
// (see accompanying GPPGcopyright.rtf)
// GPPG version 1.5.2
// Machine: DESKTOP-JOHN
// DateTime: 23/01/2016 15:13:10
// UserName: jncro
// Input file <jcasm.y - 23/01/2016 15:13:09>
// options: lines gplex
using System;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using System.Globalization;
using System.Text;
using QUT.Gppg;
namespace jcasm
{
internal enum Tokens {error=2,EOF=3,NEWLINE=4,COMMA=5,COLON=6,
ASSIGN=7,SEMICOLON=8,DOT=9,LPAREN=10,RPAREN=11,TEXT=12,
DATA=13,RODATA=14,BSS=15,FILE=16,GLOBL=17,LOCAL=18,
EXTERN=19,COMM=20,ALIGN=21,TYPE=22,SIZE=23,IDENT=24,
SECTION=25,DB=26,DW=27,DD=28,AT=29,LOR=30,
LAND=31,OR=32,AND=33,EQUALS=34,NOTEQUAL=35,LT=36,
GT=37,LEQUAL=38,GEQUAL=39,PLUS=40,MINUS=41,MUL=42,
NOT=43,LNOT=44,INT=45,STRING=46,LABEL=47,LOCLABEL=48,
CC=49,REG=50};
internal partial struct ValueType
#line 13 "jcasm.y"
{
public int intval;
public string strval;
public Statement stmtval;
public Condition condval;
public List<Expression> dilist;
public DataDirective.DDType ddtype;
public Expression exprval;
}
#line default
// Abstract base class for GPLEX scanners
[GeneratedCodeAttribute( "Gardens Point Parser Generator", "1.5.2")]
internal abstract class ScanBase : AbstractScanner<ValueType,LexLocation> {
private LexLocation __yylloc = new LexLocation();
public override LexLocation yylloc { get { return __yylloc; } set { __yylloc = value; } }
protected virtual bool yywrap() { return true; }
}
// Utility class for encapsulating token information
[GeneratedCodeAttribute( "Gardens Point Parser Generator", "1.5.2")]
internal class ScanObj {
public int token;
public ValueType yylval;
public LexLocation yylloc;
public ScanObj( int t, ValueType val, LexLocation loc ) {
this.token = t; this.yylval = val; this.yylloc = loc;
}
}
[GeneratedCodeAttribute( "Gardens Point Parser Generator", "1.5.2")]
internal partial class Parser: ShiftReduceParser<ValueType, LexLocation>
{
#pragma warning disable 649
private static Dictionary<int, string> aliases;
#pragma warning restore 649
private static Rule[] rules = new Rule[84];
private static State[] states = new State[134];
private static string[] nonTerms = new string[] {
"file", "stmtlist", "stmt", "instruction", "directive", "line_label", "cond",
"data_list", "data_directive", "anylabel", "sectionname", "expr", "expr2",
"expr3", "expr4", "expr5", "expr6", "expr7", "expr8", "expr9", "expr10",
"expr11", "operand2", "dest", "$accept", };
static Parser() {
states[0] = new State(new int[]{26,65,27,66,28,67,12,68,13,69,14,70,15,71,16,72,17,74,18,76,19,78,21,80,22,82,23,87,24,91,20,93,25,99,47,112,48,126,8,131,4,132,3,-2},new int[]{-1,1,-2,3,-3,133,-5,5,-9,9,-6,111,-4,128});
states[1] = new State(new int[]{3,2});
states[2] = new State(-1);
states[3] = new State(new int[]{26,65,27,66,28,67,12,68,13,69,14,70,15,71,16,72,17,74,18,76,19,78,21,80,22,82,23,87,24,91,20,93,25,99,47,112,48,126,8,131,4,132,3,-3},new int[]{-3,4,-5,5,-9,9,-6,111,-4,128});
states[4] = new State(-5);
states[5] = new State(new int[]{8,6,4,8});
states[6] = new State(new int[]{4,7});
states[7] = new State(-6);
states[8] = new State(-7);
states[9] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53,8,-48,4,-48},new int[]{-8,10,-12,11,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[10] = new State(-13);
states[11] = new State(new int[]{5,12,8,-49,4,-49});
states[12] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53,8,-48,4,-48},new int[]{-8,13,-12,11,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[13] = new State(-50);
states[14] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-13,15,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[15] = new State(new int[]{11,16});
states[16] = new State(-54);
states[17] = new State(new int[]{30,18,5,-57,8,-57,4,-57,11,-57,7,-57});
states[18] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-13,19,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[19] = new State(-56);
states[20] = new State(new int[]{31,21,30,-59,5,-59,8,-59,4,-59,11,-59,7,-59});
states[21] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-14,22,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[22] = new State(-58);
states[23] = new State(new int[]{32,24,31,-61,30,-61,5,-61,8,-61,4,-61,11,-61,7,-61});
states[24] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-15,25,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[25] = new State(-60);
states[26] = new State(new int[]{33,27,32,-63,31,-63,30,-63,5,-63,8,-63,4,-63,11,-63,7,-63});
states[27] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-16,28,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[28] = new State(-62);
states[29] = new State(new int[]{34,30,35,62,33,-66,32,-66,31,-66,30,-66,5,-66,8,-66,4,-66,11,-66,7,-66});
states[30] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-17,31,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[31] = new State(-64);
states[32] = new State(new int[]{36,33,37,56,38,58,39,60,34,-71,35,-71,33,-71,32,-71,31,-71,30,-71,5,-71,8,-71,4,-71,11,-71,7,-71});
states[33] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-18,34,-19,32,-20,35,-21,38,-22,47,-10,49});
states[34] = new State(-67);
states[35] = new State(new int[]{40,36,41,54,36,-74,37,-74,38,-74,39,-74,34,-74,35,-74,33,-74,32,-74,31,-74,30,-74,5,-74,8,-74,4,-74,11,-74,7,-74});
states[36] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-19,37,-20,35,-21,38,-22,47,-10,49});
states[37] = new State(-72);
states[38] = new State(new int[]{42,39,40,-76,41,-76,36,-76,37,-76,38,-76,39,-76,34,-76,35,-76,33,-76,32,-76,31,-76,30,-76,5,-76,8,-76,4,-76,11,-76,7,-76});
states[39] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-20,40,-21,38,-22,47,-10,49});
states[40] = new State(-75);
states[41] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-21,42,-22,47,-10,49});
states[42] = new State(-77);
states[43] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-21,44,-22,47,-10,49});
states[44] = new State(-78);
states[45] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-21,46,-22,47,-10,49});
states[46] = new State(-79);
states[47] = new State(-80);
states[48] = new State(-81);
states[49] = new State(-82);
states[50] = new State(-51);
states[51] = new State(-52);
states[52] = new State(-53);
states[53] = new State(-83);
states[54] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-19,55,-20,35,-21,38,-22,47,-10,49});
states[55] = new State(-73);
states[56] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-18,57,-19,32,-20,35,-21,38,-22,47,-10,49});
states[57] = new State(-68);
states[58] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-18,59,-19,32,-20,35,-21,38,-22,47,-10,49});
states[59] = new State(-69);
states[60] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-18,61,-19,32,-20,35,-21,38,-22,47,-10,49});
states[61] = new State(-70);
states[62] = new State(new int[]{43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-17,63,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[63] = new State(-65);
states[64] = new State(-55);
states[65] = new State(-45);
states[66] = new State(-46);
states[67] = new State(-47);
states[68] = new State(-14);
states[69] = new State(-15);
states[70] = new State(-16);
states[71] = new State(-17);
states[72] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-12,73,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[73] = new State(-18);
states[74] = new State(new int[]{47,50,48,51,50,52},new int[]{-10,75});
states[75] = new State(-19);
states[76] = new State(new int[]{47,50,48,51,50,52},new int[]{-10,77});
states[77] = new State(-20);
states[78] = new State(new int[]{47,50,48,51,50,52},new int[]{-10,79});
states[79] = new State(-21);
states[80] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-12,81,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[81] = new State(-22);
states[82] = new State(new int[]{47,50,48,51,50,52},new int[]{-10,83});
states[83] = new State(new int[]{5,84});
states[84] = new State(new int[]{29,85});
states[85] = new State(new int[]{47,86});
states[86] = new State(-23);
states[87] = new State(new int[]{47,50,48,51,50,52},new int[]{-10,88});
states[88] = new State(new int[]{5,89});
states[89] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-12,90,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[90] = new State(-24);
states[91] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-12,92,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[92] = new State(-25);
states[93] = new State(new int[]{47,50,48,51,50,52},new int[]{-10,94});
states[94] = new State(new int[]{5,95});
states[95] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-12,96,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[96] = new State(new int[]{5,97,8,-26,4,-26});
states[97] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-12,98,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[98] = new State(-27);
states[99] = new State(new int[]{47,50,48,51,50,52,46,110},new int[]{-11,100,-10,109});
states[100] = new State(new int[]{5,101,8,-28,4,-28});
states[101] = new State(new int[]{46,102});
states[102] = new State(new int[]{5,103,8,-29,4,-29});
states[103] = new State(new int[]{29,104});
states[104] = new State(new int[]{47,105});
states[105] = new State(new int[]{5,106,8,-30,4,-30});
states[106] = new State(new int[]{47,107,45,108});
states[107] = new State(-31);
states[108] = new State(-32);
states[109] = new State(-33);
states[110] = new State(-34);
states[111] = new State(-8);
states[112] = new State(new int[]{6,113,10,122,43,-39,44,-39,41,-39,46,-39,47,-39,48,-39,50,-39,45,-39,8,-39,4,-39},new int[]{-7,114});
states[113] = new State(-35);
states[114] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53,8,-38,4,-38},new int[]{-12,115,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[115] = new State(new int[]{5,120,7,-41,8,-41,4,-41},new int[]{-23,116});
states[116] = new State(new int[]{7,118,8,-43,4,-43},new int[]{-24,117});
states[117] = new State(-37);
states[118] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-12,119,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[119] = new State(-44);
states[120] = new State(new int[]{10,14,43,41,44,43,41,45,46,48,47,50,48,51,50,52,45,53},new int[]{-12,121,-13,64,-14,17,-15,20,-16,23,-17,26,-18,29,-19,32,-20,35,-21,38,-22,47,-10,49});
states[121] = new State(-42);
states[122] = new State(new int[]{49,123});
states[123] = new State(new int[]{50,124});
states[124] = new State(new int[]{11,125});
states[125] = new State(-40);
states[126] = new State(new int[]{6,127});
states[127] = new State(-36);
states[128] = new State(new int[]{8,129,4,130});
states[129] = new State(-9);
states[130] = new State(-10);
states[131] = new State(-11);
states[132] = new State(-12);
states[133] = new State(-4);
for (int sNo = 0; sNo < states.Length; sNo++) states[sNo].number = sNo;
rules[1] = new Rule(-25, new int[]{-1,3});
rules[2] = new Rule(-1, new int[]{});
rules[3] = new Rule(-1, new int[]{-2});
rules[4] = new Rule(-2, new int[]{-3});
rules[5] = new Rule(-2, new int[]{-2,-3});
rules[6] = new Rule(-3, new int[]{-5,8,4});
rules[7] = new Rule(-3, new int[]{-5,4});
rules[8] = new Rule(-3, new int[]{-6});
rules[9] = new Rule(-3, new int[]{-4,8});
rules[10] = new Rule(-3, new int[]{-4,4});
rules[11] = new Rule(-3, new int[]{8});
rules[12] = new Rule(-3, new int[]{4});
rules[13] = new Rule(-5, new int[]{-9,-8});
rules[14] = new Rule(-5, new int[]{12});
rules[15] = new Rule(-5, new int[]{13});
rules[16] = new Rule(-5, new int[]{14});
rules[17] = new Rule(-5, new int[]{15});
rules[18] = new Rule(-5, new int[]{16,-12});
rules[19] = new Rule(-5, new int[]{17,-10});
rules[20] = new Rule(-5, new int[]{18,-10});
rules[21] = new Rule(-5, new int[]{19,-10});
rules[22] = new Rule(-5, new int[]{21,-12});
rules[23] = new Rule(-5, new int[]{22,-10,5,29,47});
rules[24] = new Rule(-5, new int[]{23,-10,5,-12});
rules[25] = new Rule(-5, new int[]{24,-12});
rules[26] = new Rule(-5, new int[]{20,-10,5,-12});
rules[27] = new Rule(-5, new int[]{20,-10,5,-12,5,-12});
rules[28] = new Rule(-5, new int[]{25,-11});
rules[29] = new Rule(-5, new int[]{25,-11,5,46});
rules[30] = new Rule(-5, new int[]{25,-11,5,46,5,29,47});
rules[31] = new Rule(-5, new int[]{25,-11,5,46,5,29,47,5,47});
rules[32] = new Rule(-5, new int[]{25,-11,5,46,5,29,47,5,45});
rules[33] = new Rule(-11, new int[]{-10});
rules[34] = new Rule(-11, new int[]{46});
rules[35] = new Rule(-6, new int[]{47,6});
rules[36] = new Rule(-6, new int[]{48,6});
rules[37] = new Rule(-4, new int[]{47,-7,-12,-23,-24});
rules[38] = new Rule(-4, new int[]{47,-7});
rules[39] = new Rule(-7, new int[]{});
rules[40] = new Rule(-7, new int[]{10,49,50,11});
rules[41] = new Rule(-23, new int[]{});
rules[42] = new Rule(-23, new int[]{5,-12});
rules[43] = new Rule(-24, new int[]{});
rules[44] = new Rule(-24, new int[]{7,-12});
rules[45] = new Rule(-9, new int[]{26});
rules[46] = new Rule(-9, new int[]{27});
rules[47] = new Rule(-9, new int[]{28});
rules[48] = new Rule(-8, new int[]{});
rules[49] = new Rule(-8, new int[]{-12});
rules[50] = new Rule(-8, new int[]{-12,5,-8});
rules[51] = new Rule(-10, new int[]{47});
rules[52] = new Rule(-10, new int[]{48});
rules[53] = new Rule(-10, new int[]{50});
rules[54] = new Rule(-12, new int[]{10,-13,11});
rules[55] = new Rule(-12, new int[]{-13});
rules[56] = new Rule(-13, new int[]{-14,30,-13});
rules[57] = new Rule(-13, new int[]{-14});
rules[58] = new Rule(-14, new int[]{-15,31,-14});
rules[59] = new Rule(-14, new int[]{-15});
rules[60] = new Rule(-15, new int[]{-16,32,-15});
rules[61] = new Rule(-15, new int[]{-16});
rules[62] = new Rule(-16, new int[]{-17,33,-16});
rules[63] = new Rule(-16, new int[]{-17});
rules[64] = new Rule(-17, new int[]{-18,34,-17});
rules[65] = new Rule(-17, new int[]{-18,35,-17});
rules[66] = new Rule(-17, new int[]{-18});
rules[67] = new Rule(-18, new int[]{-19,36,-18});
rules[68] = new Rule(-18, new int[]{-19,37,-18});
rules[69] = new Rule(-18, new int[]{-19,38,-18});
rules[70] = new Rule(-18, new int[]{-19,39,-18});
rules[71] = new Rule(-18, new int[]{-19});
rules[72] = new Rule(-19, new int[]{-20,40,-19});
rules[73] = new Rule(-19, new int[]{-20,41,-19});
rules[74] = new Rule(-19, new int[]{-20});
rules[75] = new Rule(-20, new int[]{-21,42,-20});
rules[76] = new Rule(-20, new int[]{-21});
rules[77] = new Rule(-21, new int[]{43,-21});
rules[78] = new Rule(-21, new int[]{44,-21});
rules[79] = new Rule(-21, new int[]{41,-21});
rules[80] = new Rule(-21, new int[]{-22});
rules[81] = new Rule(-22, new int[]{46});
rules[82] = new Rule(-22, new int[]{-10});
rules[83] = new Rule(-22, new int[]{45});
}
protected override void Initialize() {
this.InitSpecialTokens((int)Tokens.error, (int)Tokens.EOF);
this.InitStates(states);
this.InitRules(rules);
this.InitNonTerminals(nonTerms);
}
protected override void DoAction(int action)
{
#pragma warning disable 162, 1522
switch (action)
{
case 2: // file -> /* empty */
#line 36 "jcasm.y"
{ output = new StatementList(); }
#line default
break;
case 3: // file -> stmtlist
#line 37 "jcasm.y"
{ output = ValueStack[ValueStack.Depth-1].stmtval; }
#line default
break;
case 4: // stmtlist -> stmt
#line 40 "jcasm.y"
{ StatementList sl = new StatementList(); sl.list = new List<Statement>(); sl.list.Add(ValueStack[ValueStack.Depth-1].stmtval); CurrentSemanticValue.stmtval = sl; }
#line default
break;
case 5: // stmtlist -> stmtlist, stmt
#line 41 "jcasm.y"
{ ((StatementList)ValueStack[ValueStack.Depth-2].stmtval).list.Add(ValueStack[ValueStack.Depth-1].stmtval); CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-2].stmtval; }
#line default
break;
case 6: // stmt -> directive, SEMICOLON, NEWLINE
#line 44 "jcasm.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-3].stmtval; }
#line default
break;
case 7: // stmt -> directive, NEWLINE
#line 45 "jcasm.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-2].stmtval; }
#line default
break;
case 8: // stmt -> line_label
#line 46 "jcasm.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-1].stmtval; }
#line default
break;
case 9: // stmt -> instruction, SEMICOLON
#line 47 "jcasm.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-2].stmtval; }
#line default
break;
case 10: // stmt -> instruction, NEWLINE
#line 48 "jcasm.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-2].stmtval; }
#line default
break;
case 13: // directive -> data_directive, data_list
#line 53 "jcasm.y"
{ CurrentSemanticValue.stmtval = new DataDirective { directive = ValueStack[ValueStack.Depth-2].ddtype, data = ValueStack[ValueStack.Depth-1].dilist }; }
#line default
break;
case 14: // directive -> TEXT
#line 54 "jcasm.y"
{ CurrentSemanticValue.stmtval = new SectionHeader { name = ".text" }; }
#line default
break;
case 15: // directive -> DATA
#line 55 "jcasm.y"
{ CurrentSemanticValue.stmtval = new SectionHeader { name = ".data" }; }
#line default
break;
case 16: // directive -> RODATA
#line 56 "jcasm.y"
{ CurrentSemanticValue.stmtval = new SectionHeader { name = ".rodata" }; }
#line default
break;
case 17: // directive -> BSS
#line 57 "jcasm.y"
{ CurrentSemanticValue.stmtval = new SectionHeader { name = ".bss" }; }
#line default
break;
case 18: // directive -> FILE, expr
#line 58 "jcasm.y"
{ CurrentSemanticValue.stmtval = null; }
#line default
break;
case 19: // directive -> GLOBL, anylabel
#line 59 "jcasm.y"
{ CurrentSemanticValue.stmtval = null; Program.global_objs[ValueStack[ValueStack.Depth-1].strval] = null; }
#line default
break;
case 20: // directive -> LOCAL, anylabel
#line 60 "jcasm.y"
{ CurrentSemanticValue.stmtval = null; }
#line default
break;
case 21: // directive -> EXTERN, anylabel
#line 61 "jcasm.y"
{ CurrentSemanticValue.stmtval = null; Program.extern_objs.Add(ValueStack[ValueStack.Depth-1].strval); }
#line default
break;
case 22: // directive -> ALIGN, expr
#line 62 "jcasm.y"
{ CurrentSemanticValue.stmtval = null; }
#line default
break;
case 23: // directive -> TYPE, anylabel, COMMA, AT, LABEL
#line 63 "jcasm.y"
{ CurrentSemanticValue.stmtval = null; Program.obj_types[ValueStack[ValueStack.Depth-4].strval] = ValueStack[ValueStack.Depth-1].strval; }
#line default
break;
case 24: // directive -> SIZE, anylabel, COMMA, expr
#line 64 "jcasm.y"
{ CurrentSemanticValue.stmtval = null; Program.obj_sizes[ValueStack[ValueStack.Depth-3].strval] = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 25: // directive -> IDENT, expr
#line 65 "jcasm.y"
{ CurrentSemanticValue.stmtval = null; }
#line default
break;
case 26: // directive -> COMM, anylabel, COMMA, expr
#line 66 "jcasm.y"
{ CurrentSemanticValue.stmtval = null; Program.comm_objs[ValueStack[ValueStack.Depth-3].strval] = new CommonSymbol { Size = ValueStack[ValueStack.Depth-1].exprval, Align = null }; }
#line default
break;
case 27: // directive -> COMM, anylabel, COMMA, expr, COMMA, expr
#line 67 "jcasm.y"
{ CurrentSemanticValue.stmtval = null; Program.comm_objs[ValueStack[ValueStack.Depth-5].strval] = new CommonSymbol { Size = ValueStack[ValueStack.Depth-3].exprval, Align = ValueStack[ValueStack.Depth-1].exprval }; }
#line default
break;
case 28: // directive -> SECTION, sectionname
#line 68 "jcasm.y"
{ CurrentSemanticValue.stmtval = new SectionHeader { name = ValueStack[ValueStack.Depth-1].strval }; Program.RegisterSection(ValueStack[ValueStack.Depth-1].strval, null, null, null); }
#line default
break;
case 29: // directive -> SECTION, sectionname, COMMA, STRING
#line 69 "jcasm.y"
{ CurrentSemanticValue.stmtval = new SectionHeader { name = ValueStack[ValueStack.Depth-3].strval }; Program.RegisterSection(ValueStack[ValueStack.Depth-3].strval, ValueStack[ValueStack.Depth-1].strval, null, null); }
#line default
break;
case 30: // directive -> SECTION, sectionname, COMMA, STRING, COMMA, AT, LABEL
#line 70 "jcasm.y"
{ CurrentSemanticValue.stmtval = new SectionHeader { name = ValueStack[ValueStack.Depth-6].strval }; Program.RegisterSection(ValueStack[ValueStack.Depth-6].strval, ValueStack[ValueStack.Depth-4].strval, ValueStack[ValueStack.Depth-1].strval, null); }
#line default
break;
case 31: // directive -> SECTION, sectionname, COMMA, STRING, COMMA, AT, LABEL, COMMA,
// LABEL
#line 71 "jcasm.y"
{ CurrentSemanticValue.stmtval = new SectionHeader { name = ValueStack[ValueStack.Depth-8].strval }; Program.RegisterSection(ValueStack[ValueStack.Depth-8].strval, ValueStack[ValueStack.Depth-6].strval, ValueStack[ValueStack.Depth-3].strval, ValueStack[ValueStack.Depth-1].strval); }
#line default
break;
case 32: // directive -> SECTION, sectionname, COMMA, STRING, COMMA, AT, LABEL, COMMA, INT
#line 72 "jcasm.y"
{ CurrentSemanticValue.stmtval = new SectionHeader { name = ValueStack[ValueStack.Depth-8].strval }; Program.RegisterSection(ValueStack[ValueStack.Depth-8].strval, ValueStack[ValueStack.Depth-6].strval, ValueStack[ValueStack.Depth-3].strval, ValueStack[ValueStack.Depth-1].intval.ToString()); }
#line default
break;
case 33: // sectionname -> anylabel
#line 75 "jcasm.y"
{ CurrentSemanticValue.strval = ValueStack[ValueStack.Depth-1].strval; }
#line default
break;
case 34: // sectionname -> STRING
#line 76 "jcasm.y"
{ CurrentSemanticValue.strval = ValueStack[ValueStack.Depth-1].strval; }
#line default
break;
case 35: // line_label -> LABEL, COLON
#line 79 "jcasm.y"
{ CurrentSemanticValue.stmtval = new LineLabel { name = ValueStack[ValueStack.Depth-2].strval }; Program.cur_label = ValueStack[ValueStack.Depth-2].strval; }
#line default
break;
case 36: // line_label -> LOCLABEL, COLON
#line 80 "jcasm.y"
{ CurrentSemanticValue.stmtval = new LineLabel { name = ValueStack[ValueStack.Depth-2].strval }; }
#line default
break;
case 37: // instruction -> LABEL, cond, expr, operand2, dest
#line 83 "jcasm.y"
{ CurrentSemanticValue.stmtval = new Instruction { op = ValueStack[ValueStack.Depth-5].strval, cond = ValueStack[ValueStack.Depth-4].condval, srca = ValueStack[ValueStack.Depth-3].exprval, srcb = ValueStack[ValueStack.Depth-2].exprval, dest = ValueStack[ValueStack.Depth-1].exprval }; }
#line default
break;
case 38: // instruction -> LABEL, cond
#line 84 "jcasm.y"
{ CurrentSemanticValue.stmtval = new Instruction { op = ValueStack[ValueStack.Depth-2].strval, cond = ValueStack[ValueStack.Depth-1].condval, srca = null, srcb = null, dest = null }; }
#line default
break;
case 39: // cond -> /* empty */
#line 87 "jcasm.y"
{ CurrentSemanticValue.condval = new Condition { ctype = Condition.CType.Always}; }
#line default
break;
case 40: // cond -> LPAREN, CC, REG, RPAREN
#line 88 "jcasm.y"
{ CurrentSemanticValue.condval = new Condition(ValueStack[ValueStack.Depth-3].strval, ValueStack[ValueStack.Depth-2].strval); }
#line default
break;
case 41: // operand2 -> /* empty */
#line 91 "jcasm.y"
{ CurrentSemanticValue.exprval = null; }
#line default
break;
case 42: // operand2 -> COMMA, expr
#line 92 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 43: // dest -> /* empty */
#line 95 "jcasm.y"
{ CurrentSemanticValue.exprval = null; }
#line default
break;
case 44: // dest -> ASSIGN, expr
#line 96 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 45: // data_directive -> DB
#line 99 "jcasm.y"
{ CurrentSemanticValue.ddtype = DataDirective.DDType.Byte; }
#line default
break;
case 46: // data_directive -> DW
#line 100 "jcasm.y"
{ CurrentSemanticValue.ddtype = DataDirective.DDType.Word; }
#line default
break;
case 47: // data_directive -> DD
#line 101 "jcasm.y"
{ CurrentSemanticValue.ddtype = DataDirective.DDType.DWord; }
#line default
break;
case 48: // data_list -> /* empty */
#line 104 "jcasm.y"
{ CurrentSemanticValue.dilist = new List<Expression>(); }
#line default
break;
case 49: // data_list -> expr
#line 105 "jcasm.y"
{ CurrentSemanticValue.dilist = new List<Expression> { ValueStack[ValueStack.Depth-1].exprval }; }
#line default
break;
case 50: // data_list -> expr, COMMA, data_list
#line 106 "jcasm.y"
{ CurrentSemanticValue.dilist = new List<Expression>(); CurrentSemanticValue.dilist.Add(ValueStack[ValueStack.Depth-3].exprval); CurrentSemanticValue.dilist.AddRange(ValueStack[ValueStack.Depth-1].dilist); }
#line default
break;
case 51: // anylabel -> LABEL
#line 109 "jcasm.y"
{ CurrentSemanticValue.strval = ValueStack[ValueStack.Depth-1].strval; }
#line default
break;
case 52: // anylabel -> LOCLABEL
#line 110 "jcasm.y"
{ CurrentSemanticValue.strval = ValueStack[ValueStack.Depth-1].strval; }
#line default
break;
case 53: // anylabel -> REG
#line 111 "jcasm.y"
{ CurrentSemanticValue.strval = ValueStack[ValueStack.Depth-1].strval; }
#line default
break;
case 54: // expr -> LPAREN, expr2, RPAREN
#line 114 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-2].exprval; }
#line default
break;
case 55: // expr -> expr2
#line 115 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 56: // expr2 -> expr3, LOR, expr2
#line 118 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.LOR }; }
#line default
break;
case 57: // expr2 -> expr3
#line 119 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 58: // expr3 -> expr4, LAND, expr3
#line 122 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.LAND }; }
#line default
break;
case 59: // expr3 -> expr4
#line 123 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 60: // expr4 -> expr5, OR, expr4
#line 126 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.OR }; }
#line default
break;
case 61: // expr4 -> expr5
#line 127 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 62: // expr5 -> expr6, AND, expr5
#line 130 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.AND }; }
#line default
break;
case 63: // expr5 -> expr6
#line 131 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 64: // expr6 -> expr7, EQUALS, expr6
#line 134 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.EQUALS }; }
#line default
break;
case 65: // expr6 -> expr7, NOTEQUAL, expr6
#line 135 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.NOTEQUAL }; }
#line default
break;
case 66: // expr6 -> expr7
#line 136 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 67: // expr7 -> expr8, LT, expr7
#line 139 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.LT }; }
#line default
break;
case 68: // expr7 -> expr8, GT, expr7
#line 140 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.GT }; }
#line default
break;
case 69: // expr7 -> expr8, LEQUAL, expr7
#line 141 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.LEQUAL }; }
#line default
break;
case 70: // expr7 -> expr8, GEQUAL, expr7
#line 142 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.GEQUAL }; }
#line default
break;
case 71: // expr7 -> expr8
#line 143 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 72: // expr8 -> expr9, PLUS, expr8
#line 146 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.PLUS }; }
#line default
break;
case 73: // expr8 -> expr9, MINUS, expr8
#line 147 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.MINUS }; }
#line default
break;
case 74: // expr8 -> expr9
#line 148 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 75: // expr9 -> expr10, MUL, expr9
#line 151 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.MUL }; }
#line default
break;
case 76: // expr9 -> expr10
#line 152 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 77: // expr10 -> NOT, expr10
#line 155 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-1].exprval, b = null, op = Tokens.NOT }; }
#line default
break;
case 78: // expr10 -> LNOT, expr10
#line 156 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-1].exprval, b = null, op = Tokens.LNOT }; }
#line default
break;
case 79: // expr10 -> MINUS, expr10
#line 157 "jcasm.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-1].exprval, b = null, op = Tokens.MINUS }; }
#line default
break;
case 80: // expr10 -> expr11
#line 158 "jcasm.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 81: // expr11 -> STRING
#line 161 "jcasm.y"
{ CurrentSemanticValue.exprval = new StringExpression { val = ValueStack[ValueStack.Depth-1].strval }; }
#line default
break;
case 82: // expr11 -> anylabel
#line 162 "jcasm.y"
{ CurrentSemanticValue.exprval = new LabelExpression { val = ValueStack[ValueStack.Depth-1].strval, cur_outer_label = Program.cur_label }; }
#line default
break;
case 83: // expr11 -> INT
#line 163 "jcasm.y"
{ CurrentSemanticValue.exprval = new IntExpression { val = ValueStack[ValueStack.Depth-1].intval }; }
#line default
break;
}
#pragma warning restore 162, 1522
}
protected override string TerminalToString(int terminal)
{
if (aliases != null && aliases.ContainsKey(terminal))
return aliases[terminal];
else if (((Tokens)terminal).ToString() != terminal.ToString(CultureInfo.InvariantCulture))
return ((Tokens)terminal).ToString();
else
return CharToString((char)terminal);
}
#line 168 "jcasm.y"
internal Statement output;
#line default
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record.Aggregates
{
using System;
using System.Text;
using System.Collections;
using NPOI.DDF;
using NPOI.Util;
using NPOI.HSSF.Record;
using NPOI.SS.Formula;
using NPOI.HSSF.Model;
using NPOI.SS.Formula.PTG;
/**
*
* Aggregate value records toGether. Things are easier to handle that way.
*
* @author andy
* @author Glen Stampoultzis (glens at apache.org)
* @author Jason Height (jheight at chariot dot net dot au)
*/
internal class ValueRecordsAggregate
{
const int MAX_ROW_INDEX = 0XFFFF;
const int INDEX_NOT_SET = -1;
public const short sid = -1001; // 1000 clashes with RowRecordsAggregate
int firstcell = INDEX_NOT_SET;
int lastcell = INDEX_NOT_SET;
CellValueRecordInterface[][] records;
/** Creates a new instance of ValueRecordsAggregate */
public ValueRecordsAggregate():
this(INDEX_NOT_SET, INDEX_NOT_SET, new CellValueRecordInterface[30][]) // We start with 30 Rows.
{
}
private ValueRecordsAggregate(int firstCellIx, int lastCellIx, CellValueRecordInterface[][] pRecords)
{
firstcell = firstCellIx;
lastcell = lastCellIx;
records = pRecords;
}
public void InsertCell(CellValueRecordInterface cell)
{
int column = cell.Column;
int row = cell.Row;
if (row >= records.Length)
{
CellValueRecordInterface[][] oldRecords = records;
int newSize = oldRecords.Length * 2;
if (newSize < row + 1) newSize = row + 1;
records = new CellValueRecordInterface[newSize][];
Array.Copy(oldRecords, 0, records, 0, oldRecords.Length);
}
object objRowCells = records[row];
if (objRowCells == null)
{
int newSize = column + 1;
if (newSize < 10) newSize = 10;
objRowCells = new CellValueRecordInterface[newSize];
records[row] = (CellValueRecordInterface[])objRowCells;
}
CellValueRecordInterface[] rowCells = (CellValueRecordInterface[])objRowCells;
if (column >= rowCells.Length)
{
CellValueRecordInterface[] oldRowCells = rowCells;
int newSize = oldRowCells.Length * 2;
if (newSize < column + 1) newSize = column + 1;
// if(newSize>257) newSize=257; // activate?
rowCells = new CellValueRecordInterface[newSize];
Array.Copy(oldRowCells, 0, rowCells, 0, oldRowCells.Length);
records[row] = rowCells;
}
rowCells[column] = cell;
if ((column < firstcell) || (firstcell == -1))
{
firstcell = column;
}
if ((column > lastcell) || (lastcell == -1))
{
lastcell = column;
}
}
public void RemoveCell(CellValueRecordInterface cell)
{
if (cell == null)
{
throw new ArgumentException("cell must not be null");
}
int row = cell.Row;
if (row >= records.Length)
{
throw new Exception("cell row is out of range");
}
CellValueRecordInterface[] rowCells = records[row];
if (rowCells == null)
{
throw new Exception("cell row is already empty");
}
int column = cell.Column;
if (column >= rowCells.Length)
{
throw new Exception("cell column is out of range");
}
rowCells[column] = null;
}
public void RemoveAllCellsValuesForRow(int rowIndex)
{
if (rowIndex < 0 || rowIndex > MAX_ROW_INDEX)
{
throw new ArgumentException("Specified rowIndex " + rowIndex
+ " is outside the allowable range (0.." + MAX_ROW_INDEX + ")");
}
if (rowIndex >= records.Length)
{
// this can happen when the client code has created a row,
// and then removes/replaces it before adding any cells. (see bug 46312)
return;
}
records[rowIndex] = null;
}
public CellValueRecordInterface[] GetValueRecords()
{
ArrayList temp = new ArrayList();
for (int i = 0; i < records.Length; i++)
{
CellValueRecordInterface[] rowCells = records[i];
if (rowCells == null)
{
continue;
}
for (int j = 0; j < rowCells.Length; j++)
{
CellValueRecordInterface cell = rowCells[j];
if (cell != null)
{
temp.Add(cell);
}
}
}
return (CellValueRecordInterface[])temp.ToArray(typeof(CellValueRecordInterface));
}
public int PhysicalNumberOfCells
{
get
{
int count = 0;
for (int r = 0; r < records.Length; r++)
{
CellValueRecordInterface[] rowCells = records[r];
if (rowCells != null)
for (short c = 0; c < rowCells.Length; c++)
{
if (rowCells[c] != null) count++;
}
}
return count;
}
}
public int FirstCellNum
{
get
{
return firstcell;
}
}
public int LastCellNum
{
get
{
return lastcell;
}
}
public void AddMultipleBlanks(MulBlankRecord mbr)
{
for (int j = 0; j < mbr.NumColumns; j++)
{
BlankRecord br = new BlankRecord();
br.Column = j + mbr.FirstColumn;
br.Row = mbr.Row;
br.XFIndex = (mbr.GetXFAt(j));
InsertCell(br);
}
}
private MulBlankRecord CreateMBR(CellValueRecordInterface[] cellValues, int startIx, int nBlank)
{
short[] xfs = new short[nBlank];
for (int i = 0; i < xfs.Length; i++)
{
xfs[i] = ((BlankRecord)cellValues[startIx + i]).XFIndex;
}
int rowIx = cellValues[startIx].Row;
return new MulBlankRecord(rowIx, startIx, xfs);
}
public void Construct(CellValueRecordInterface rec, RecordStream rs, SharedValueManager sfh)
{
if (rec is FormulaRecord)
{
FormulaRecord formulaRec = (FormulaRecord)rec;
// read optional cached text value
StringRecord cachedText=null;
Type nextClass = rs.PeekNextClass();
if (nextClass == typeof(StringRecord))
{
cachedText = (StringRecord)rs.GetNext();
}
else
{
cachedText = null;
}
InsertCell(new FormulaRecordAggregate(formulaRec, cachedText, sfh));
}
else
{
InsertCell(rec);
}
}
/**
* Sometimes the shared formula flag "seems" to be erroneously Set, in which case there is no
* call to <c>SharedFormulaRecord.ConvertSharedFormulaRecord</c> and hence the
* <c>ParsedExpression</c> field of this <c>FormulaRecord</c> will not Get updated.<br/>
* As it turns out, this is not a problem, because in these circumstances, the existing value
* for <c>ParsedExpression</c> is perfectly OK.<p/>
*
* This method may also be used for Setting breakpoints to help diagnose Issues regarding the
* abnormally-Set 'shared formula' flags.
* (see TestValueRecordsAggregate.testSpuriousSharedFormulaFlag()).<p/>
*
* The method currently does nothing but do not delete it without Finding a nice home for this
* comment.
*/
static void HandleMissingSharedFormulaRecord(FormulaRecord formula)
{
// could log an info message here since this is a fairly Unusual occurrence.
}
/** Tallies a count of the size of the cell records
* that are attached to the rows in the range specified.
*/
public int GetRowCellBlockSize(int startRow, int endRow)
{
MyEnumerator itr = new MyEnumerator(ref records,startRow, endRow);
int size = 0;
while (itr.MoveNext())
{
CellValueRecordInterface cell = (CellValueRecordInterface)itr.Current;
int row = cell.Row;
if (row > endRow)
break;
if ((row >= startRow) && (row <= endRow))
size += ((RecordBase)cell).RecordSize;
}
return size;
}
/** Returns true if the row has cells attached to it */
public bool RowHasCells(int row)
{
if (row > records.Length - 1) //previously this said row > records.Length which means if
return false; // if records.Length == 60 and I pass "60" here I Get array out of bounds
CellValueRecordInterface[] rowCells = records[row]; //because a 60 Length array has the last index = 59
if (rowCells == null) return false;
for (int col = 0; col < rowCells.Length; col++)
{
if (rowCells[col] != null) return true;
}
return false;
}
public void UpdateFormulasAfterRowShift(FormulaShifter shifter, int currentExternSheetIndex)
{
for (int i = 0; i < records.Length; i++)
{
CellValueRecordInterface[] rowCells = records[i];
if (rowCells == null)
{
continue;
}
for (int j = 0; j < rowCells.Length; j++)
{
CellValueRecordInterface cell = rowCells[j];
if (cell is FormulaRecordAggregate)
{
FormulaRecord fr = ((FormulaRecordAggregate)cell).FormulaRecord;
Ptg[] ptgs = fr.ParsedExpression; // needs clone() inside this getter?
if (shifter.AdjustFormula(ptgs, currentExternSheetIndex))
{
fr.ParsedExpression = (ptgs);
}
}
}
}
}
public void VisitCellsForRow(int rowIndex, RecordVisitor rv)
{
CellValueRecordInterface[] rowCells = records[rowIndex];
if (rowCells == null)
{
throw new ArgumentException("Row [" + rowIndex + "] is empty");
}
for (int i = 0; i < rowCells.Length; i++)
{
RecordBase cvr = (RecordBase)rowCells[i];
if (cvr == null)
{
continue;
}
int nBlank = CountBlanks(rowCells, i);
if (nBlank > 1)
{
rv.VisitRecord(CreateMBR(rowCells, i, nBlank));
i += nBlank - 1;
}
else if (cvr is RecordAggregate)
{
RecordAggregate agg = (RecordAggregate)cvr;
agg.VisitContainedRecords(rv);
}
else
{
rv.VisitRecord((Record)cvr);
}
}
}
static int CountBlanks(CellValueRecordInterface[] rowCellValues, int startIx)
{
int i = startIx;
while (i < rowCellValues.Length)
{
CellValueRecordInterface cvr = rowCellValues[i];
if (!(cvr is BlankRecord))
{
break;
}
i++;
}
return i - startIx;
}
/** Serializes the cells that are allocated to a certain row range*/
public int SerializeCellRow(int row, int offset, byte[] data)
{
MyEnumerator itr = new MyEnumerator(ref records,row, row);
int pos = offset;
while (itr.MoveNext())
{
CellValueRecordInterface cell = (CellValueRecordInterface)itr.Current;
if (cell.Row != row)
break;
pos += ((RecordBase)cell).Serialize(pos, data);
}
return pos - offset;
}
public IEnumerator GetEnumerator()
{
return new MyEnumerator(ref records);
}
private class MyEnumerator : IEnumerator
{
short nextColumn = -1;
int nextRow, lastRow;
CellValueRecordInterface[][] records;
public MyEnumerator(ref CellValueRecordInterface[][] _records)
{
this.records = _records;
this.nextRow = 0;
this.lastRow = _records.Length - 1;
//FindNext();
}
public MyEnumerator(ref CellValueRecordInterface[][] _records,int firstRow, int lastRow)
{
this.records = _records;
this.nextRow = firstRow;
this.lastRow = lastRow;
//FindNext();
}
public bool MoveNext()
{
FindNext();
return nextRow <= lastRow; ;
}
public Object Current
{
get
{
Object o = this.records[nextRow][nextColumn];
return o;
}
}
public void Remove()
{
throw new InvalidOperationException("gibt's noch nicht");
}
private void FindNext()
{
nextColumn++;
for (; nextRow <= lastRow; nextRow++)
{
//previously this threw array out of bounds...
CellValueRecordInterface[] rowCells = (nextRow < records.Length) ? records[nextRow] : null;
if (rowCells == null)
{ // This row is empty
nextColumn = 0;
continue;
}
for (; nextColumn < rowCells.Length; nextColumn++)
{
if (rowCells[nextColumn] != null) return;
}
nextColumn = 0;
}
}
public void Reset()
{
nextColumn = -1;
nextRow = 0;
}
}
}
}
| |
namespace XLabs.Platform.Services.Geolocation
{
using System;
using System.Threading;
using System.Threading.Tasks;
using CoreLocation;
using Foundation;
using ObjCRuntime;
using UIKit;
using XLabs.Platform.Services.GeoLocation;
[assembly: Xamarin.Forms.Dependency(typeof(Geolocator))]
/// <summary>
/// Class Geolocator.
/// </summary>
public class Geolocator : IGeolocator
{
/// <summary>
/// The _position
/// </summary>
private Position _position;
/// <summary>
/// The _manager
/// </summary>
private readonly CLLocationManager _manager;
/// <summary>
/// Initializes a new instance of the <see cref="Geolocator"/> class.
/// </summary>
public Geolocator()
{
_manager = GetManager();
_manager.AuthorizationChanged += OnAuthorizationChanged;
_manager.Failed += OnFailed;
#if (IOS_8)
if (_manager.RespondsToSelector(new Selector("requestWhenInUseAuthorization")))
{
_manager.RequestWhenInUseAuthorization();
}
#endif
if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
{
_manager.LocationsUpdated += OnLocationsUpdated;
}
else
{
_manager.UpdatedLocation += OnUpdatedLocation;
}
_manager.UpdatedHeading += OnUpdatedHeading;
}
/// <summary>
/// Gets or sets the desired accuracy.
/// </summary>
/// <value>The desired accuracy.</value>
public double DesiredAccuracy { get; set; }
/// <summary>
/// Gets a value indicating whether this instance is listening.
/// </summary>
/// <value><c>true</c> if this instance is listening; otherwise, <c>false</c>.</value>
public bool IsListening { get; private set; }
/// <summary>
/// Gets a value indicating whether [supports heading].
/// </summary>
/// <value><c>true</c> if [supports heading]; otherwise, <c>false</c>.</value>
public bool SupportsHeading
{
get
{
return CLLocationManager.HeadingAvailable;
}
}
/// <summary>
/// Gets a value indicating whether this instance is geolocation available.
/// </summary>
/// <value><c>true</c> if this instance is geolocation available; otherwise, <c>false</c>.</value>
public bool IsGeolocationAvailable
{
get
{
return true;
} // all iOS devices support at least wifi geolocation
}
/// <summary>
/// Gets a value indicating whether this instance is geolocation enabled.
/// </summary>
/// <value><c>true</c> if this instance is geolocation enabled; otherwise, <c>false</c>.</value>
public bool IsGeolocationEnabled
{
get
{
#if (IOS_8)
return CLLocationManager.Status >= CLAuthorizationStatus.AuthorizedAlways;
#else
return CLLocationManager.Status >= CLAuthorizationStatus.Authorized;
#endif
}
}
/// <summary>
/// Stop listening to location changes
/// </summary>
public void StopListening()
{
if (!IsListening)
{
return;
}
IsListening = false;
if (CLLocationManager.HeadingAvailable)
{
_manager.StopUpdatingHeading();
}
_manager.StopUpdatingLocation();
_position = null;
}
/// <summary>
/// Occurs when [position error].
/// </summary>
public event EventHandler<PositionErrorEventArgs> PositionError;
/// <summary>
/// Occurs when [position changed].
/// </summary>
public event EventHandler<PositionEventArgs> PositionChanged;
/// <summary>
/// Gets the position asynchronous.
/// </summary>
/// <param name="timeout">The timeout.</param>
/// <returns>Task<Position>.</returns>
public Task<Position> GetPositionAsync(int timeout)
{
return GetPositionAsync(timeout, CancellationToken.None, false);
}
/// <summary>
/// Gets the position asynchronous.
/// </summary>
/// <param name="timeout">The timeout.</param>
/// <param name="includeHeading">if set to <c>true</c> [include heading].</param>
/// <returns>Task<Position>.</returns>
public Task<Position> GetPositionAsync(int timeout, bool includeHeading)
{
return GetPositionAsync(timeout, CancellationToken.None, includeHeading);
}
/// <summary>
/// Gets the position asynchronous.
/// </summary>
/// <param name="cancelToken">The cancel token.</param>
/// <returns>Task<Position>.</returns>
public Task<Position> GetPositionAsync(CancellationToken cancelToken)
{
return GetPositionAsync(Timeout.Infinite, cancelToken, false);
}
/// <summary>
/// Gets the position asynchronous.
/// </summary>
/// <param name="cancelToken">The cancel token.</param>
/// <param name="includeHeading">if set to <c>true</c> [include heading].</param>
/// <returns>Task<Position>.</returns>
public Task<Position> GetPositionAsync(CancellationToken cancelToken, bool includeHeading)
{
return GetPositionAsync(Timeout.Infinite, cancelToken, includeHeading);
}
/// <summary>
/// Gets the position asynchronous.
/// </summary>
/// <param name="timeout">The timeout.</param>
/// <param name="cancelToken">The cancel token.</param>
/// <returns>Task<Position>.</returns>
public Task<Position> GetPositionAsync(int timeout, CancellationToken cancelToken)
{
return GetPositionAsync(timeout, cancelToken, false);
}
/// <summary>
/// Gets the position asynchronous.
/// </summary>
/// <param name="timeout">The timeout.</param>
/// <param name="cancelToken">The cancel token.</param>
/// <param name="includeHeading">if set to <c>true</c> [include heading].</param>
/// <returns>Task<Position>.</returns>
/// <exception cref="ArgumentOutOfRangeException">timeout;Timeout must be positive or Timeout.Infinite</exception>
public Task<Position> GetPositionAsync(int timeout, CancellationToken cancelToken, bool includeHeading)
{
if (timeout <= 0 && timeout != Timeout.Infinite)
{
throw new ArgumentOutOfRangeException("timeout", "Timeout must be positive or Timeout.Infinite");
}
TaskCompletionSource<Position> tcs;
if (!IsListening)
{
var m = GetManager();
tcs = new TaskCompletionSource<Position>(m);
var singleListener = new GeolocationSingleUpdateDelegate(m, DesiredAccuracy, includeHeading, timeout, cancelToken);
m.Delegate = singleListener;
m.StartUpdatingLocation();
if (includeHeading && SupportsHeading)
{
m.StartUpdatingHeading();
}
return singleListener.Task;
}
tcs = new TaskCompletionSource<Position>();
if (_position == null)
{
EventHandler<PositionErrorEventArgs> gotError = null;
gotError = (s, e) =>
{
tcs.TrySetException(new GeolocationException(e.Error));
PositionError -= gotError;
};
PositionError += gotError;
EventHandler<PositionEventArgs> gotPosition = null;
gotPosition = (s, e) =>
{
tcs.TrySetResult(e.Position);
PositionChanged -= gotPosition;
};
PositionChanged += gotPosition;
}
else
{
tcs.SetResult(_position);
}
return tcs.Task;
}
/// <summary>
/// Start listening to location changes
/// </summary>
/// <param name="minTime">Minimum interval in milliseconds</param>
/// <param name="minDistance">Minimum distance in meters</param>
public void StartListening(uint minTime, double minDistance)
{
StartListening(minTime, minDistance, false);
}
/// <summary>
/// Start listening to location changes
/// </summary>
/// <param name="minTime">Minimum interval in milliseconds</param>
/// <param name="minDistance">Minimum distance in meters</param>
/// <param name="includeHeading">Include heading information</param>
/// <exception cref="ArgumentOutOfRangeException">
/// minTime
/// or
/// minDistance
/// </exception>
/// <exception cref="InvalidOperationException">Already listening</exception>
public void StartListening(uint minTime, double minDistance, bool includeHeading)
{
if (minTime < 0)
{
throw new ArgumentOutOfRangeException("minTime");
}
if (minDistance < 0)
{
throw new ArgumentOutOfRangeException("minDistance");
}
if (IsListening)
{
throw new InvalidOperationException("Already listening");
}
IsListening = true;
_manager.DesiredAccuracy = DesiredAccuracy;
_manager.DistanceFilter = minDistance;
_manager.StartUpdatingLocation();
if (includeHeading && CLLocationManager.HeadingAvailable)
{
_manager.StartUpdatingHeading();
}
}
/// <summary>
/// Gets the manager.
/// </summary>
/// <returns>CLLocationManager.</returns>
private CLLocationManager GetManager()
{
CLLocationManager m = null;
new NSObject().InvokeOnMainThread(() => m = new CLLocationManager());
return m;
}
/// <summary>
/// Handles the <see cref="E:UpdatedHeading" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="CLHeadingUpdatedEventArgs"/> instance containing the event data.</param>
private void OnUpdatedHeading(object sender, CLHeadingUpdatedEventArgs e)
{
if (e.NewHeading.TrueHeading == -1)
{
return;
}
var p = (_position == null) ? new Position() : new Position(_position);
p.Heading = e.NewHeading.TrueHeading;
_position = p;
OnPositionChanged(new PositionEventArgs(p));
}
/// <summary>
/// Handles the <see cref="E:LocationsUpdated" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="CLLocationsUpdatedEventArgs"/> instance containing the event data.</param>
private void OnLocationsUpdated(object sender, CLLocationsUpdatedEventArgs e)
{
foreach (var location in e.Locations)
{
UpdatePosition(location);
}
}
/// <summary>
/// Handles the <see cref="E:UpdatedLocation" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="CLLocationUpdatedEventArgs"/> instance containing the event data.</param>
private void OnUpdatedLocation(object sender, CLLocationUpdatedEventArgs e)
{
UpdatePosition(e.NewLocation);
}
/// <summary>
/// Updates the position.
/// </summary>
/// <param name="location">The location.</param>
private void UpdatePosition(CLLocation location)
{
var p = (_position == null) ? new Position() : new Position(_position);
if (location.HorizontalAccuracy > -1)
{
p.Accuracy = location.HorizontalAccuracy;
p.Latitude = location.Coordinate.Latitude;
p.Longitude = location.Coordinate.Longitude;
}
if (location.VerticalAccuracy > -1)
{
p.Altitude = location.Altitude;
p.AltitudeAccuracy = location.VerticalAccuracy;
}
if (location.Speed > -1)
{
p.Speed = location.Speed;
}
//p.Timestamp = new DateTimeOffset(location.Timestamp);
_position = p;
OnPositionChanged(new PositionEventArgs(p));
location.Dispose();
}
/// <summary>
/// Handles the <see cref="E:Failed" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="NSErrorEventArgs"/> instance containing the event data.</param>
private void OnFailed(object sender, NSErrorEventArgs e)
{
if ((int)e.Error.Code == (int)CLError.Network)
{
OnPositionError(new PositionErrorEventArgs(GeolocationError.PositionUnavailable));
}
}
/// <summary>
/// Handles the <see cref="E:AuthorizationChanged" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="CLAuthorizationChangedEventArgs"/> instance containing the event data.</param>
private void OnAuthorizationChanged(object sender, CLAuthorizationChangedEventArgs e)
{
if (e.Status == CLAuthorizationStatus.Denied || e.Status == CLAuthorizationStatus.Restricted)
{
OnPositionError(new PositionErrorEventArgs(GeolocationError.Unauthorized));
}
}
/// <summary>
/// Handles the <see cref="E:PositionChanged" /> event.
/// </summary>
/// <param name="e">The <see cref="PositionEventArgs"/> instance containing the event data.</param>
private void OnPositionChanged(PositionEventArgs e)
{
var changed = PositionChanged;
if (changed != null)
{
changed(this, e);
}
}
/// <summary>
/// Handles the <see cref="E:PositionError" /> event.
/// </summary>
/// <param name="e">The <see cref="PositionErrorEventArgs"/> instance containing the event data.</param>
private void OnPositionError(PositionErrorEventArgs e)
{
StopListening();
var error = PositionError;
if (error != null)
{
error(this, e);
}
}
}
}
| |
#if UNITY_EDITOR || !(UNITY_WEBPLAYER || UNITY_WEBGL)
#region License
/*
* EndPointListener.cs
*
* This code is derived from EndPointListener.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 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:
* - Gonzalo Paniagua Javier <[email protected]>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <[email protected]>
* - Nicholas Devenish
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace WebSocketSharp.Net
{
internal sealed class EndPointListener
{
#region Private Fields
private List<HttpListenerPrefix> _all; // host == '+'
private static readonly string _defaultCertFolderPath;
private IPEndPoint _endpoint;
private Dictionary<HttpListenerPrefix, HttpListener> _prefixes;
private bool _secure;
private Socket _socket;
private ServerSslConfiguration _sslConfig;
private List<HttpListenerPrefix> _unhandled; // host == '*'
private Dictionary<HttpConnection, HttpConnection> _unregistered;
private object _unregisteredSync;
#endregion
#region Static Constructor
static EndPointListener ()
{
_defaultCertFolderPath =
Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
}
#endregion
#region Internal Constructors
internal EndPointListener (
IPAddress address,
int port,
bool reuseAddress,
bool secure,
string certificateFolderPath,
ServerSslConfiguration sslConfig)
{
if (secure) {
var cert = getCertificate (port, certificateFolderPath, sslConfig.ServerCertificate);
if (cert == null)
throw new ArgumentException ("No server certificate could be found.");
_secure = secure;
_sslConfig = sslConfig;
_sslConfig.ServerCertificate = cert;
}
_prefixes = new Dictionary<HttpListenerPrefix, HttpListener> ();
_unregistered = new Dictionary<HttpConnection, HttpConnection> ();
_unregisteredSync = ((ICollection) _unregistered).SyncRoot;
_socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (reuseAddress)
_socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_endpoint = new IPEndPoint (address, port);
_socket.Bind (_endpoint);
_socket.Listen (500);
_socket.BeginAccept (onAccept, this);
}
#endregion
#region Public Properties
public IPAddress Address {
get {
return _endpoint.Address;
}
}
public bool IsSecure {
get {
return _secure;
}
}
public int Port {
get {
return _endpoint.Port;
}
}
public ServerSslConfiguration SslConfiguration {
get {
return _sslConfig;
}
}
#endregion
#region Private Methods
private static void addSpecial (List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix)
{
var path = prefix.Path;
foreach (var pref in prefixes)
if (pref.Path == path)
throw new HttpListenerException (400, "The prefix is already in use."); // TODO: Code?
prefixes.Add (prefix);
}
private void checkIfRemove ()
{
if (_prefixes.Count > 0)
return;
var list = _unhandled;
if (list != null && list.Count > 0)
return;
list = _all;
if (list != null && list.Count > 0)
return;
EndPointManager.RemoveEndPoint (this);
}
private static RSACryptoServiceProvider createRSAFromFile (string filename)
{
byte[] pvk = null;
using (var fs = File.Open (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
pvk = new byte[fs.Length];
fs.Read (pvk, 0, pvk.Length);
}
var rsa = new RSACryptoServiceProvider ();
rsa.ImportCspBlob (pvk);
return rsa;
}
private static X509Certificate2 getCertificate (
int port, string certificateFolderPath, X509Certificate2 defaultCertificate)
{
if (certificateFolderPath == null || certificateFolderPath.Length == 0)
certificateFolderPath = _defaultCertFolderPath;
try {
var cer = Path.Combine (certificateFolderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (certificateFolderPath, String.Format ("{0}.key", port));
if (File.Exists (cer) && File.Exists (key)) {
var cert = new X509Certificate2 (cer);
cert.PrivateKey = createRSAFromFile (key);
return cert;
}
}
catch {
}
return defaultCertificate;
}
private static HttpListener matchFromList (
string host, string path, List<HttpListenerPrefix> list, out HttpListenerPrefix prefix)
{
prefix = null;
if (list == null)
return null;
HttpListener bestMatch = null;
var bestLen = -1;
foreach (var pref in list) {
var ppath = pref.Path;
if (ppath.Length < bestLen)
continue;
if (path.StartsWith (ppath)) {
bestLen = ppath.Length;
bestMatch = pref.Listener;
prefix = pref;
}
}
return bestMatch;
}
private static void onAccept (IAsyncResult asyncResult)
{
var lsnr = (EndPointListener) asyncResult.AsyncState;
Socket sock = null;
try {
sock = lsnr._socket.EndAccept (asyncResult);
lsnr._socket.BeginAccept (onAccept, lsnr);
}
catch {
if (sock != null)
sock.Close ();
return;
}
processAccepted (sock, lsnr);
}
private static void processAccepted (Socket socket, EndPointListener listener)
{
HttpConnection conn = null;
try {
conn = new HttpConnection (socket, listener);
lock (listener._unregisteredSync)
listener._unregistered[conn] = conn;
conn.BeginReadRequest ();
}
catch {
if (conn != null) {
conn.Close (true);
return;
}
socket.Close ();
}
}
private static bool removeSpecial (List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix)
{
var path = prefix.Path;
var cnt = prefixes.Count;
for (var i = 0; i < cnt; i++) {
if (prefixes[i].Path == path) {
prefixes.RemoveAt (i);
return true;
}
}
return false;
}
private HttpListener searchListener (Uri uri, out HttpListenerPrefix prefix)
{
prefix = null;
if (uri == null)
return null;
var host = uri.Host;
var dns = Uri.CheckHostName (host) == UriHostNameType.Dns;
var port = uri.Port;
var path = HttpUtility.UrlDecode (uri.AbsolutePath);
var pathSlash = path[path.Length - 1] == '/' ? path : path + "/";
HttpListener bestMatch = null;
var bestLen = -1;
if (host != null && host.Length > 0) {
foreach (var pref in _prefixes.Keys) {
var ppath = pref.Path;
if (ppath.Length < bestLen)
continue;
if (pref.Port != port)
continue;
if (dns) {
var phost = pref.Host;
if (Uri.CheckHostName (phost) == UriHostNameType.Dns && phost != host)
continue;
}
if (path.StartsWith (ppath) || pathSlash.StartsWith (ppath)) {
bestLen = ppath.Length;
bestMatch = _prefixes[pref];
prefix = pref;
}
}
if (bestLen != -1)
return bestMatch;
}
var list = _unhandled;
bestMatch = matchFromList (host, path, list, out prefix);
if (path != pathSlash && bestMatch == null)
bestMatch = matchFromList (host, pathSlash, list, out prefix);
if (bestMatch != null)
return bestMatch;
list = _all;
bestMatch = matchFromList (host, path, list, out prefix);
if (path != pathSlash && bestMatch == null)
bestMatch = matchFromList (host, pathSlash, list, out prefix);
if (bestMatch != null)
return bestMatch;
return null;
}
#endregion
#region Internal Methods
internal static bool CertificateExists (int port, string certificateFolderPath)
{
if (certificateFolderPath == null || certificateFolderPath.Length == 0)
certificateFolderPath = _defaultCertFolderPath;
var cer = Path.Combine (certificateFolderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (certificateFolderPath, String.Format ("{0}.key", port));
return File.Exists (cer) && File.Exists (key);
}
internal void RemoveConnection (HttpConnection connection)
{
lock (_unregisteredSync)
_unregistered.Remove (connection);
}
#endregion
#region Public Methods
public void AddPrefix (HttpListenerPrefix prefix, HttpListener listener)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*") {
do {
current = _unhandled;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
prefix.Listener = listener;
addSpecial (future, prefix);
}
while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);
return;
}
if (prefix.Host == "+") {
do {
current = _all;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
prefix.Listener = listener;
addSpecial (future, prefix);
}
while (Interlocked.CompareExchange (ref _all, future, current) != current);
return;
}
Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2;
do {
prefs = _prefixes;
if (prefs.ContainsKey (prefix)) {
if (prefs[prefix] != listener)
throw new HttpListenerException (
400, String.Format ("There's another listener for {0}.", prefix)); // TODO: Code?
return;
}
prefs2 = new Dictionary<HttpListenerPrefix, HttpListener> (prefs);
prefs2[prefix] = listener;
}
while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs);
}
public bool BindContext (HttpListenerContext context)
{
HttpListenerPrefix pref;
var lsnr = searchListener (context.Request.Url, out pref);
if (lsnr == null)
return false;
context.Listener = lsnr;
context.Connection.Prefix = pref;
return true;
}
public void Close ()
{
_socket.Close ();
lock (_unregisteredSync) {
var conns = new List<HttpConnection> (_unregistered.Keys);
_unregistered.Clear ();
foreach (var conn in conns)
conn.Close (true);
conns.Clear ();
}
}
public void RemovePrefix (HttpListenerPrefix prefix, HttpListener listener)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*") {
do {
current = _unhandled;
if (current == null)
break;
future = new List<HttpListenerPrefix> (current);
if (!removeSpecial (future, prefix))
break; // The prefix wasn't found.
}
while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);
checkIfRemove ();
return;
}
if (prefix.Host == "+") {
do {
current = _all;
if (current == null)
break;
future = new List<HttpListenerPrefix> (current);
if (!removeSpecial (future, prefix))
break; // The prefix wasn't found.
}
while (Interlocked.CompareExchange (ref _all, future, current) != current);
checkIfRemove ();
return;
}
Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2;
do {
prefs = _prefixes;
if (!prefs.ContainsKey (prefix))
break;
prefs2 = new Dictionary<HttpListenerPrefix, HttpListener> (prefs);
prefs2.Remove (prefix);
}
while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs);
checkIfRemove ();
}
public void UnbindContext (HttpListenerContext context)
{
if (context == null || context.Listener == null)
return;
context.Listener.UnregisterContext (context);
}
#endregion
}
}
#endif
| |
// <copyright file="FixedLengthParserTest.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.IO;
using Xunit;
namespace BeanIO.Parser.FixedLength
{
public class FixedLengthParserTest : ParserTest
{
[Fact]
public void TestFieldDefinitions()
{
var factory = NewStreamFactory("fixedlength.xml");
var reader = factory.CreateReader("f1", LoadReader("f1_valid.txt"));
try
{
var map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.Equal(" value", map["default"]);
Assert.Equal(12345, map["number"]);
Assert.Equal("value", map["padx"]);
Assert.Equal("value", map["pos40"]);
var text = new StringWriter();
var writer = factory.CreateWriter("f1", text);
writer.Write(map);
writer.Flush();
writer.Close();
Assert.Equal(" value 0000012345valuexxxxx value", text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestDefaultMinLengthValidation()
{
var factory = NewStreamFactory("fixedlength.xml");
var reader = factory.CreateReader("f1", LoadReader("f1_minLength.txt"));
try
{
Assert.ThrowsAny<InvalidRecordException>(() => reader.Read());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestDefaultMaxLengthValidation()
{
var factory = NewStreamFactory("fixedlength.xml");
var reader = factory.CreateReader("f1", LoadReader("f1_maxLength.txt"));
try
{
Assert.ThrowsAny<InvalidRecordException>(() => reader.Read());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestOptionalField()
{
var factory = NewStreamFactory("fixedlength.xml");
var reader = factory.CreateReader("f2", LoadReader("f2_valid.txt"));
try
{
var map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("field3"));
Assert.Equal("value", map["field3"]);
map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("field3"));
Assert.Equal("value", map["field3"]);
map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.False(map.ContainsKey("field3"));
var text = new StringWriter();
factory.CreateWriter("f2", text).Write(map);
Assert.Equal("1234512345\r\n", text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestValidation()
{
var factory = NewStreamFactory("fixedlength.xml");
var reader = factory.CreateReader("f2", LoadReader("f2_invalid.txt"));
try
{
AssertRecordError(reader, 1, "record", "minLength, 1, Record Label, 12345, 10, 20");
AssertRecordError(reader, 2, "record", "maxLength, 2, Record Label, 123456789012345678901, 10, 20");
AssertFieldError(reader, 3, "record", "field3", "val", "Invalid field length, expected 5 characters");
}
finally
{
reader.Close();
}
}
[Fact]
public void TestReader()
{
var factory = NewStreamFactory("fixedlength.xml");
var reader = factory.CreateReader("f3", LoadReader("f3_valid.txt"));
try
{
var map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("field1"));
Assert.Equal("00001", map["field1"]);
Assert.True(map.ContainsKey("field2"));
Assert.Equal(string.Empty, map["field2"]);
Assert.True(map.ContainsKey("field3"));
Assert.Equal("XXXXX", map["field3"]);
var text = new StringWriter();
factory.CreateWriter("f3", text).Write(map);
Assert.Equal("00001 XXXXX" + LineSeparator, text.ToString());
map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("field1"));
Assert.Equal("00002", map["field1"]);
Assert.True(map.ContainsKey("field2"));
Assert.Equal("Val2", map["field2"]);
map["field2"] = "Value2";
text = new StringWriter();
factory.CreateWriter("f3", text).Write(map);
Assert.Equal("00002Value" + LineSeparator, text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestPadding()
{
var factory = NewStreamFactory("fixedlength.xml");
var reader = factory.CreateReader("f4", LoadReader("f4_padding.txt"));
try
{
var map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("number"));
Assert.Equal(new int?[] { 0, 1, 10, 100, 1000, 10000, null }, Assert.IsType<List<int?>>(map["number"]));
var text = new StringWriter();
factory.CreateWriter("f4", text).Write(map);
Assert.Equal("INT000000000100010001000100010000 ", text.ToString());
map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("character"));
Assert.Equal(new[] { 'A', 'B', ' ', 'D' }, Assert.IsType<List<char>>(map["character"]));
text = new StringWriter();
factory.CreateWriter("f4", text).Write(map);
Assert.Equal("CHAAB D", text.ToString());
map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("stringLeft"));
Assert.Equal(new[] { "TXT", "TX", "T", string.Empty }, Assert.IsType<List<string>>(map["stringLeft"]));
text = new StringWriter();
factory.CreateWriter("f4", text).Write(map);
Assert.Equal("STLTXTTX T ", text.ToString());
map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("stringRight"));
Assert.Equal(new[] { "TXT", "TX", "T", string.Empty }, Assert.IsType<List<string>>(map["stringRight"]));
text = new StringWriter();
factory.CreateWriter("f4", text).Write(map);
Assert.Equal("STRTXT TX T ", text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestIgnoredField()
{
var factory = NewStreamFactory("fixedlength.xml");
var reader = factory.CreateReader("f5", LoadReader("f5_valid.txt"));
try
{
var map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("lastName"));
Assert.Equal("Smith", map["lastName"]);
Assert.False(map.ContainsKey("firstName"));
var text = new StringWriter();
factory.CreateWriter("f5", text).Write(map);
Assert.Equal("AAAAAAAAAASmith ", text.ToString());
}
finally
{
reader.Close();
}
}
[Fact]
public void TestVariableLengthField()
{
var factory = NewStreamFactory("fixedlength.xml");
var u = factory.CreateUnmarshaller("f6");
var record = "kevin johnson";
var map = Assert.IsType<Dictionary<string, object>>(u.Unmarshal(record));
Assert.True(map.ContainsKey("firstName"));
Assert.Equal("kevin", map["firstName"]);
Assert.True(map.ContainsKey("lastName"));
Assert.Equal("johnson", map["lastName"]);
var m = factory.CreateMarshaller("f6");
Assert.Equal(record, m.Marshal(map).ToString());
}
[Fact]
public void TestKeepPadding()
{
var factory = NewStreamFactory("fixedlength.xml");
var m = factory.CreateMarshaller("f7");
var reader = factory.CreateReader("f7", LoadReader("f7.txt"));
try
{
var map = Assert.IsType<Dictionary<string, object>>(reader.Read());
Assert.True(map.ContainsKey("firstName"));
Assert.Equal("kevin ", map["firstName"]);
Assert.True(map.ContainsKey("lastName"));
Assert.Equal(" ", map["lastName"]);
Assert.Equal("kevin ", m.Marshal(map).ToString());
AssertFieldError(reader, 2, "record", "firstName", " ", "Required field not set");
}
finally
{
reader.Close();
}
}
[Fact]
public void TestOverlay()
{
var factory = NewStreamFactory("fixedlength.xml");
var output = new StringWriter();
var writer = factory.CreateWriter("f8", output);
var map = new System.Collections.Hashtable();
map["number"] = 3;
map["name"] = "LAUREN1";
writer.Write("record1", map);
map.Clear();
map["number"] = 5;
writer.Write("record2", map);
writer.Flush();
Assert.Equal("003LAUREN1\n0005\n", output.ToString());
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Testing;
using osu.Framework.Utils;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online;
using osu.Game.Online.Multiplayer;
using osu.Game.Online.Rooms;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Screens.OnlinePlay.Multiplayer.Participants;
using osu.Game.Users;
using osuTK;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneMultiplayerParticipantsList : MultiplayerTestScene
{
[SetUpSteps]
public void SetupSteps()
{
createNewParticipantsList();
}
[Test]
public void TestAddUser()
{
AddAssert("one unique panel", () => this.ChildrenOfType<ParticipantPanel>().Select(p => p.User).Distinct().Count() == 1);
AddStep("add user", () => Client.AddUser(new User
{
Id = 3,
Username = "Second",
CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
}));
AddAssert("two unique panels", () => this.ChildrenOfType<ParticipantPanel>().Select(p => p.User).Distinct().Count() == 2);
}
[Test]
public void TestAddNullUser()
{
AddAssert("one unique panel", () => this.ChildrenOfType<ParticipantPanel>().Select(p => p.User).Distinct().Count() == 1);
AddStep("add non-resolvable user", () => Client.AddNullUser(-3));
AddUntilStep("two unique panels", () => this.ChildrenOfType<ParticipantPanel>().Select(p => p.User).Distinct().Count() == 2);
}
[Test]
public void TestRemoveUser()
{
User secondUser = null;
AddStep("add a user", () =>
{
Client.AddUser(secondUser = new User
{
Id = 3,
Username = "Second",
CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
});
});
AddStep("remove host", () => Client.RemoveUser(API.LocalUser.Value));
AddAssert("single panel is for second user", () => this.ChildrenOfType<ParticipantPanel>().Single().User.User == secondUser);
}
[Test]
public void TestGameStateHasPriorityOverDownloadState()
{
AddStep("set to downloading map", () => Client.ChangeBeatmapAvailability(BeatmapAvailability.Downloading(0)));
checkProgressBarVisibility(true);
AddStep("make user ready", () => Client.ChangeState(MultiplayerUserState.Results));
checkProgressBarVisibility(false);
AddUntilStep("ready mark visible", () => this.ChildrenOfType<StateDisplay>().Single().IsPresent);
AddStep("make user ready", () => Client.ChangeState(MultiplayerUserState.Idle));
checkProgressBarVisibility(true);
}
[Test]
public void TestCorrectInitialState()
{
AddStep("set to downloading map", () => Client.ChangeBeatmapAvailability(BeatmapAvailability.Downloading(0)));
createNewParticipantsList();
checkProgressBarVisibility(true);
}
[Test]
public void TestBeatmapDownloadingStates()
{
AddStep("set to no map", () => Client.ChangeBeatmapAvailability(BeatmapAvailability.NotDownloaded()));
AddStep("set to downloading map", () => Client.ChangeBeatmapAvailability(BeatmapAvailability.Downloading(0)));
checkProgressBarVisibility(true);
AddRepeatStep("increment progress", () =>
{
var progress = this.ChildrenOfType<ParticipantPanel>().Single().User.BeatmapAvailability.DownloadProgress ?? 0;
Client.ChangeBeatmapAvailability(BeatmapAvailability.Downloading(progress + RNG.NextSingle(0.1f)));
}, 25);
AddAssert("progress bar increased", () => this.ChildrenOfType<ProgressBar>().Single().Current.Value > 0);
AddStep("set to importing map", () => Client.ChangeBeatmapAvailability(BeatmapAvailability.Importing()));
checkProgressBarVisibility(false);
AddStep("set to available", () => Client.ChangeBeatmapAvailability(BeatmapAvailability.LocallyAvailable()));
}
[Test]
public void TestToggleReadyState()
{
AddAssert("ready mark invisible", () => !this.ChildrenOfType<StateDisplay>().Single().IsPresent);
AddStep("make user ready", () => Client.ChangeState(MultiplayerUserState.Ready));
AddUntilStep("ready mark visible", () => this.ChildrenOfType<StateDisplay>().Single().IsPresent);
AddStep("make user idle", () => Client.ChangeState(MultiplayerUserState.Idle));
AddUntilStep("ready mark invisible", () => !this.ChildrenOfType<StateDisplay>().Single().IsPresent);
}
[Test]
public void TestToggleSpectateState()
{
AddStep("make user spectating", () => Client.ChangeState(MultiplayerUserState.Spectating));
AddStep("make user idle", () => Client.ChangeState(MultiplayerUserState.Idle));
}
[Test]
public void TestCrownChangesStateWhenHostTransferred()
{
AddStep("add user", () => Client.AddUser(new User
{
Id = 3,
Username = "Second",
CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
}));
AddUntilStep("first user crown visible", () => this.ChildrenOfType<ParticipantPanel>().ElementAt(0).ChildrenOfType<SpriteIcon>().First().Alpha == 1);
AddUntilStep("second user crown hidden", () => this.ChildrenOfType<ParticipantPanel>().ElementAt(1).ChildrenOfType<SpriteIcon>().First().Alpha == 0);
AddStep("make second user host", () => Client.TransferHost(3));
AddUntilStep("first user crown hidden", () => this.ChildrenOfType<ParticipantPanel>().ElementAt(0).ChildrenOfType<SpriteIcon>().First().Alpha == 0);
AddUntilStep("second user crown visible", () => this.ChildrenOfType<ParticipantPanel>().ElementAt(1).ChildrenOfType<SpriteIcon>().First().Alpha == 1);
}
[Test]
public void TestManyUsers()
{
AddStep("add many users", () =>
{
for (int i = 0; i < 20; i++)
{
Client.AddUser(new User
{
Id = i,
Username = $"User {i}",
RulesetsStatistics = new Dictionary<string, UserStatistics>
{
{
Ruleset.Value.ShortName,
new UserStatistics { GlobalRank = RNG.Next(1, 100000), }
}
},
CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
});
Client.ChangeUserState(i, (MultiplayerUserState)RNG.Next(0, (int)MultiplayerUserState.Results + 1));
if (RNG.NextBool())
{
var beatmapState = (DownloadState)RNG.Next(0, (int)DownloadState.LocallyAvailable + 1);
switch (beatmapState)
{
case DownloadState.NotDownloaded:
Client.ChangeUserBeatmapAvailability(i, BeatmapAvailability.NotDownloaded());
break;
case DownloadState.Downloading:
Client.ChangeUserBeatmapAvailability(i, BeatmapAvailability.Downloading(RNG.NextSingle()));
break;
case DownloadState.Importing:
Client.ChangeUserBeatmapAvailability(i, BeatmapAvailability.Importing());
break;
}
}
}
});
}
[Test]
public void TestUserWithMods()
{
AddStep("add user", () =>
{
Client.AddUser(new User
{
Id = 0,
Username = "User 0",
RulesetsStatistics = new Dictionary<string, UserStatistics>
{
{
Ruleset.Value.ShortName,
new UserStatistics { GlobalRank = RNG.Next(1, 100000), }
}
},
CoverUrl = @"https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
});
Client.ChangeUserMods(0, new Mod[]
{
new OsuModHardRock(),
new OsuModDifficultyAdjust { ApproachRate = { Value = 1 } }
});
});
for (var i = MultiplayerUserState.Idle; i < MultiplayerUserState.Results; i++)
{
var state = i;
AddStep($"set state: {state}", () => Client.ChangeUserState(0, state));
}
}
private void createNewParticipantsList()
{
ParticipantsList participantsList = null;
AddStep("create new list", () => Child = participantsList = new ParticipantsList
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Y,
Size = new Vector2(380, 0.7f)
});
AddUntilStep("wait for list to load", () => participantsList.IsLoaded);
}
private void checkProgressBarVisibility(bool visible) =>
AddUntilStep($"progress bar {(visible ? "is" : "is not")}visible", () =>
this.ChildrenOfType<ProgressBar>().Single().IsPresent == visible);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation.Host;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// The RemoteHostMethodId enum.
/// </summary>
internal enum RemoteHostMethodId
{
// Host read-only properties.
GetName = 1,
GetVersion = 2,
GetInstanceId = 3,
GetCurrentCulture = 4,
GetCurrentUICulture = 5,
// Host methods.
SetShouldExit = 6,
EnterNestedPrompt = 7,
ExitNestedPrompt = 8,
NotifyBeginApplication = 9,
NotifyEndApplication = 10,
// Host UI methods.
ReadLine = 11,
ReadLineAsSecureString = 12,
Write1 = 13,
Write2 = 14,
WriteLine1 = 15,
WriteLine2 = 16,
WriteLine3 = 17,
WriteErrorLine = 18,
WriteDebugLine = 19,
WriteProgress = 20,
WriteVerboseLine = 21,
WriteWarningLine = 22,
Prompt = 23,
PromptForCredential1 = 24,
PromptForCredential2 = 25,
PromptForChoice = 26,
// Host Raw UI read-write properties.
GetForegroundColor = 27,
SetForegroundColor = 28,
GetBackgroundColor = 29,
SetBackgroundColor = 30,
GetCursorPosition = 31,
SetCursorPosition = 32,
GetWindowPosition = 33,
SetWindowPosition = 34,
GetCursorSize = 35,
SetCursorSize = 36,
GetBufferSize = 37,
SetBufferSize = 38,
GetWindowSize = 39,
SetWindowSize = 40,
GetWindowTitle = 41,
SetWindowTitle = 42,
// Host Raw UI read-only properties.
GetMaxWindowSize = 43,
GetMaxPhysicalWindowSize = 44,
GetKeyAvailable = 45,
// Host Raw UI methods.
ReadKey = 46,
FlushInputBuffer = 47,
SetBufferContents1 = 48,
SetBufferContents2 = 49,
GetBufferContents = 50,
ScrollBufferContents = 51,
// IHostSupportsInteractiveSession methods.
PushRunspace = 52,
PopRunspace = 53,
// IHostSupportsInteractiveSession read-only properties.
GetIsRunspacePushed = 54,
GetRunspace = 55,
// IHostSupportsMultipleChoiceSelection
PromptForChoiceMultipleSelection = 56,
}
/// <summary>
/// Stores information about remote host methods. By storing information
/// in this data structure we only need to transport enums on the wire.
/// </summary>
internal class RemoteHostMethodInfo
{
/// <summary>
/// Interface type.
/// </summary>
internal Type InterfaceType { get; }
/// <summary>
/// Name.
/// </summary>
internal string Name { get; }
/// <summary>
/// Return type.
/// </summary>
internal Type ReturnType { get; }
/// <summary>
/// Parameter types.
/// </summary>
internal Type[] ParameterTypes { get; }
/// <summary>
/// Create a new instance of RemoteHostMethodInfo.
/// </summary>
internal RemoteHostMethodInfo(
Type interfaceType,
string name,
Type returnType,
Type[] parameterTypes)
{
InterfaceType = interfaceType;
Name = name;
ReturnType = returnType;
ParameterTypes = parameterTypes;
}
/// <summary>
/// Look up.
/// </summary>
internal static RemoteHostMethodInfo LookUp(RemoteHostMethodId methodId)
{
switch (methodId)
{
// Host read-only properties.
case RemoteHostMethodId.GetName:
return new RemoteHostMethodInfo(
typeof(PSHost),
"get_Name",
typeof(string),
new Type[] { });
case RemoteHostMethodId.GetVersion:
return new RemoteHostMethodInfo(
typeof(PSHost),
"get_Version",
typeof(Version),
new Type[] { });
case RemoteHostMethodId.GetInstanceId:
return new RemoteHostMethodInfo(
typeof(PSHost),
"get_InstanceId",
typeof(Guid),
new Type[] { });
case RemoteHostMethodId.GetCurrentCulture:
return new RemoteHostMethodInfo(
typeof(PSHost),
"get_CurrentCulture",
typeof(System.Globalization.CultureInfo),
new Type[] { });
case RemoteHostMethodId.GetCurrentUICulture:
return new RemoteHostMethodInfo(
typeof(PSHost),
"get_CurrentUICulture",
typeof(System.Globalization.CultureInfo),
new Type[] { });
// Host methods.
case RemoteHostMethodId.SetShouldExit:
return new RemoteHostMethodInfo(
typeof(PSHost),
"SetShouldExit",
typeof(void),
new Type[] { typeof(int) });
case RemoteHostMethodId.EnterNestedPrompt:
return new RemoteHostMethodInfo(
typeof(PSHost),
"EnterNestedPrompt",
typeof(void),
new Type[] { });
case RemoteHostMethodId.ExitNestedPrompt:
return new RemoteHostMethodInfo(
typeof(PSHost),
"ExitNestedPrompt",
typeof(void),
new Type[] { });
case RemoteHostMethodId.NotifyBeginApplication:
return new RemoteHostMethodInfo(
typeof(PSHost),
"NotifyBeginApplication",
typeof(void),
new Type[] { });
case RemoteHostMethodId.NotifyEndApplication:
return new RemoteHostMethodInfo(
typeof(PSHost),
"NotifyEndApplication",
typeof(void),
new Type[] { });
// Host UI methods.
case RemoteHostMethodId.ReadLine:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"ReadLine",
typeof(string),
new Type[] { });
case RemoteHostMethodId.ReadLineAsSecureString:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"ReadLineAsSecureString",
typeof(System.Security.SecureString),
new Type[] { });
case RemoteHostMethodId.Write1:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"Write",
typeof(void),
new Type[] { typeof(string) });
case RemoteHostMethodId.Write2:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"Write",
typeof(void),
new Type[] { typeof(ConsoleColor), typeof(ConsoleColor), typeof(string) });
case RemoteHostMethodId.WriteLine1:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"WriteLine",
typeof(void),
new Type[] { });
case RemoteHostMethodId.WriteLine2:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"WriteLine",
typeof(void),
new Type[] { typeof(string) });
case RemoteHostMethodId.WriteLine3:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"WriteLine",
typeof(void),
new Type[] { typeof(ConsoleColor), typeof(ConsoleColor), typeof(string) });
case RemoteHostMethodId.WriteErrorLine:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"WriteErrorLine",
typeof(void),
new Type[] { typeof(string) });
case RemoteHostMethodId.WriteDebugLine:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"WriteDebugLine",
typeof(void),
new Type[] { typeof(string) });
case RemoteHostMethodId.WriteProgress:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"WriteProgress",
typeof(void),
new Type[] { typeof(long), typeof(ProgressRecord) });
case RemoteHostMethodId.WriteVerboseLine:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"WriteVerboseLine",
typeof(void),
new Type[] { typeof(string) });
case RemoteHostMethodId.WriteWarningLine:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"WriteWarningLine",
typeof(void),
new Type[] { typeof(string) });
case RemoteHostMethodId.Prompt:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"Prompt",
typeof(Dictionary<string, PSObject>),
new Type[] { typeof(string), typeof(string), typeof(System.Collections.ObjectModel.Collection<FieldDescription>) });
case RemoteHostMethodId.PromptForCredential1:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"PromptForCredential",
typeof(PSCredential),
new Type[] { typeof(string), typeof(string), typeof(string), typeof(string) });
case RemoteHostMethodId.PromptForCredential2:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"PromptForCredential",
typeof(PSCredential),
new Type[] { typeof(string), typeof(string), typeof(string), typeof(string), typeof(PSCredentialTypes), typeof(PSCredentialUIOptions) });
case RemoteHostMethodId.PromptForChoice:
return new RemoteHostMethodInfo(
typeof(PSHostUserInterface),
"PromptForChoice",
typeof(int),
new Type[] { typeof(string), typeof(string), typeof(System.Collections.ObjectModel.Collection<ChoiceDescription>), typeof(int) });
case RemoteHostMethodId.PromptForChoiceMultipleSelection:
return new RemoteHostMethodInfo(
typeof(IHostUISupportsMultipleChoiceSelection),
"PromptForChoice",
typeof(Collection<int>),
new Type[] { typeof(string), typeof(string), typeof(Collection<ChoiceDescription>), typeof(IEnumerable<int>) });
// Host raw UI read-write properties.
case RemoteHostMethodId.GetForegroundColor:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_ForegroundColor",
typeof(ConsoleColor),
new Type[] { });
case RemoteHostMethodId.SetForegroundColor:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"set_ForegroundColor",
typeof(void),
new Type[] { typeof(ConsoleColor) });
case RemoteHostMethodId.GetBackgroundColor:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_BackgroundColor",
typeof(ConsoleColor),
new Type[] { });
case RemoteHostMethodId.SetBackgroundColor:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"set_BackgroundColor",
typeof(void),
new Type[] { typeof(ConsoleColor) });
case RemoteHostMethodId.GetCursorPosition:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_CursorPosition",
typeof(Coordinates),
new Type[] { });
case RemoteHostMethodId.SetCursorPosition:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"set_CursorPosition",
typeof(void),
new Type[] { typeof(Coordinates) });
case RemoteHostMethodId.GetWindowPosition:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_WindowPosition",
typeof(Coordinates),
new Type[] { });
case RemoteHostMethodId.SetWindowPosition:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"set_WindowPosition",
typeof(void),
new Type[] { typeof(Coordinates) });
case RemoteHostMethodId.GetCursorSize:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_CursorSize",
typeof(int),
new Type[] { });
case RemoteHostMethodId.SetCursorSize:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"set_CursorSize",
typeof(void),
new Type[] { typeof(int) });
case RemoteHostMethodId.GetBufferSize:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_BufferSize",
typeof(Size),
new Type[] { });
case RemoteHostMethodId.SetBufferSize:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"set_BufferSize",
typeof(void),
new Type[] { typeof(Size) });
case RemoteHostMethodId.GetWindowSize:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_WindowSize",
typeof(Size),
new Type[] { });
case RemoteHostMethodId.SetWindowSize:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"set_WindowSize",
typeof(void),
new Type[] { typeof(Size) });
case RemoteHostMethodId.GetWindowTitle:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_WindowTitle",
typeof(string),
new Type[] { });
case RemoteHostMethodId.SetWindowTitle:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"set_WindowTitle",
typeof(void),
new Type[] { typeof(string) });
// Host raw UI read-only properties.
case RemoteHostMethodId.GetMaxWindowSize:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_MaxWindowSize",
typeof(Size),
new Type[] { });
case RemoteHostMethodId.GetMaxPhysicalWindowSize:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_MaxPhysicalWindowSize",
typeof(Size),
new Type[] { });
case RemoteHostMethodId.GetKeyAvailable:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"get_KeyAvailable",
typeof(bool),
new Type[] { });
// Host raw UI methods.
case RemoteHostMethodId.ReadKey:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"ReadKey",
typeof(KeyInfo),
new Type[] { typeof(ReadKeyOptions) });
case RemoteHostMethodId.FlushInputBuffer:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"FlushInputBuffer",
typeof(void),
new Type[] { });
case RemoteHostMethodId.SetBufferContents1:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"SetBufferContents",
typeof(void),
new Type[] { typeof(Rectangle), typeof(BufferCell) });
case RemoteHostMethodId.SetBufferContents2:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"SetBufferContents",
typeof(void),
new Type[] { typeof(Coordinates), typeof(BufferCell[,]) });
case RemoteHostMethodId.GetBufferContents:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"GetBufferContents",
typeof(BufferCell[,]),
new Type[] { typeof(Rectangle) });
case RemoteHostMethodId.ScrollBufferContents:
return new RemoteHostMethodInfo(
typeof(PSHostRawUserInterface),
"ScrollBufferContents",
typeof(void),
new Type[] { typeof(Rectangle), typeof(Coordinates), typeof(Rectangle), typeof(BufferCell) });
// IHostSupportsInteractiveSession methods.
case RemoteHostMethodId.PushRunspace:
return new RemoteHostMethodInfo(
typeof(IHostSupportsInteractiveSession),
"PushRunspace",
typeof(void),
new Type[] { typeof(System.Management.Automation.Runspaces.Runspace) });
case RemoteHostMethodId.PopRunspace:
return new RemoteHostMethodInfo(
typeof(IHostSupportsInteractiveSession),
"PopRunspace",
typeof(void),
new Type[] { });
// IHostSupportsInteractiveSession properties.
case RemoteHostMethodId.GetIsRunspacePushed:
return new RemoteHostMethodInfo(
typeof(IHostSupportsInteractiveSession),
"get_IsRunspacePushed",
typeof(bool),
new Type[] { });
case RemoteHostMethodId.GetRunspace:
return new RemoteHostMethodInfo(
typeof(IHostSupportsInteractiveSession),
"get_Runspace",
typeof(System.Management.Automation.Runspaces.Runspace),
new Type[] { });
default:
Dbg.Assert(false, "All RemoteHostMethodId's should be handled. This code should not be reached.");
return null;
}
}
}
}
| |
// 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.Management.Batch
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ApplicationPackageOperations operations.
/// </summary>
internal partial class ApplicationPackageOperations : Microsoft.Rest.IServiceOperations<BatchManagementClient>, IApplicationPackageOperations
{
/// <summary>
/// Initializes a new instance of the ApplicationPackageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ApplicationPackageOperations(BatchManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the BatchManagementClient
/// </summary>
public BatchManagementClient Client { get; private set; }
/// <summary>
/// Activates the specified application package.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application to activate.
/// </param>
/// <param name='format'>
/// The format of the application package binary file.
/// </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> ActivateWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, string version, string format, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (applicationId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "applicationId");
}
if (version == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "version");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (format == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "format");
}
ActivateApplicationPackageParameters parameters = new ActivateApplicationPackageParameters();
if (format != null)
{
parameters.Format = format;
}
// 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("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("applicationId", applicationId);
tracingParameters.Add("version", version);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Activate", 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.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}/activate").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId));
_url = _url.Replace("{version}", System.Uri.EscapeDataString(version));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + 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;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.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 (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 != 204)
{
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;
}
/// <summary>
/// Creates an application package record.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application.
/// </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.SerializationException">
/// Thrown when unable to deserialize the response
/// </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<ApplicationPackage>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, string version, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (applicationId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "applicationId");
}
if (version == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "version");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// 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("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("applicationId", applicationId);
tracingParameters.Add("version", version);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Create", 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.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId));
_url = _url.Replace("{version}", System.Uri.EscapeDataString(version));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + 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("PUT");
_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 != 201)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
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<ApplicationPackage>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationPackage>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an application package record and its associated binary file.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application to delete.
/// </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> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, string version, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (applicationId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "applicationId");
}
if (version == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "version");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// 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("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("applicationId", applicationId);
tracingParameters.Add("version", version);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", 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.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId));
_url = _url.Replace("{version}", System.Uri.EscapeDataString(version));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + 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("DELETE");
_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 != 204)
{
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;
}
/// <summary>
/// Gets information about the specified application package.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the Batch account.
/// </param>
/// <param name='accountName'>
/// The name of the Batch account.
/// </param>
/// <param name='applicationId'>
/// The id of the application.
/// </param>
/// <param name='version'>
/// The version of the application.
/// </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.SerializationException">
/// Thrown when unable to deserialize the response
/// </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<ApplicationPackage>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string applicationId, string version, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (accountName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
}
}
if (applicationId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "applicationId");
}
if (version == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "version");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// 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("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("applicationId", applicationId);
tracingParameters.Add("version", version);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", 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.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{applicationId}", System.Uri.EscapeDataString(applicationId));
_url = _url.Replace("{version}", System.Uri.EscapeDataString(version));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + 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("GET");
_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 != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
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<ApplicationPackage>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationPackage>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Orchard.Caching;
using Orchard.Environment.Extensions.Models;
using Orchard.FileSystems.WebSite;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Utility.Extensions;
using Orchard.Exceptions;
namespace Orchard.Environment.Extensions.Folders {
public class ExtensionHarvester : IExtensionHarvester {
private const string NameSection = "name";
private const string PathSection = "path";
private const string DescriptionSection = "description";
private const string VersionSection = "version";
private const string OrchardVersionSection = "orchardversion";
private const string AuthorSection = "author";
private const string WebsiteSection = "website";
private const string TagsSection = "tags";
private const string AntiForgerySection = "antiforgery";
private const string ZonesSection = "zones";
private const string BaseThemeSection = "basetheme";
private const string DependenciesSection = "dependencies";
private const string CategorySection = "category";
private const string FeatureDescriptionSection = "featuredescription";
private const string FeatureNameSection = "featurename";
private const string PrioritySection = "priority";
private const string FeaturesSection = "features";
private const string SessionStateSection = "sessionstate";
private const string LifecycleStatusSection = "lifecyclestatus";
private readonly ICacheManager _cacheManager;
private readonly IWebSiteFolder _webSiteFolder;
private readonly ICriticalErrorProvider _criticalErrorProvider;
public ExtensionHarvester(ICacheManager cacheManager, IWebSiteFolder webSiteFolder, ICriticalErrorProvider criticalErrorProvider) {
_cacheManager = cacheManager;
_webSiteFolder = webSiteFolder;
_criticalErrorProvider = criticalErrorProvider;
Logger = NullLogger.Instance;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public ILogger Logger { get; set; }
public bool DisableMonitoring { get; set; }
public IEnumerable<ExtensionDescriptor> HarvestExtensions(IEnumerable<string> paths, string extensionType, string manifestName, bool manifestIsOptional) {
return paths
.SelectMany(path => HarvestExtensions(path, extensionType, manifestName, manifestIsOptional))
.ToList();
}
private IEnumerable<ExtensionDescriptor> HarvestExtensions(string path, string extensionType, string manifestName, bool manifestIsOptional) {
string key = string.Format("{0}-{1}-{2}", path, manifestName, extensionType);
return _cacheManager.Get(key, true, ctx => {
if (!DisableMonitoring) {
Logger.Debug("Monitoring virtual path \"{0}\"", path);
ctx.Monitor(_webSiteFolder.WhenPathChanges(path));
}
return AvailableExtensionsInFolder(path, extensionType, manifestName, manifestIsOptional).ToReadOnlyCollection();
});
}
private List<ExtensionDescriptor> AvailableExtensionsInFolder(string path, string extensionType, string manifestName, bool manifestIsOptional) {
Logger.Information("Start looking for extensions in '{0}'...", path);
var subfolderPaths = _webSiteFolder.ListDirectories(path);
var localList = new List<ExtensionDescriptor>();
foreach (var subfolderPath in subfolderPaths) {
var extensionId = Path.GetFileName(subfolderPath.TrimEnd('/', '\\'));
var manifestPath = Path.Combine(subfolderPath, manifestName);
try {
var descriptor = GetExtensionDescriptor(path, extensionId, extensionType, manifestPath, manifestIsOptional);
if (descriptor == null)
continue;
if (descriptor.Path != null && !descriptor.Path.IsValidUrlSegment()) {
Logger.Error("The module '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.",
extensionId,
descriptor.Path);
_criticalErrorProvider.RegisterErrorMessage(T("The extension '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.",
extensionId,
descriptor.Path));
continue;
}
if (descriptor.Path == null) {
descriptor.Path = descriptor.Name.IsValidUrlSegment()
? descriptor.Name
: descriptor.Id;
}
localList.Add(descriptor);
}
catch (Exception ex) {
// Ignore invalid module manifests
if (ex.IsFatal()) {
throw;
}
Logger.Error(ex, "The module '{0}' could not be loaded. It was ignored.", extensionId);
_criticalErrorProvider.RegisterErrorMessage(T("The extension '{0}' manifest could not be loaded. It was ignored.", extensionId));
}
}
Logger.Information("Done looking for extensions in '{0}': {1}", path, string.Join(", ", localList.Select(d => d.Id)));
return localList;
}
public static ExtensionDescriptor GetDescriptorForExtension(string locationPath, string extensionId, string extensionType, string manifestText) {
Dictionary<string, string> manifest = ParseManifest(manifestText);
var extensionDescriptor = new ExtensionDescriptor {
Location = locationPath,
Id = extensionId,
ExtensionType = extensionType,
Name = GetValue(manifest, NameSection) ?? extensionId,
Path = GetValue(manifest, PathSection),
Description = GetValue(manifest, DescriptionSection),
Version = GetValue(manifest, VersionSection),
OrchardVersion = GetValue(manifest, OrchardVersionSection),
Author = GetValue(manifest, AuthorSection),
WebSite = GetValue(manifest, WebsiteSection),
Tags = GetValue(manifest, TagsSection),
AntiForgery = GetValue(manifest, AntiForgerySection),
Zones = GetValue(manifest, ZonesSection),
BaseTheme = GetValue(manifest, BaseThemeSection),
SessionState = GetValue(manifest, SessionStateSection),
LifecycleStatus = GetValue(manifest, LifecycleStatusSection, LifecycleStatus.Production)
};
extensionDescriptor.Features = GetFeaturesForExtension(manifest, extensionDescriptor);
return extensionDescriptor;
}
private ExtensionDescriptor GetExtensionDescriptor(string locationPath, string extensionId, string extensionType, string manifestPath, bool manifestIsOptional) {
return _cacheManager.Get(manifestPath, true, context => {
if (!DisableMonitoring) {
Logger.Debug("Monitoring virtual path \"{0}\"", manifestPath);
context.Monitor(_webSiteFolder.WhenPathChanges(manifestPath));
}
var manifestText = _webSiteFolder.ReadFile(manifestPath);
if (manifestText == null) {
if (manifestIsOptional) {
manifestText = string.Format("Id: {0}", extensionId);
}
else {
return null;
}
}
return GetDescriptorForExtension(locationPath, extensionId, extensionType, manifestText);
});
}
private static Dictionary<string, string> ParseManifest(string manifestText) {
var manifest = new Dictionary<string, string>();
using (StringReader reader = new StringReader(manifestText)) {
string line;
while ((line = reader.ReadLine()) != null) {
string[] field = line.Split(new[] { ":" }, 2, StringSplitOptions.None);
int fieldLength = field.Length;
if (fieldLength != 2)
continue;
for (int i = 0; i < fieldLength; i++) {
field[i] = field[i].Trim();
}
switch (field[0].ToLowerInvariant()) {
case NameSection:
manifest.Add(NameSection, field[1]);
break;
case PathSection:
manifest.Add(PathSection, field[1]);
break;
case DescriptionSection:
manifest.Add(DescriptionSection, field[1]);
break;
case VersionSection:
manifest.Add(VersionSection, field[1]);
break;
case OrchardVersionSection:
manifest.Add(OrchardVersionSection, field[1]);
break;
case AuthorSection:
manifest.Add(AuthorSection, field[1]);
break;
case WebsiteSection:
manifest.Add(WebsiteSection, field[1]);
break;
case TagsSection:
manifest.Add(TagsSection, field[1]);
break;
case AntiForgerySection:
manifest.Add(AntiForgerySection, field[1]);
break;
case ZonesSection:
manifest.Add(ZonesSection, field[1]);
break;
case BaseThemeSection:
manifest.Add(BaseThemeSection, field[1]);
break;
case DependenciesSection:
manifest.Add(DependenciesSection, field[1]);
break;
case CategorySection:
manifest.Add(CategorySection, field[1]);
break;
case FeatureDescriptionSection:
manifest.Add(FeatureDescriptionSection, field[1]);
break;
case FeatureNameSection:
manifest.Add(FeatureNameSection, field[1]);
break;
case PrioritySection:
manifest.Add(PrioritySection, field[1]);
break;
case SessionStateSection:
manifest.Add(SessionStateSection, field[1]);
break;
case LifecycleStatusSection:
manifest.Add(LifecycleStatusSection, field[1]);
break;
case FeaturesSection:
manifest.Add(FeaturesSection, reader.ReadToEnd());
break;
}
}
}
return manifest;
}
private static IEnumerable<FeatureDescriptor> GetFeaturesForExtension(IDictionary<string, string> manifest, ExtensionDescriptor extensionDescriptor) {
var featureDescriptors = new List<FeatureDescriptor>();
// Default feature
FeatureDescriptor defaultFeature = new FeatureDescriptor {
Id = extensionDescriptor.Id,
Name = GetValue(manifest, FeatureNameSection) ?? extensionDescriptor.Name,
Priority = GetValue(manifest, PrioritySection) != null ? int.Parse(GetValue(manifest, PrioritySection)) : 0,
Description = GetValue(manifest, FeatureDescriptionSection) ?? GetValue(manifest, DescriptionSection) ?? string.Empty,
Dependencies = ParseFeatureDependenciesEntry(GetValue(manifest, DependenciesSection)),
Extension = extensionDescriptor,
Category = GetValue(manifest, CategorySection)
};
featureDescriptors.Add(defaultFeature);
// Remaining features
string featuresText = GetValue(manifest, FeaturesSection);
if (featuresText != null) {
FeatureDescriptor featureDescriptor = null;
using (StringReader reader = new StringReader(featuresText)) {
string line;
while ((line = reader.ReadLine()) != null) {
if (IsFeatureDeclaration(line)) {
if (featureDescriptor != null) {
if (!featureDescriptor.Equals(defaultFeature)) {
featureDescriptors.Add(featureDescriptor);
}
featureDescriptor = null;
}
string[] featureDeclaration = line.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
string featureDescriptorId = featureDeclaration[0].Trim();
if (String.Equals(featureDescriptorId, extensionDescriptor.Id, StringComparison.OrdinalIgnoreCase)) {
featureDescriptor = defaultFeature;
featureDescriptor.Name = extensionDescriptor.Name;
}
else {
featureDescriptor = new FeatureDescriptor {
Id = featureDescriptorId,
Extension = extensionDescriptor
};
}
}
else if (IsFeatureFieldDeclaration(line)) {
if (featureDescriptor != null) {
string[] featureField = line.Split(new[] { ":" }, 2, StringSplitOptions.None);
int featureFieldLength = featureField.Length;
if (featureFieldLength != 2)
continue;
for (int i = 0; i < featureFieldLength; i++) {
featureField[i] = featureField[i].Trim();
}
switch (featureField[0].ToLowerInvariant()) {
case NameSection:
featureDescriptor.Name = featureField[1];
break;
case DescriptionSection:
featureDescriptor.Description = featureField[1];
break;
case CategorySection:
featureDescriptor.Category = featureField[1];
break;
case PrioritySection:
featureDescriptor.Priority = int.Parse(featureField[1]);
break;
case DependenciesSection:
featureDescriptor.Dependencies = ParseFeatureDependenciesEntry(featureField[1]);
break;
}
}
else {
string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id);
throw new ArgumentException(message);
}
}
else {
string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id);
throw new ArgumentException(message);
}
}
if (featureDescriptor != null && !featureDescriptor.Equals(defaultFeature))
featureDescriptors.Add(featureDescriptor);
}
}
return featureDescriptors;
}
private static bool IsFeatureFieldDeclaration(string line) {
if (line.StartsWith("\t\t") ||
line.StartsWith("\t ") ||
line.StartsWith(" ") ||
line.StartsWith(" \t"))
return true;
return false;
}
private static bool IsFeatureDeclaration(string line) {
int lineLength = line.Length;
if (line.StartsWith("\t") && lineLength >= 2) {
return !Char.IsWhiteSpace(line[1]);
}
if (line.StartsWith(" ") && lineLength >= 5)
return !Char.IsWhiteSpace(line[4]);
return false;
}
private static IEnumerable<string> ParseFeatureDependenciesEntry(string dependenciesEntry) {
if (string.IsNullOrEmpty(dependenciesEntry))
return Enumerable.Empty<string>();
var dependencies = new List<string>();
foreach (var s in dependenciesEntry.Split(',')) {
dependencies.Add(s.Trim());
}
return dependencies;
}
private static string GetValue(IDictionary<string, string> fields, string key) {
string value;
return fields.TryGetValue(key, out value) ? value : null;
}
private static T GetValue<T>(IDictionary<string, string> fields, string key, T defaultValue = default(T)) {
var value = GetValue(fields, key);
return String.IsNullOrWhiteSpace(value) ? defaultValue : XmlHelper.Parse<T>(value);
}
}
}
| |
// $ANTLR 3.1.3 Mar 18, 2009 10:09:25 TT\\Template.g 2009-06-12 20:20:15
// The variable 'variable' is assigned but its value is never used.
#pragma warning disable 168, 219
// Unreachable code detected.
#pragma warning disable 162
using System;
using Antlr.Runtime;
using IList = System.Collections.IList;
using ArrayList = System.Collections.ArrayList;
using Stack = Antlr.Runtime.Collections.StackList;
using Antlr.Runtime.Tree;
namespace TT
{
public partial class TemplateParser : Parser
{
public static readonly string[] tokenNames = new string[]
{
"<invalid>",
"<EOR>",
"<DOWN>",
"<UP>",
"GET",
"SET",
"PRINT",
"DOCUMENT",
"WS",
"TSTART",
"TSTOP",
"QUOTE",
"SQUOTE",
"ILITERAL",
"LITERAL",
"CALL",
"DEFAULT",
"INSERT",
"PROCESS",
"INCLUDE",
"WRAPPER",
"BLOCK",
"FOREACH",
"WHILE",
"IF",
"UNLESS",
"ELSIF",
"ELSE",
"SWITCH",
"CASE",
"MACRO",
"FILTER",
"USE",
"PERL",
"RAWPERL",
"TRY",
"THROW",
"CATCH",
"FINAL",
"NEXT",
"LAST",
"RETURN",
"STOP",
"TAGS",
"COMMENTS",
"END",
"IN",
"ID",
"NUMBER",
"DECIMAL",
"ADD",
"SUB",
"MULT",
"DIV",
"ASSIGN",
"EQUAL",
"CHAR",
"'GET'",
"'SET'"
};
public const int WHILE = 23;
public const int CASE = 29;
public const int CHAR = 56;
public const int RAWPERL = 34;
public const int SUB = 51;
public const int ID = 47;
public const int EOF = -1;
public const int TSTART = 9;
public const int IF = 24;
public const int QUOTE = 11;
public const int TSTOP = 10;
public const int T__57 = 57;
public const int FINAL = 38;
public const int T__58 = 58;
public const int IN = 46;
public const int COMMENTS = 44;
public const int INSERT = 17;
public const int DOCUMENT = 7;
public const int EQUAL = 55;
public const int INCLUDE = 19;
public const int RETURN = 41;
public const int GET = 4;
public const int NEXT = 39;
public const int LAST = 40;
public const int UNLESS = 25;
public const int ILITERAL = 13;
public const int ADD = 50;
public const int SWITCH = 28;
public const int DEFAULT = 16;
public const int ELSE = 27;
public const int NUMBER = 48;
public const int TAGS = 43;
public const int STOP = 42;
public const int LITERAL = 14;
public const int SET = 5;
public const int MULT = 52;
public const int SQUOTE = 12;
public const int WRAPPER = 20;
public const int PRINT = 6;
public const int TRY = 35;
public const int PERL = 33;
public const int WS = 8;
public const int DECIMAL = 49;
public const int BLOCK = 21;
public const int ASSIGN = 54;
public const int FILTER = 31;
public const int FOREACH = 22;
public const int CALL = 15;
public const int ELSIF = 26;
public const int USE = 32;
public const int DIV = 53;
public const int END = 45;
public const int PROCESS = 18;
public const int CATCH = 37;
public const int MACRO = 30;
public const int THROW = 36;
// delegates
// delegators
public TemplateParser(ITokenStream input)
: this(input, new RecognizerSharedState()) {
}
public TemplateParser(ITokenStream input, RecognizerSharedState state)
: base(input, state) {
InitializeCyclicDFAs();
}
protected ITreeAdaptor adaptor = new CommonTreeAdaptor();
public ITreeAdaptor TreeAdaptor
{
get { return this.adaptor; }
set {
this.adaptor = value;
}
}
override public string[] TokenNames {
get { return TemplateParser.tokenNames; }
}
override public string GrammarFileName {
get { return "TT\\Template.g"; }
}
public class document_return : ParserRuleReturnScope
{
private CommonTree tree;
override public object Tree
{
get { return tree; }
set { tree = (CommonTree) value; }
}
};
// $ANTLR start "document"
// TT\\Template.g:74:1: document : ( block )* -> ^( DOCUMENT ( block )* ) ;
public TemplateParser.document_return document() // throws RecognitionException [1]
{
TemplateParser.document_return retval = new TemplateParser.document_return();
retval.Start = input.LT(1);
CommonTree root_0 = null;
TemplateParser.block_return block1 = default(TemplateParser.block_return);
RewriteRuleSubtreeStream stream_block = new RewriteRuleSubtreeStream(adaptor,"rule block");
try
{
// TT\\Template.g:75:2: ( ( block )* -> ^( DOCUMENT ( block )* ) )
// TT\\Template.g:75:4: ( block )*
{
// TT\\Template.g:75:4: ( block )*
do
{
int alt1 = 2;
int LA1_0 = input.LA(1);
if ( (LA1_0 == TSTART) )
{
alt1 = 1;
}
switch (alt1)
{
case 1 :
// TT\\Template.g:75:4: block
{
PushFollow(FOLLOW_block_in_document485);
block1 = block();
state.followingStackPointer--;
stream_block.Add(block1.Tree);
}
break;
default:
goto loop1;
}
} while (true);
loop1:
; // Stops C# compiler whining that label 'loop1' has no statements
// AST REWRITE
// elements: block
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 75:11: -> ^( DOCUMENT ( block )* )
{
// TT\\Template.g:75:14: ^( DOCUMENT ( block )* )
{
CommonTree root_1 = (CommonTree)adaptor.GetNilNode();
root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(DOCUMENT, "DOCUMENT"), root_1);
// TT\\Template.g:75:25: ( block )*
while ( stream_block.HasNext() )
{
adaptor.AddChild(root_1, stream_block.NextTree());
}
stream_block.Reset();
adaptor.AddChild(root_0, root_1);
}
}
retval.Tree = root_0;retval.Tree = root_0;
}
retval.Stop = input.LT(-1);
retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);
}
catch (RecognitionException re)
{
ReportError(re);
Recover(input,re);
// Conversion of the second argument necessary, but harmless
retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);
}
finally
{
}
return retval;
}
// $ANTLR end "document"
public class block_return : ParserRuleReturnScope
{
private CommonTree tree;
override public object Tree
{
get { return tree; }
set { tree = (CommonTree) value; }
}
};
// $ANTLR start "block"
// TT\\Template.g:78:1: block : TSTART statement TSTOP ;
public TemplateParser.block_return block() // throws RecognitionException [1]
{
TemplateParser.block_return retval = new TemplateParser.block_return();
retval.Start = input.LT(1);
CommonTree root_0 = null;
IToken TSTART2 = null;
IToken TSTOP4 = null;
TemplateParser.statement_return statement3 = default(TemplateParser.statement_return);
CommonTree TSTART2_tree=null;
CommonTree TSTOP4_tree=null;
try
{
// TT\\Template.g:79:2: ( TSTART statement TSTOP )
// TT\\Template.g:79:4: TSTART statement TSTOP
{
root_0 = (CommonTree)adaptor.GetNilNode();
TSTART2=(IToken)Match(input,TSTART,FOLLOW_TSTART_in_block506);
PushFollow(FOLLOW_statement_in_block509);
statement3 = statement();
state.followingStackPointer--;
adaptor.AddChild(root_0, statement3.Tree);
TSTOP4=(IToken)Match(input,TSTOP,FOLLOW_TSTOP_in_block511);
}
retval.Stop = input.LT(-1);
retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);
}
catch (RecognitionException re)
{
ReportError(re);
Recover(input,re);
// Conversion of the second argument necessary, but harmless
retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);
}
finally
{
}
return retval;
}
// $ANTLR end "block"
public class statement_return : ParserRuleReturnScope
{
private CommonTree tree;
override public object Tree
{
get { return tree; }
set { tree = (CommonTree) value; }
}
};
// $ANTLR start "statement"
// TT\\Template.g:82:1: statement : ( getExpr | setExpr | defaultExpr | ifStatement | forEachLoop );
public TemplateParser.statement_return statement() // throws RecognitionException [1]
{
TemplateParser.statement_return retval = new TemplateParser.statement_return();
retval.Start = input.LT(1);
CommonTree root_0 = null;
TemplateParser.getExpr_return getExpr5 = default(TemplateParser.getExpr_return);
TemplateParser.setExpr_return setExpr6 = default(TemplateParser.setExpr_return);
TemplateParser.defaultExpr_return defaultExpr7 = default(TemplateParser.defaultExpr_return);
TemplateParser.ifStatement_return ifStatement8 = default(TemplateParser.ifStatement_return);
TemplateParser.forEachLoop_return forEachLoop9 = default(TemplateParser.forEachLoop_return);
try
{
// TT\\Template.g:83:2: ( getExpr | setExpr | defaultExpr | ifStatement | forEachLoop )
int alt2 = 5;
switch ( input.LA(1) )
{
case ILITERAL:
case LITERAL:
case 57:
{
alt2 = 1;
}
break;
case ID:
{
int LA2_2 = input.LA(2);
if ( (LA2_2 == ASSIGN) )
{
alt2 = 2;
}
else if ( ((LA2_2 >= TSTART && LA2_2 <= TSTOP) || LA2_2 == END) )
{
alt2 = 1;
}
else
{
NoViableAltException nvae_d2s2 =
new NoViableAltException("", 2, 2, input);
throw nvae_d2s2;
}
}
break;
case 58:
{
alt2 = 2;
}
break;
case DEFAULT:
{
alt2 = 3;
}
break;
case IF:
{
alt2 = 4;
}
break;
case FOREACH:
{
alt2 = 5;
}
break;
default:
NoViableAltException nvae_d2s0 =
new NoViableAltException("", 2, 0, input);
throw nvae_d2s0;
}
switch (alt2)
{
case 1 :
// TT\\Template.g:83:4: getExpr
{
root_0 = (CommonTree)adaptor.GetNilNode();
PushFollow(FOLLOW_getExpr_in_statement524);
getExpr5 = getExpr();
state.followingStackPointer--;
adaptor.AddChild(root_0, getExpr5.Tree);
}
break;
case 2 :
// TT\\Template.g:84:4: setExpr
{
root_0 = (CommonTree)adaptor.GetNilNode();
PushFollow(FOLLOW_setExpr_in_statement529);
setExpr6 = setExpr();
state.followingStackPointer--;
adaptor.AddChild(root_0, setExpr6.Tree);
}
break;
case 3 :
// TT\\Template.g:85:4: defaultExpr
{
root_0 = (CommonTree)adaptor.GetNilNode();
PushFollow(FOLLOW_defaultExpr_in_statement534);
defaultExpr7 = defaultExpr();
state.followingStackPointer--;
adaptor.AddChild(root_0, defaultExpr7.Tree);
}
break;
case 4 :
// TT\\Template.g:86:4: ifStatement
{
root_0 = (CommonTree)adaptor.GetNilNode();
PushFollow(FOLLOW_ifStatement_in_statement539);
ifStatement8 = ifStatement();
state.followingStackPointer--;
adaptor.AddChild(root_0, ifStatement8.Tree);
}
break;
case 5 :
// TT\\Template.g:87:4: forEachLoop
{
root_0 = (CommonTree)adaptor.GetNilNode();
PushFollow(FOLLOW_forEachLoop_in_statement544);
forEachLoop9 = forEachLoop();
state.followingStackPointer--;
adaptor.AddChild(root_0, forEachLoop9.Tree);
}
break;
}
retval.Stop = input.LT(-1);
retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);
}
catch (RecognitionException re)
{
ReportError(re);
Recover(input,re);
// Conversion of the second argument necessary, but harmless
retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);
}
finally
{
}
return retval;
}
// $ANTLR end "statement"
public class ifStatement_return : ParserRuleReturnScope
{
private CommonTree tree;
override public object Tree
{
get { return tree; }
set { tree = (CommonTree) value; }
}
};
// $ANTLR start "ifStatement"
// TT\\Template.g:90:1: ifStatement : IF ID ( TSTOP )? ( TSTART )? statement ( TSTOP )? ( TSTART )? END -> ^( IF ID statement ) ;
public TemplateParser.ifStatement_return ifStatement() // throws RecognitionException [1]
{
TemplateParser.ifStatement_return retval = new TemplateParser.ifStatement_return();
retval.Start = input.LT(1);
CommonTree root_0 = null;
IToken IF10 = null;
IToken ID11 = null;
IToken TSTOP12 = null;
IToken TSTART13 = null;
IToken TSTOP15 = null;
IToken TSTART16 = null;
IToken END17 = null;
TemplateParser.statement_return statement14 = default(TemplateParser.statement_return);
CommonTree IF10_tree=null;
CommonTree ID11_tree=null;
CommonTree TSTOP12_tree=null;
CommonTree TSTART13_tree=null;
CommonTree TSTOP15_tree=null;
CommonTree TSTART16_tree=null;
CommonTree END17_tree=null;
RewriteRuleTokenStream stream_TSTOP = new RewriteRuleTokenStream(adaptor,"token TSTOP");
RewriteRuleTokenStream stream_ID = new RewriteRuleTokenStream(adaptor,"token ID");
RewriteRuleTokenStream stream_END = new RewriteRuleTokenStream(adaptor,"token END");
RewriteRuleTokenStream stream_IF = new RewriteRuleTokenStream(adaptor,"token IF");
RewriteRuleTokenStream stream_TSTART = new RewriteRuleTokenStream(adaptor,"token TSTART");
RewriteRuleSubtreeStream stream_statement = new RewriteRuleSubtreeStream(adaptor,"rule statement");
try
{
// TT\\Template.g:91:2: ( IF ID ( TSTOP )? ( TSTART )? statement ( TSTOP )? ( TSTART )? END -> ^( IF ID statement ) )
// TT\\Template.g:91:4: IF ID ( TSTOP )? ( TSTART )? statement ( TSTOP )? ( TSTART )? END
{
IF10=(IToken)Match(input,IF,FOLLOW_IF_in_ifStatement555);
stream_IF.Add(IF10);
ID11=(IToken)Match(input,ID,FOLLOW_ID_in_ifStatement557);
stream_ID.Add(ID11);
// TT\\Template.g:91:10: ( TSTOP )?
int alt3 = 2;
int LA3_0 = input.LA(1);
if ( (LA3_0 == TSTOP) )
{
alt3 = 1;
}
switch (alt3)
{
case 1 :
// TT\\Template.g:91:10: TSTOP
{
TSTOP12=(IToken)Match(input,TSTOP,FOLLOW_TSTOP_in_ifStatement559);
stream_TSTOP.Add(TSTOP12);
}
break;
}
// TT\\Template.g:91:17: ( TSTART )?
int alt4 = 2;
int LA4_0 = input.LA(1);
if ( (LA4_0 == TSTART) )
{
alt4 = 1;
}
switch (alt4)
{
case 1 :
// TT\\Template.g:91:17: TSTART
{
TSTART13=(IToken)Match(input,TSTART,FOLLOW_TSTART_in_ifStatement562);
stream_TSTART.Add(TSTART13);
}
break;
}
PushFollow(FOLLOW_statement_in_ifStatement565);
statement14 = statement();
state.followingStackPointer--;
stream_statement.Add(statement14.Tree);
// TT\\Template.g:91:35: ( TSTOP )?
int alt5 = 2;
int LA5_0 = input.LA(1);
if ( (LA5_0 == TSTOP) )
{
alt5 = 1;
}
switch (alt5)
{
case 1 :
// TT\\Template.g:91:35: TSTOP
{
TSTOP15=(IToken)Match(input,TSTOP,FOLLOW_TSTOP_in_ifStatement567);
stream_TSTOP.Add(TSTOP15);
}
break;
}
// TT\\Template.g:91:42: ( TSTART )?
int alt6 = 2;
int LA6_0 = input.LA(1);
if ( (LA6_0 == TSTART) )
{
alt6 = 1;
}
switch (alt6)
{
case 1 :
// TT\\Template.g:91:42: TSTART
{
TSTART16=(IToken)Match(input,TSTART,FOLLOW_TSTART_in_ifStatement570);
stream_TSTART.Add(TSTART16);
}
break;
}
END17=(IToken)Match(input,END,FOLLOW_END_in_ifStatement573);
stream_END.Add(END17);
// AST REWRITE
// elements: statement, ID, IF
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 91:54: -> ^( IF ID statement )
{
// TT\\Template.g:91:57: ^( IF ID statement )
{
CommonTree root_1 = (CommonTree)adaptor.GetNilNode();
root_1 = (CommonTree)adaptor.BecomeRoot(stream_IF.NextNode(), root_1);
adaptor.AddChild(root_1, stream_ID.NextNode());
adaptor.AddChild(root_1, stream_statement.NextTree());
adaptor.AddChild(root_0, root_1);
}
}
retval.Tree = root_0;retval.Tree = root_0;
}
retval.Stop = input.LT(-1);
retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);
}
catch (RecognitionException re)
{
ReportError(re);
Recover(input,re);
// Conversion of the second argument necessary, but harmless
retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);
}
finally
{
}
return retval;
}
// $ANTLR end "ifStatement"
public class forEachLoop_return : ParserRuleReturnScope
{
private CommonTree tree;
override public object Tree
{
get { return tree; }
set { tree = (CommonTree) value; }
}
};
// $ANTLR start "forEachLoop"
// TT\\Template.g:94:1: forEachLoop : FOREACH ID IN ID ( TSTOP )? ( TSTART )? statement ( TSTOP )? ( TSTART )? END -> ^( FOREACH ID ID statement ) ;
public TemplateParser.forEachLoop_return forEachLoop() // throws RecognitionException [1]
{
TemplateParser.forEachLoop_return retval = new TemplateParser.forEachLoop_return();
retval.Start = input.LT(1);
CommonTree root_0 = null;
IToken FOREACH18 = null;
IToken ID19 = null;
IToken IN20 = null;
IToken ID21 = null;
IToken TSTOP22 = null;
IToken TSTART23 = null;
IToken TSTOP25 = null;
IToken TSTART26 = null;
IToken END27 = null;
TemplateParser.statement_return statement24 = default(TemplateParser.statement_return);
CommonTree FOREACH18_tree=null;
CommonTree ID19_tree=null;
CommonTree IN20_tree=null;
CommonTree ID21_tree=null;
CommonTree TSTOP22_tree=null;
CommonTree TSTART23_tree=null;
CommonTree TSTOP25_tree=null;
CommonTree TSTART26_tree=null;
CommonTree END27_tree=null;
RewriteRuleTokenStream stream_TSTOP = new RewriteRuleTokenStream(adaptor,"token TSTOP");
RewriteRuleTokenStream stream_FOREACH = new RewriteRuleTokenStream(adaptor,"token FOREACH");
RewriteRuleTokenStream stream_IN = new RewriteRuleTokenStream(adaptor,"token IN");
RewriteRuleTokenStream stream_ID = new RewriteRuleTokenStream(adaptor,"token ID");
RewriteRuleTokenStream stream_END = new RewriteRuleTokenStream(adaptor,"token END");
RewriteRuleTokenStream stream_TSTART = new RewriteRuleTokenStream(adaptor,"token TSTART");
RewriteRuleSubtreeStream stream_statement = new RewriteRuleSubtreeStream(adaptor,"rule statement");
try
{
// TT\\Template.g:95:2: ( FOREACH ID IN ID ( TSTOP )? ( TSTART )? statement ( TSTOP )? ( TSTART )? END -> ^( FOREACH ID ID statement ) )
// TT\\Template.g:95:4: FOREACH ID IN ID ( TSTOP )? ( TSTART )? statement ( TSTOP )? ( TSTART )? END
{
FOREACH18=(IToken)Match(input,FOREACH,FOLLOW_FOREACH_in_forEachLoop594);
stream_FOREACH.Add(FOREACH18);
ID19=(IToken)Match(input,ID,FOLLOW_ID_in_forEachLoop596);
stream_ID.Add(ID19);
IN20=(IToken)Match(input,IN,FOLLOW_IN_in_forEachLoop598);
stream_IN.Add(IN20);
ID21=(IToken)Match(input,ID,FOLLOW_ID_in_forEachLoop600);
stream_ID.Add(ID21);
// TT\\Template.g:95:21: ( TSTOP )?
int alt7 = 2;
int LA7_0 = input.LA(1);
if ( (LA7_0 == TSTOP) )
{
alt7 = 1;
}
switch (alt7)
{
case 1 :
// TT\\Template.g:95:21: TSTOP
{
TSTOP22=(IToken)Match(input,TSTOP,FOLLOW_TSTOP_in_forEachLoop602);
stream_TSTOP.Add(TSTOP22);
}
break;
}
// TT\\Template.g:95:28: ( TSTART )?
int alt8 = 2;
int LA8_0 = input.LA(1);
if ( (LA8_0 == TSTART) )
{
alt8 = 1;
}
switch (alt8)
{
case 1 :
// TT\\Template.g:95:28: TSTART
{
TSTART23=(IToken)Match(input,TSTART,FOLLOW_TSTART_in_forEachLoop605);
stream_TSTART.Add(TSTART23);
}
break;
}
PushFollow(FOLLOW_statement_in_forEachLoop608);
statement24 = statement();
state.followingStackPointer--;
stream_statement.Add(statement24.Tree);
// TT\\Template.g:95:46: ( TSTOP )?
int alt9 = 2;
int LA9_0 = input.LA(1);
if ( (LA9_0 == TSTOP) )
{
alt9 = 1;
}
switch (alt9)
{
case 1 :
// TT\\Template.g:95:46: TSTOP
{
TSTOP25=(IToken)Match(input,TSTOP,FOLLOW_TSTOP_in_forEachLoop610);
stream_TSTOP.Add(TSTOP25);
}
break;
}
// TT\\Template.g:95:53: ( TSTART )?
int alt10 = 2;
int LA10_0 = input.LA(1);
if ( (LA10_0 == TSTART) )
{
alt10 = 1;
}
switch (alt10)
{
case 1 :
// TT\\Template.g:95:53: TSTART
{
TSTART26=(IToken)Match(input,TSTART,FOLLOW_TSTART_in_forEachLoop613);
stream_TSTART.Add(TSTART26);
}
break;
}
END27=(IToken)Match(input,END,FOLLOW_END_in_forEachLoop616);
stream_END.Add(END27);
// AST REWRITE
// elements: ID, statement, ID, FOREACH
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 95:65: -> ^( FOREACH ID ID statement )
{
// TT\\Template.g:95:68: ^( FOREACH ID ID statement )
{
CommonTree root_1 = (CommonTree)adaptor.GetNilNode();
root_1 = (CommonTree)adaptor.BecomeRoot(stream_FOREACH.NextNode(), root_1);
adaptor.AddChild(root_1, stream_ID.NextNode());
adaptor.AddChild(root_1, stream_ID.NextNode());
adaptor.AddChild(root_1, stream_statement.NextTree());
adaptor.AddChild(root_0, root_1);
}
}
retval.Tree = root_0;retval.Tree = root_0;
}
retval.Stop = input.LT(-1);
retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);
}
catch (RecognitionException re)
{
ReportError(re);
Recover(input,re);
// Conversion of the second argument necessary, but harmless
retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);
}
finally
{
}
return retval;
}
// $ANTLR end "forEachLoop"
public class getExpr_return : ParserRuleReturnScope
{
private CommonTree tree;
override public object Tree
{
get { return tree; }
set { tree = (CommonTree) value; }
}
};
// $ANTLR start "getExpr"
// TT\\Template.g:98:1: getExpr : ( ( 'GET' )? ID -> ^( GET ID ) | ( 'GET' )? LITERAL -> ^( GET LITERAL ) | ( 'GET' )? ILITERAL -> ^( GET ILITERAL ) );
public TemplateParser.getExpr_return getExpr() // throws RecognitionException [1]
{
TemplateParser.getExpr_return retval = new TemplateParser.getExpr_return();
retval.Start = input.LT(1);
CommonTree root_0 = null;
IToken string_literal28 = null;
IToken ID29 = null;
IToken string_literal30 = null;
IToken LITERAL31 = null;
IToken string_literal32 = null;
IToken ILITERAL33 = null;
CommonTree string_literal28_tree=null;
CommonTree ID29_tree=null;
CommonTree string_literal30_tree=null;
CommonTree LITERAL31_tree=null;
CommonTree string_literal32_tree=null;
CommonTree ILITERAL33_tree=null;
RewriteRuleTokenStream stream_LITERAL = new RewriteRuleTokenStream(adaptor,"token LITERAL");
RewriteRuleTokenStream stream_57 = new RewriteRuleTokenStream(adaptor,"token 57");
RewriteRuleTokenStream stream_ID = new RewriteRuleTokenStream(adaptor,"token ID");
RewriteRuleTokenStream stream_ILITERAL = new RewriteRuleTokenStream(adaptor,"token ILITERAL");
try
{
// TT\\Template.g:99:2: ( ( 'GET' )? ID -> ^( GET ID ) | ( 'GET' )? LITERAL -> ^( GET LITERAL ) | ( 'GET' )? ILITERAL -> ^( GET ILITERAL ) )
int alt14 = 3;
switch ( input.LA(1) )
{
case 57:
{
switch ( input.LA(2) )
{
case ID:
{
alt14 = 1;
}
break;
case ILITERAL:
{
alt14 = 3;
}
break;
case LITERAL:
{
alt14 = 2;
}
break;
default:
NoViableAltException nvae_d14s1 =
new NoViableAltException("", 14, 1, input);
throw nvae_d14s1;
}
}
break;
case ID:
{
alt14 = 1;
}
break;
case LITERAL:
{
alt14 = 2;
}
break;
case ILITERAL:
{
alt14 = 3;
}
break;
default:
NoViableAltException nvae_d14s0 =
new NoViableAltException("", 14, 0, input);
throw nvae_d14s0;
}
switch (alt14)
{
case 1 :
// TT\\Template.g:99:4: ( 'GET' )? ID
{
// TT\\Template.g:99:4: ( 'GET' )?
int alt11 = 2;
int LA11_0 = input.LA(1);
if ( (LA11_0 == 57) )
{
alt11 = 1;
}
switch (alt11)
{
case 1 :
// TT\\Template.g:99:4: 'GET'
{
string_literal28=(IToken)Match(input,57,FOLLOW_57_in_getExpr639);
stream_57.Add(string_literal28);
}
break;
}
ID29=(IToken)Match(input,ID,FOLLOW_ID_in_getExpr642);
stream_ID.Add(ID29);
// AST REWRITE
// elements: ID
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 99:20: -> ^( GET ID )
{
// TT\\Template.g:99:23: ^( GET ID )
{
CommonTree root_1 = (CommonTree)adaptor.GetNilNode();
root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(GET, "GET"), root_1);
adaptor.AddChild(root_1, stream_ID.NextNode());
adaptor.AddChild(root_0, root_1);
}
}
retval.Tree = root_0;retval.Tree = root_0;
}
break;
case 2 :
// TT\\Template.g:100:4: ( 'GET' )? LITERAL
{
// TT\\Template.g:100:4: ( 'GET' )?
int alt12 = 2;
int LA12_0 = input.LA(1);
if ( (LA12_0 == 57) )
{
alt12 = 1;
}
switch (alt12)
{
case 1 :
// TT\\Template.g:100:4: 'GET'
{
string_literal30=(IToken)Match(input,57,FOLLOW_57_in_getExpr661);
stream_57.Add(string_literal30);
}
break;
}
LITERAL31=(IToken)Match(input,LITERAL,FOLLOW_LITERAL_in_getExpr664);
stream_LITERAL.Add(LITERAL31);
// AST REWRITE
// elements: LITERAL
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 100:20: -> ^( GET LITERAL )
{
// TT\\Template.g:100:23: ^( GET LITERAL )
{
CommonTree root_1 = (CommonTree)adaptor.GetNilNode();
root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(GET, "GET"), root_1);
adaptor.AddChild(root_1, stream_LITERAL.NextNode());
adaptor.AddChild(root_0, root_1);
}
}
retval.Tree = root_0;retval.Tree = root_0;
}
break;
case 3 :
// TT\\Template.g:101:4: ( 'GET' )? ILITERAL
{
// TT\\Template.g:101:4: ( 'GET' )?
int alt13 = 2;
int LA13_0 = input.LA(1);
if ( (LA13_0 == 57) )
{
alt13 = 1;
}
switch (alt13)
{
case 1 :
// TT\\Template.g:101:4: 'GET'
{
string_literal32=(IToken)Match(input,57,FOLLOW_57_in_getExpr678);
stream_57.Add(string_literal32);
}
break;
}
ILITERAL33=(IToken)Match(input,ILITERAL,FOLLOW_ILITERAL_in_getExpr681);
stream_ILITERAL.Add(ILITERAL33);
// AST REWRITE
// elements: ILITERAL
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 101:20: -> ^( GET ILITERAL )
{
// TT\\Template.g:101:23: ^( GET ILITERAL )
{
CommonTree root_1 = (CommonTree)adaptor.GetNilNode();
root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(GET, "GET"), root_1);
adaptor.AddChild(root_1, stream_ILITERAL.NextNode());
adaptor.AddChild(root_0, root_1);
}
}
retval.Tree = root_0;retval.Tree = root_0;
}
break;
}
retval.Stop = input.LT(-1);
retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);
}
catch (RecognitionException re)
{
ReportError(re);
Recover(input,re);
// Conversion of the second argument necessary, but harmless
retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);
}
finally
{
}
return retval;
}
// $ANTLR end "getExpr"
public class setExpr_return : ParserRuleReturnScope
{
private CommonTree tree;
override public object Tree
{
get { return tree; }
set { tree = (CommonTree) value; }
}
};
// $ANTLR start "setExpr"
// TT\\Template.g:104:1: setExpr : ( 'SET' )? ( assignment )+ -> ( ^( SET assignment ) )+ ;
public TemplateParser.setExpr_return setExpr() // throws RecognitionException [1]
{
TemplateParser.setExpr_return retval = new TemplateParser.setExpr_return();
retval.Start = input.LT(1);
CommonTree root_0 = null;
IToken string_literal34 = null;
TemplateParser.assignment_return assignment35 = default(TemplateParser.assignment_return);
CommonTree string_literal34_tree=null;
RewriteRuleTokenStream stream_58 = new RewriteRuleTokenStream(adaptor,"token 58");
RewriteRuleSubtreeStream stream_assignment = new RewriteRuleSubtreeStream(adaptor,"rule assignment");
try
{
// TT\\Template.g:105:2: ( ( 'SET' )? ( assignment )+ -> ( ^( SET assignment ) )+ )
// TT\\Template.g:105:4: ( 'SET' )? ( assignment )+
{
// TT\\Template.g:105:4: ( 'SET' )?
int alt15 = 2;
int LA15_0 = input.LA(1);
if ( (LA15_0 == 58) )
{
alt15 = 1;
}
switch (alt15)
{
case 1 :
// TT\\Template.g:105:4: 'SET'
{
string_literal34=(IToken)Match(input,58,FOLLOW_58_in_setExpr700);
stream_58.Add(string_literal34);
}
break;
}
// TT\\Template.g:105:11: ( assignment )+
int cnt16 = 0;
do
{
int alt16 = 2;
int LA16_0 = input.LA(1);
if ( (LA16_0 == ID) )
{
alt16 = 1;
}
switch (alt16)
{
case 1 :
// TT\\Template.g:105:12: assignment
{
PushFollow(FOLLOW_assignment_in_setExpr704);
assignment35 = assignment();
state.followingStackPointer--;
stream_assignment.Add(assignment35.Tree);
}
break;
default:
if ( cnt16 >= 1 ) goto loop16;
EarlyExitException eee16 =
new EarlyExitException(16, input);
throw eee16;
}
cnt16++;
} while (true);
loop16:
; // Stops C# compiler whining that label 'loop16' has no statements
// AST REWRITE
// elements: assignment
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 105:25: -> ( ^( SET assignment ) )+
{
if ( !(stream_assignment.HasNext()) ) {
throw new RewriteEarlyExitException();
}
while ( stream_assignment.HasNext() )
{
// TT\\Template.g:105:28: ^( SET assignment )
{
CommonTree root_1 = (CommonTree)adaptor.GetNilNode();
root_1 = (CommonTree)adaptor.BecomeRoot((CommonTree)adaptor.Create(SET, "SET"), root_1);
adaptor.AddChild(root_1, stream_assignment.NextTree());
adaptor.AddChild(root_0, root_1);
}
}
stream_assignment.Reset();
}
retval.Tree = root_0;retval.Tree = root_0;
}
retval.Stop = input.LT(-1);
retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);
}
catch (RecognitionException re)
{
ReportError(re);
Recover(input,re);
// Conversion of the second argument necessary, but harmless
retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);
}
finally
{
}
return retval;
}
// $ANTLR end "setExpr"
public class defaultExpr_return : ParserRuleReturnScope
{
private CommonTree tree;
override public object Tree
{
get { return tree; }
set { tree = (CommonTree) value; }
}
};
// $ANTLR start "defaultExpr"
// TT\\Template.g:108:1: defaultExpr : DEFAULT ( assignment )+ -> ( ^( DEFAULT assignment ) )+ ;
public TemplateParser.defaultExpr_return defaultExpr() // throws RecognitionException [1]
{
TemplateParser.defaultExpr_return retval = new TemplateParser.defaultExpr_return();
retval.Start = input.LT(1);
CommonTree root_0 = null;
IToken DEFAULT36 = null;
TemplateParser.assignment_return assignment37 = default(TemplateParser.assignment_return);
CommonTree DEFAULT36_tree=null;
RewriteRuleTokenStream stream_DEFAULT = new RewriteRuleTokenStream(adaptor,"token DEFAULT");
RewriteRuleSubtreeStream stream_assignment = new RewriteRuleSubtreeStream(adaptor,"rule assignment");
try
{
// TT\\Template.g:109:2: ( DEFAULT ( assignment )+ -> ( ^( DEFAULT assignment ) )+ )
// TT\\Template.g:109:4: DEFAULT ( assignment )+
{
DEFAULT36=(IToken)Match(input,DEFAULT,FOLLOW_DEFAULT_in_defaultExpr726);
stream_DEFAULT.Add(DEFAULT36);
// TT\\Template.g:109:12: ( assignment )+
int cnt17 = 0;
do
{
int alt17 = 2;
int LA17_0 = input.LA(1);
if ( (LA17_0 == ID) )
{
alt17 = 1;
}
switch (alt17)
{
case 1 :
// TT\\Template.g:109:13: assignment
{
PushFollow(FOLLOW_assignment_in_defaultExpr729);
assignment37 = assignment();
state.followingStackPointer--;
stream_assignment.Add(assignment37.Tree);
}
break;
default:
if ( cnt17 >= 1 ) goto loop17;
EarlyExitException eee17 =
new EarlyExitException(17, input);
throw eee17;
}
cnt17++;
} while (true);
loop17:
; // Stops C# compiler whining that label 'loop17' has no statements
// AST REWRITE
// elements: DEFAULT, assignment
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 109:26: -> ( ^( DEFAULT assignment ) )+
{
if ( !(stream_DEFAULT.HasNext() || stream_assignment.HasNext()) ) {
throw new RewriteEarlyExitException();
}
while ( stream_DEFAULT.HasNext() || stream_assignment.HasNext() )
{
// TT\\Template.g:109:29: ^( DEFAULT assignment )
{
CommonTree root_1 = (CommonTree)adaptor.GetNilNode();
root_1 = (CommonTree)adaptor.BecomeRoot(stream_DEFAULT.NextNode(), root_1);
adaptor.AddChild(root_1, stream_assignment.NextTree());
adaptor.AddChild(root_0, root_1);
}
}
stream_DEFAULT.Reset();
stream_assignment.Reset();
}
retval.Tree = root_0;retval.Tree = root_0;
}
retval.Stop = input.LT(-1);
retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);
}
catch (RecognitionException re)
{
ReportError(re);
Recover(input,re);
// Conversion of the second argument necessary, but harmless
retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);
}
finally
{
}
return retval;
}
// $ANTLR end "defaultExpr"
public class assignment_return : ParserRuleReturnScope
{
private CommonTree tree;
override public object Tree
{
get { return tree; }
set { tree = (CommonTree) value; }
}
};
// $ANTLR start "assignment"
// TT\\Template.g:112:1: assignment : ( ID ASSIGN LITERAL -> ID LITERAL | ID ASSIGN NUMBER -> ID NUMBER | ID ASSIGN DECIMAL -> ID DECIMAL );
public TemplateParser.assignment_return assignment() // throws RecognitionException [1]
{
TemplateParser.assignment_return retval = new TemplateParser.assignment_return();
retval.Start = input.LT(1);
CommonTree root_0 = null;
IToken ID38 = null;
IToken ASSIGN39 = null;
IToken LITERAL40 = null;
IToken ID41 = null;
IToken ASSIGN42 = null;
IToken NUMBER43 = null;
IToken ID44 = null;
IToken ASSIGN45 = null;
IToken DECIMAL46 = null;
CommonTree ID38_tree=null;
CommonTree ASSIGN39_tree=null;
CommonTree LITERAL40_tree=null;
CommonTree ID41_tree=null;
CommonTree ASSIGN42_tree=null;
CommonTree NUMBER43_tree=null;
CommonTree ID44_tree=null;
CommonTree ASSIGN45_tree=null;
CommonTree DECIMAL46_tree=null;
RewriteRuleTokenStream stream_LITERAL = new RewriteRuleTokenStream(adaptor,"token LITERAL");
RewriteRuleTokenStream stream_DECIMAL = new RewriteRuleTokenStream(adaptor,"token DECIMAL");
RewriteRuleTokenStream stream_ID = new RewriteRuleTokenStream(adaptor,"token ID");
RewriteRuleTokenStream stream_NUMBER = new RewriteRuleTokenStream(adaptor,"token NUMBER");
RewriteRuleTokenStream stream_ASSIGN = new RewriteRuleTokenStream(adaptor,"token ASSIGN");
try
{
// TT\\Template.g:113:2: ( ID ASSIGN LITERAL -> ID LITERAL | ID ASSIGN NUMBER -> ID NUMBER | ID ASSIGN DECIMAL -> ID DECIMAL )
int alt18 = 3;
int LA18_0 = input.LA(1);
if ( (LA18_0 == ID) )
{
int LA18_1 = input.LA(2);
if ( (LA18_1 == ASSIGN) )
{
switch ( input.LA(3) )
{
case LITERAL:
{
alt18 = 1;
}
break;
case NUMBER:
{
alt18 = 2;
}
break;
case DECIMAL:
{
alt18 = 3;
}
break;
default:
NoViableAltException nvae_d18s2 =
new NoViableAltException("", 18, 2, input);
throw nvae_d18s2;
}
}
else
{
NoViableAltException nvae_d18s1 =
new NoViableAltException("", 18, 1, input);
throw nvae_d18s1;
}
}
else
{
NoViableAltException nvae_d18s0 =
new NoViableAltException("", 18, 0, input);
throw nvae_d18s0;
}
switch (alt18)
{
case 1 :
// TT\\Template.g:113:4: ID ASSIGN LITERAL
{
ID38=(IToken)Match(input,ID,FOLLOW_ID_in_assignment751);
stream_ID.Add(ID38);
ASSIGN39=(IToken)Match(input,ASSIGN,FOLLOW_ASSIGN_in_assignment753);
stream_ASSIGN.Add(ASSIGN39);
LITERAL40=(IToken)Match(input,LITERAL,FOLLOW_LITERAL_in_assignment755);
stream_LITERAL.Add(LITERAL40);
// AST REWRITE
// elements: ID, LITERAL
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 113:22: -> ID LITERAL
{
adaptor.AddChild(root_0, stream_ID.NextNode());
adaptor.AddChild(root_0, stream_LITERAL.NextNode());
}
retval.Tree = root_0;retval.Tree = root_0;
}
break;
case 2 :
// TT\\Template.g:114:4: ID ASSIGN NUMBER
{
ID41=(IToken)Match(input,ID,FOLLOW_ID_in_assignment766);
stream_ID.Add(ID41);
ASSIGN42=(IToken)Match(input,ASSIGN,FOLLOW_ASSIGN_in_assignment768);
stream_ASSIGN.Add(ASSIGN42);
NUMBER43=(IToken)Match(input,NUMBER,FOLLOW_NUMBER_in_assignment770);
stream_NUMBER.Add(NUMBER43);
// AST REWRITE
// elements: NUMBER, ID
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 114:22: -> ID NUMBER
{
adaptor.AddChild(root_0, stream_ID.NextNode());
adaptor.AddChild(root_0, stream_NUMBER.NextNode());
}
retval.Tree = root_0;retval.Tree = root_0;
}
break;
case 3 :
// TT\\Template.g:115:4: ID ASSIGN DECIMAL
{
ID44=(IToken)Match(input,ID,FOLLOW_ID_in_assignment782);
stream_ID.Add(ID44);
ASSIGN45=(IToken)Match(input,ASSIGN,FOLLOW_ASSIGN_in_assignment784);
stream_ASSIGN.Add(ASSIGN45);
DECIMAL46=(IToken)Match(input,DECIMAL,FOLLOW_DECIMAL_in_assignment786);
stream_DECIMAL.Add(DECIMAL46);
// AST REWRITE
// elements: DECIMAL, ID
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.Tree = root_0;
RewriteRuleSubtreeStream stream_retval = new RewriteRuleSubtreeStream(adaptor, "rule retval", retval!=null ? retval.Tree : null);
root_0 = (CommonTree)adaptor.GetNilNode();
// 115:22: -> ID DECIMAL
{
adaptor.AddChild(root_0, stream_ID.NextNode());
adaptor.AddChild(root_0, stream_DECIMAL.NextNode());
}
retval.Tree = root_0;retval.Tree = root_0;
}
break;
}
retval.Stop = input.LT(-1);
retval.Tree = (CommonTree)adaptor.RulePostProcessing(root_0);
adaptor.SetTokenBoundaries(retval.Tree, (IToken) retval.Start, (IToken) retval.Stop);
}
catch (RecognitionException re)
{
ReportError(re);
Recover(input,re);
// Conversion of the second argument necessary, but harmless
retval.Tree = (CommonTree)adaptor.ErrorNode(input, (IToken) retval.Start, input.LT(-1), re);
}
finally
{
}
return retval;
}
// $ANTLR end "assignment"
// Delegated rules
private void InitializeCyclicDFAs()
{
}
public static readonly BitSet FOLLOW_block_in_document485 = new BitSet(new ulong[]{0x0000000000000202UL});
public static readonly BitSet FOLLOW_TSTART_in_block506 = new BitSet(new ulong[]{0x0600800001416000UL});
public static readonly BitSet FOLLOW_statement_in_block509 = new BitSet(new ulong[]{0x0000000000000400UL});
public static readonly BitSet FOLLOW_TSTOP_in_block511 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_getExpr_in_statement524 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_setExpr_in_statement529 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_defaultExpr_in_statement534 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_ifStatement_in_statement539 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_forEachLoop_in_statement544 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_IF_in_ifStatement555 = new BitSet(new ulong[]{0x0000800000000000UL});
public static readonly BitSet FOLLOW_ID_in_ifStatement557 = new BitSet(new ulong[]{0x0600800001416600UL});
public static readonly BitSet FOLLOW_TSTOP_in_ifStatement559 = new BitSet(new ulong[]{0x0600800001416200UL});
public static readonly BitSet FOLLOW_TSTART_in_ifStatement562 = new BitSet(new ulong[]{0x0600800001416000UL});
public static readonly BitSet FOLLOW_statement_in_ifStatement565 = new BitSet(new ulong[]{0x0000200000000600UL});
public static readonly BitSet FOLLOW_TSTOP_in_ifStatement567 = new BitSet(new ulong[]{0x0000200000000200UL});
public static readonly BitSet FOLLOW_TSTART_in_ifStatement570 = new BitSet(new ulong[]{0x0000200000000000UL});
public static readonly BitSet FOLLOW_END_in_ifStatement573 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_FOREACH_in_forEachLoop594 = new BitSet(new ulong[]{0x0000800000000000UL});
public static readonly BitSet FOLLOW_ID_in_forEachLoop596 = new BitSet(new ulong[]{0x0000400000000000UL});
public static readonly BitSet FOLLOW_IN_in_forEachLoop598 = new BitSet(new ulong[]{0x0000800000000000UL});
public static readonly BitSet FOLLOW_ID_in_forEachLoop600 = new BitSet(new ulong[]{0x0600800001416600UL});
public static readonly BitSet FOLLOW_TSTOP_in_forEachLoop602 = new BitSet(new ulong[]{0x0600800001416200UL});
public static readonly BitSet FOLLOW_TSTART_in_forEachLoop605 = new BitSet(new ulong[]{0x0600800001416000UL});
public static readonly BitSet FOLLOW_statement_in_forEachLoop608 = new BitSet(new ulong[]{0x0000200000000600UL});
public static readonly BitSet FOLLOW_TSTOP_in_forEachLoop610 = new BitSet(new ulong[]{0x0000200000000200UL});
public static readonly BitSet FOLLOW_TSTART_in_forEachLoop613 = new BitSet(new ulong[]{0x0000200000000000UL});
public static readonly BitSet FOLLOW_END_in_forEachLoop616 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_57_in_getExpr639 = new BitSet(new ulong[]{0x0000800000000000UL});
public static readonly BitSet FOLLOW_ID_in_getExpr642 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_57_in_getExpr661 = new BitSet(new ulong[]{0x0000000000004000UL});
public static readonly BitSet FOLLOW_LITERAL_in_getExpr664 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_57_in_getExpr678 = new BitSet(new ulong[]{0x0000000000002000UL});
public static readonly BitSet FOLLOW_ILITERAL_in_getExpr681 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_58_in_setExpr700 = new BitSet(new ulong[]{0x0400800000000000UL});
public static readonly BitSet FOLLOW_assignment_in_setExpr704 = new BitSet(new ulong[]{0x0400800000000002UL});
public static readonly BitSet FOLLOW_DEFAULT_in_defaultExpr726 = new BitSet(new ulong[]{0x0400800000000000UL});
public static readonly BitSet FOLLOW_assignment_in_defaultExpr729 = new BitSet(new ulong[]{0x0400800000000002UL});
public static readonly BitSet FOLLOW_ID_in_assignment751 = new BitSet(new ulong[]{0x0040000000000000UL});
public static readonly BitSet FOLLOW_ASSIGN_in_assignment753 = new BitSet(new ulong[]{0x0000000000004000UL});
public static readonly BitSet FOLLOW_LITERAL_in_assignment755 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_ID_in_assignment766 = new BitSet(new ulong[]{0x0040000000000000UL});
public static readonly BitSet FOLLOW_ASSIGN_in_assignment768 = new BitSet(new ulong[]{0x0001000000000000UL});
public static readonly BitSet FOLLOW_NUMBER_in_assignment770 = new BitSet(new ulong[]{0x0000000000000002UL});
public static readonly BitSet FOLLOW_ID_in_assignment782 = new BitSet(new ulong[]{0x0040000000000000UL});
public static readonly BitSet FOLLOW_ASSIGN_in_assignment784 = new BitSet(new ulong[]{0x0002000000000000UL});
public static readonly BitSet FOLLOW_DECIMAL_in_assignment786 = new BitSet(new ulong[]{0x0000000000000002UL});
}
}
| |
using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Preferences;
using Plugin.Settings.Abstractions;
namespace Plugin.Settings
{
/// <summary>
/// Main Implementation for ISettings
/// </summary>
public class SettingsImplementation : ISettings
{
private readonly object locker = new object();
/// <summary>
/// Gets the current value or the default that you specify.
/// </summary>
/// <typeparam name="T">Vaue of t (bool, int, float, long, string)</typeparam>
/// <param name="key">Key for settings</param>
/// <param name="defaultValue">default value if not set</param>
/// <returns>Value or default</returns>
public T GetValueOrDefault<T>(string key, T defaultValue = default(T))
{
lock (locker)
{
using (var sharedPreferences = PreferenceManager.GetDefaultSharedPreferences(Application.Context))
{
return GetValueOrDefaultCore(sharedPreferences, key, defaultValue);
}
}
}
private T GetValueOrDefaultCore<T>(ISharedPreferences sharedPreferences, string key, T defaultValue)
{
Type typeOf = typeof(T);
if (typeOf.IsGenericType && typeOf.GetGenericTypeDefinition() == typeof(Nullable<>))
{
typeOf = Nullable.GetUnderlyingType(typeOf);
}
object value = null;
var typeCode = Type.GetTypeCode(typeOf);
bool resave = false;
switch (typeCode)
{
case TypeCode.Decimal:
//Android doesn't have decimal in shared prefs so get string and convert
var savedDecimal = string.Empty;
try
{
savedDecimal = sharedPreferences.GetString(key, string.Empty);
}
catch (Java.Lang.ClassCastException)
{
Console.WriteLine("Settings 1.5 change, have to remove key.");
try
{
Console.WriteLine("Attempting to get old value.");
savedDecimal =
sharedPreferences.GetLong(key,
(long)Convert.ToDecimal(defaultValue, System.Globalization.CultureInfo.InvariantCulture))
.ToString();
Console.WriteLine("Old value has been parsed and will be updated and saved.");
}
catch (Java.Lang.ClassCastException)
{
Console.WriteLine("Could not parse old value, will be lost.");
}
Remove("key");
resave = true;
}
if (string.IsNullOrWhiteSpace(savedDecimal))
value = Convert.ToDecimal(defaultValue, System.Globalization.CultureInfo.InvariantCulture);
else
value = Convert.ToDecimal(savedDecimal, System.Globalization.CultureInfo.InvariantCulture);
if (resave)
AddOrUpdateValue(key, value);
break;
case TypeCode.Boolean:
value = sharedPreferences.GetBoolean(key, Convert.ToBoolean(defaultValue));
break;
case TypeCode.Int64:
value =
(Int64)
sharedPreferences.GetLong(key,
(long)Convert.ToInt64(defaultValue, System.Globalization.CultureInfo.InvariantCulture));
break;
case TypeCode.String:
value = sharedPreferences.GetString(key, Convert.ToString(defaultValue));
break;
case TypeCode.Double:
//Android doesn't have double, so must get as string and parse.
var savedDouble = string.Empty;
try
{
savedDouble = sharedPreferences.GetString(key, string.Empty);
}
catch (Java.Lang.ClassCastException)
{
Console.WriteLine("Settings 1.5 change, have to remove key.");
try
{
Console.WriteLine("Attempting to get old value.");
savedDouble =
sharedPreferences.GetLong(key,
(long)Convert.ToDouble(defaultValue, System.Globalization.CultureInfo.InvariantCulture))
.ToString();
Console.WriteLine("Old value has been parsed and will be updated and saved.");
}
catch (Java.Lang.ClassCastException)
{
Console.WriteLine("Could not parse old value, will be lost.");
}
Remove(key);
resave = true;
}
if (string.IsNullOrWhiteSpace(savedDouble))
value = Convert.ToDouble(defaultValue, System.Globalization.CultureInfo.InvariantCulture);
else
value = Convert.ToDouble(savedDouble, System.Globalization.CultureInfo.InvariantCulture);
if (resave)
AddOrUpdateValue(key, value);
break;
case TypeCode.Int32:
value = sharedPreferences.GetInt(key,
Convert.ToInt32(defaultValue, System.Globalization.CultureInfo.InvariantCulture));
break;
case TypeCode.Single:
value = sharedPreferences.GetFloat(key,
Convert.ToSingle(defaultValue, System.Globalization.CultureInfo.InvariantCulture));
break;
case TypeCode.DateTime:
if (sharedPreferences.Contains(key))
{
var ticks = sharedPreferences.GetLong(key, 0);
if (ticks >= 0)
{
//Old value, stored before update to UTC values
value = new DateTime(ticks);
}
else
{
//New value, UTC
value = new DateTime(-ticks, DateTimeKind.Utc);
}
}
else
{
return defaultValue;
}
break;
default:
if (defaultValue is Guid)
{
var outGuid = Guid.Empty;
Guid.TryParse(sharedPreferences.GetString(key, Guid.Empty.ToString()), out outGuid);
value = outGuid;
}
else
{
throw new ArgumentException(string.Format("Value of type {0} is not supported.", value.GetType().Name));
}
break;
}
return null != value ? (T)value : defaultValue;
}
/// <summary>
/// Adds or updates a value
/// </summary>
/// <param name="key">key to update</param>
/// <param name="value">value to set</param>
/// <returns>True if added or update and you need to save</returns>
public bool AddOrUpdateValue<T>(string key, T value)
{
Type typeOf = typeof(T);
if (typeOf.IsGenericType && typeOf.GetGenericTypeDefinition() == typeof(Nullable<>))
{
typeOf = Nullable.GetUnderlyingType(typeOf);
}
var typeCode = Type.GetTypeCode(typeOf);
return AddOrUpdateValue(key, value, typeCode);
}
private bool AddOrUpdateValue(string key, object value, TypeCode typeCode)
{
lock (locker)
{
using (var sharedPreferences = PreferenceManager.GetDefaultSharedPreferences(Application.Context))
{
using (var sharedPreferencesEditor = sharedPreferences.Edit())
{
switch (typeCode)
{
case TypeCode.Decimal:
sharedPreferencesEditor.PutString(key,
Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
break;
case TypeCode.Boolean:
sharedPreferencesEditor.PutBoolean(key, Convert.ToBoolean(value));
break;
case TypeCode.Int64:
sharedPreferencesEditor.PutLong(key,
(long)Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture));
break;
case TypeCode.String:
sharedPreferencesEditor.PutString(key, Convert.ToString(value));
break;
case TypeCode.Double:
sharedPreferencesEditor.PutString(key,
Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
break;
case TypeCode.Int32:
sharedPreferencesEditor.PutInt(key,
Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture));
break;
case TypeCode.Single:
sharedPreferencesEditor.PutFloat(key,
Convert.ToSingle(value, System.Globalization.CultureInfo.InvariantCulture));
break;
case TypeCode.DateTime:
sharedPreferencesEditor.PutLong(key, -(Convert.ToDateTime(value)).ToUniversalTime().Ticks);
break;
default:
if (value is Guid)
{
sharedPreferencesEditor.PutString(key, ((Guid)value).ToString());
}
else
{
throw new ArgumentException(string.Format("Value of type {0} is not supported.",
value.GetType().Name));
}
break;
}
sharedPreferencesEditor.Commit();
}
}
}
return true;
}
/// <summary>
/// Removes a desired key from the settings
/// </summary>
/// <param name="key">Key for setting</param>
public void Remove(string key)
{
lock (locker)
{
using (var sharedPreferences = PreferenceManager.GetDefaultSharedPreferences(Application.Context))
{
using (var sharedPreferencesEditor = sharedPreferences.Edit())
{
sharedPreferencesEditor.Remove(key);
sharedPreferencesEditor.Commit();
}
}
}
}
}
}
| |
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
public class PostEffectsBase : MonoBehaviour
{
protected bool supportHDRTextures = true;
protected bool supportDX11 = false;
protected bool isSupported = true;
protected Material CheckShaderAndCreateMaterial ( Shader s, Material m2Create)
{
if (!s)
{
Debug.Log("Missing shader in " + ToString ());
enabled = false;
return null;
}
if (s.isSupported && m2Create && m2Create.shader == s)
return m2Create;
if (!s.isSupported)
{
NotSupported ();
Debug.Log("The shader " + s.ToString() + " on effect "+ToString()+" is not supported on this platform!");
return null;
}
else
{
m2Create = new Material (s);
m2Create.hideFlags = HideFlags.DontSave;
if (m2Create)
return m2Create;
else return null;
}
}
protected Material CreateMaterial (Shader s, Material m2Create)
{
if (!s)
{
Debug.Log ("Missing shader in " + ToString ());
return null;
}
if (m2Create && (m2Create.shader == s) && (s.isSupported))
return m2Create;
if (!s.isSupported)
{
return null;
}
else
{
m2Create = new Material (s);
m2Create.hideFlags = HideFlags.DontSave;
if (m2Create)
return m2Create;
else return null;
}
}
void OnEnable ()
{
isSupported = true;
}
protected bool CheckSupport ()
{
return CheckSupport (false);
}
public virtual bool CheckResources ()
{
//Debug.LogWarning ("CheckResources () for " + ToString() + " should be overwritten.");
return isSupported;
}
protected void Start ()
{
CheckResources ();
}
protected bool CheckSupport (bool needDepth)
{
isSupported = true;
supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf);
supportDX11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders;
if (!SystemInfo.supportsImageEffects || !SystemInfo.supportsRenderTextures)
{
NotSupported ();
return false;
}
if (needDepth && !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth))
{
NotSupported ();
return false;
}
if (needDepth)
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
return true;
}
protected bool CheckSupport (bool needDepth, bool needHdr)
{
if (!CheckSupport(needDepth))
return false;
if (needHdr && !supportHDRTextures)
{
NotSupported ();
return false;
}
return true;
}
public bool Dx11Support ()
{
return supportDX11;
}
protected void ReportAutoDisable ()
{
Debug.LogWarning ("The image effect " + ToString() + " has been disabled as it's not supported on the current platform.");
}
// deprecated but needed for old effects to survive upgrading
bool CheckShader (Shader s)
{
Debug.Log("The shader " + s.ToString () + " on effect "+ ToString () + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package.");
if (!s.isSupported)
{
NotSupported ();
return false;
}
else
{
return false;
}
}
protected void NotSupported ()
{
enabled = false;
isSupported = false;
return;
}
protected void DrawBorder (RenderTexture dest, Material material)
{
float x1;
float x2;
float y1;
float y2;
RenderTexture.active = dest;
bool invertY = true; // source.texelSize.y < 0.0ff;
// Set up the simple Matrix
GL.PushMatrix();
GL.LoadOrtho();
for (int i = 0; i < material.passCount; i++)
{
material.SetPass(i);
float y1_; float y2_;
if (invertY)
{
y1_ = 1.0f; y2_ = 0.0f;
}
else
{
y1_ = 0.0f; y2_ = 1.0f;
}
// left
x1 = 0.0f;
x2 = 0.0f + 1.0f/(dest.width*1.0f);
y1 = 0.0f;
y2 = 1.0f;
GL.Begin(GL.QUADS);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// right
x1 = 1.0f - 1.0f/(dest.width*1.0f);
x2 = 1.0f;
y1 = 0.0f;
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// top
x1 = 0.0f;
x2 = 1.0f;
y1 = 0.0f;
y2 = 0.0f + 1.0f/(dest.height*1.0f);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// bottom
x1 = 0.0f;
x2 = 1.0f;
y1 = 1.0f - 1.0f/(dest.height*1.0f);
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
GL.End();
}
GL.PopMatrix();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace FileHelpers.WizardApp
{
[Designer(typeof (FixedWidthDesigner.FileBrowserDesigner))]
public partial class FixedWidthDesigner : UserControl
{
private class FileBrowserDesigner : ControlDesigner
{
protected override void PostFilterProperties(System.Collections.IDictionary properties)
{
base.PostFilterProperties(properties);
properties.Remove("Font");
}
}
public void AddColumn(ColumnInfo column) {}
internal void RecalculatePositions()
{
Graphics g = this.CreateGraphics();
CalculateCharWidth(g);
int x = mTextLeft;
foreach (ColumnInfo column in mColumns) {
column.mFileBrowser = this;
column.mControlLeft = x;
column.mControlWith = column.Width*mCharWidth;
x += column.mControlWith;
}
}
private ToolStripMenuItem cmdShowInfo;
private ToolStripSeparator toolStripSeparator1;
private ToolStripMenuItem cmdDeleteColumn;
private ToolStripSeparator toolStripSeparator2;
private ToolStripTextBox txtColumnName;
private int mTextTop = 25;
private int mFontSize = 16;
public int FontSize
{
get { return mFontSize; }
set
{
mFontSize = value;
mCharWidth = -1;
this.Font = new System.Drawing.Font("Courier New", mFontSize, System.Drawing.FontStyle.Regular);
this.Invalidate();
}
}
public int TextTop
{
get { return mTextTop; }
set
{
mTextTop = value;
this.Invalidate();
}
}
private int mTextLeft = 10;
public int TextLeft
{
get { return mTextLeft; }
set
{
mTextLeft = value;
this.Invalidate();
}
}
private List<ColumnInfo> mColumns = new List<ColumnInfo>();
public List<ColumnInfo> Columns
{
get { return mColumns; }
}
private Color ColorEvenRule = Color.DarkOrange;
private Color ColorOddRule = Color.RoyalBlue;
private Color ColorOverRule = Color.Black;
private Color ColorOverColumn = Color.LightGoldenrodYellow;
private Pen PenEvenRule;
private Pen PenOddRule;
private Pen PenOverRule;
private int mCharWidth = -1;
private ContextMenuStrip cmnuOptions;
private int mOverColumn = -1;
protected override void OnPaint(PaintEventArgs e)
{
CalculateCharWidth(e.Graphics);
int width;
int left = mTextLeft;
int rulesTop = mTextTop - 2;
int rulesNumberTop = rulesTop - 15;
bool even = true;
for (int i = 0; i < mColumns.Count; i++) {
width = mCharWidth*mColumns[i].Width;
Brush backBrush;
if (i == mOverColumn)
backBrush = new SolidBrush(ColorOverColumn);
else
backBrush = new SolidBrush(mColumns[i].Color);
e.Graphics.FillRectangle(backBrush, left, 0, width, this.Height - 1);
backBrush.Dispose();
Pen rulePen;
rulePen = even
? PenEvenRule
: PenOddRule;
even = !even;
if (i == mOverColumn)
rulePen = PenOverRule;
e.Graphics.DrawLine(rulePen, left + 1, rulesTop, left + width - 1, rulesTop);
Brush widthBrush;
if (i == mOverColumn)
widthBrush = new SolidBrush(Color.Black);
else
widthBrush = Brushes.DarkRed;
e.Graphics.DrawString(mColumns[i].Width.ToString(),
this.Font,
widthBrush,
left + width/2 - 10,
rulesNumberTop);
left += width;
}
Brush b = new SolidBrush(this.ForeColor);
e.Graphics.DrawString(Text, this.Font, b, mTextLeft, mTextTop);
b.Dispose();
int closer = CalculateCloser(Control.MousePosition.X);
if (closer >= 0) {
ColumnInfo col = mColumns[closer];
if (closer > 0) {
if (col.CloserToLeft(Control.MousePosition.X))
col = mColumns[closer - 1];
}
Pen p = new Pen(Color.Red, 3);
e.Graphics.DrawLine(p,
col.mControlLeft + col.mControlWith,
0,
col.mControlLeft + col.mControlWith,
this.Height);
p.Dispose();
}
}
private void CalculateCharWidth(Graphics g)
{
if (mCharWidth == -1)
mCharWidth = (int) TextRenderer.MeasureText("m", this.Font).Width - 4;
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (mCloserColumn != null) {
if (mCloserToLeft) {
if (mCloserLeftColumn == null)
return;
int ant = mCloserLeftColumn.Width;
int newWidth = mOriginalLeftWidth + ((e.X - mCloserInitialX)/mCharWidth);
if (newWidth < 1)
newWidth = 1;
mCloserLeftColumn.Width = newWidth;
if (ant != mCloserLeftColumn.Width)
this.Invalidate();
}
else {
int ant = mCloserColumn.Width;
int newWidth = mOriginalWidth + ((e.X - mCloserInitialX)/mCharWidth);
if (newWidth < 1)
newWidth = 1;
mCloserColumn.Width = newWidth;
if (ant != mCloserColumn.Width)
this.Invalidate();
}
}
else {
int oldCol = mOverColumn;
mOverColumn = CalculateColumn(e.X);
int oldClose = mCloserEdge;
mCloserEdge = CalculateCloser(e.X);
if (mCloserEdge > 0 &&
mColumns[mCloserEdge].CloserToLeft(e.X))
mCloserEdge--;
if (oldCol != mOverColumn ||
oldClose != mCloserEdge)
this.Invalidate();
}
}
private int mCloserEdge;
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
int closer = CalculateCloser(e.X);
mCloserColumn = mColumns[closer];
if (e.Button == MouseButtons.Right) {
mPosMouseDown = e.Location;
cmnuOptions.Show(this, e.Location);
txtColumnName.Text = mCloserColumn.Name;
}
else if (e.Button == MouseButtons.Left) {
if (closer > 0) {
mCloserLeftColumn = mColumns[closer - 1];
mOriginalLeftWidth = mCloserLeftColumn.Width;
}
mCloserToLeft = mCloserColumn.CloserToLeft(e.X);
mCloserInitialX = e.X;
mOriginalWidth = mCloserColumn.Width;
this.Invalidate();
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
mCloserColumn = null;
mCloserLeftColumn = null;
this.Invalidate();
}
private int CalculateCloser(int x)
{
int res = -1;
int dist = int.MaxValue;
for (int i = 0; i < mColumns.Count; i++) {
int currDist = mColumns[i].CalculateDistance(x);
if (currDist < dist) {
dist = currDist;
res = i;
}
}
return res;
}
private ColumnInfo mCloserColumn = null;
private bool mCloserToLeft = false;
private int mCloserInitialX = -1;
private int mOriginalWidth = -1;
private int mOriginalLeftWidth = -1;
private ColumnInfo mCloserLeftColumn = null;
private Point mPosMouseDown;
private int CalculateColumn(int x)
{
if (x < mTextLeft)
return -1;
for (int i = 0; i < mColumns.Count; i++) {
if (mColumns[i].ContainsPoint(x))
return i;
}
return -1;
}
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
mCharWidth = -1;
}
public FixedWidthDesigner()
{
InitializeComponent();
mColumns.AddRange(new ColumnInfo[] {
new ColumnInfo(11),
new ColumnInfo(38),
new ColumnInfo(72 - 50),
new ColumnInfo(110 - 72),
new ColumnInfo(151 - 110),
new ColumnInfo(169 - 151),
new ColumnInfo(15)
});
PenEvenRule = new Pen(ColorEvenRule);
PenOddRule = new Pen(ColorOddRule);
PenOverRule = new Pen(ColorOverRule);
this.Font = new System.Drawing.Font("Courier New",
mFontSize,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Pixel,
((byte) (0)));
this.VerticalScroll.Enabled = true;
this.DoubleBuffered = true;
RecalculatePositions();
}
private void cmdDeleteColumn_Click(object sender, EventArgs e)
{
int closer = CalculateCloser(MousePosition.X);
if (closer == -1)
return;
mColumns.RemoveAt(closer);
RecalculatePositions();
this.Invalidate();
}
private void addColumnHereToolStripMenuItem_Click(object sender, EventArgs e)
{
//ColumnInfo colAnte = null;
//foreach (var col in Columns.ToArray())
//{
// if (col.ContainsPoint(mPosMouseDown.X))
// {
// Columns.Insert(Columns.IndexOf(col), new ColumnInfo());
// }
// mPosMouseDown
//}
}
}
public class ColumnInfo
{
internal FixedWidthDesigner mFileBrowser;
private int mWidth;
public int Width
{
get { return mWidth; }
set
{
if (mWidth == value)
return;
mWidth = value;
if (mFileBrowser != null)
mFileBrowser.RecalculatePositions();
}
}
private string mName = string.Empty;
public string Name
{
get { return mName; }
set { mName = value; }
}
private Color mColor;
public Color Color
{
get { return mColor; }
set { mColor = value; }
}
public static bool even = false;
public ColumnInfo()
{
if (even)
Color = Color.AliceBlue;
else
Color = Color.White;
even = !even;
}
public ColumnInfo(int width)
: this()
{
this.Width = width;
}
internal int mControlLeft;
internal int mControlWith;
internal bool ContainsPoint(int x)
{
return x >= mControlLeft && x < mControlLeft + mControlWith;
}
internal int CalculateDistance(int x)
{
return Math.Min(Math.Abs(mControlLeft - x), Math.Abs((mControlWith + mControlLeft) - x));
}
internal bool CloserToLeft(int x)
{
if (Math.Abs(mControlLeft - x) < Math.Abs((mControlWith + mControlLeft) - x))
return true;
else
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace NLog.SourceCodeTests
{
/// <summary>
/// Source code tests.
/// </summary>
public class SourceCodeTests
{
private static readonly Regex ClassNameRegex = new Regex(@"^\s+(public |abstract |sealed |static |partial |internal )*\s*(class|interface|struct|enum)\s+(?<className>\w+)\b", RegexOptions.Compiled);
private static readonly Regex DelegateTypeRegex = new Regex(@"^ (public |internal )delegate .*\b(?<delegateType>\w+)\(", RegexOptions.Compiled);
private static List<string> _directoriesToVerify;
private readonly bool _verifyNamespaces;
private readonly IList<string> _fileNamesToIgnore;
private readonly string _rootDir;
private string _licenseFile;
private readonly string[] _licenseLines;
public SourceCodeTests()
{
_rootDir = FindRootDir();
_directoriesToVerify = GetAppSettingAsList("VerifyFiles.Paths");
_fileNamesToIgnore = GetAppSettingAsList("VerifyFiles.IgnoreFiles");
_verifyNamespaces = false; //off for now (april 2019) - so we could create folders and don't break stuff
if (_rootDir != null)
{
_licenseLines = File.ReadAllLines(_licenseFile);
}
else
{
throw new Exception("root not found (where LICENSE.txt is located)");
}
}
private static List<string> GetAppSettingAsList(string setting)
{
return ConfigurationManager.AppSettings[setting].Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
}
/// <summary>
/// Find source root by finding LICENSE.txt
/// </summary>
private string FindRootDir()
{
var dir = ConfigurationManager.AppSettings["rootdir"];
dir = Path.GetFullPath(dir);
while (dir != null)
{
_licenseFile = Path.Combine(dir, "LICENSE.txt");
if (File.Exists(_licenseFile))
{
break;
}
dir = Path.GetDirectoryName(dir);
}
return dir;
}
public bool VerifyFileHeaders()
{
var missing = FindFilesWithMissingHeaders().ToList();
return ReportErrors(missing, "Missing headers (copy them form other another file).");
}
private IEnumerable<string> FindFilesWithMissingHeaders()
{
foreach (string dir in _directoriesToVerify)
{
foreach (string file in Directory.GetFiles(Path.Combine(_rootDir, dir), "*.cs", SearchOption.AllDirectories))
{
if (ShouldIgnoreFileForVerify(file))
{
continue;
}
if (!VerifyFileHeader(file))
{
yield return file;
}
}
}
}
public bool VerifyNamespacesAndClassNames()
{
var errors = new List<string>();
foreach (string dir in _directoriesToVerify)
{
VerifyClassNames(Path.Combine(_rootDir, dir), Path.GetFileName(dir), errors);
}
return ReportErrors(errors, "Namespace or classname not in-sync with file name.");
}
bool ShouldIgnoreFileForVerify(string filePath)
{
string baseName = Path.GetFileName(filePath);
if (baseName == null || _fileNamesToIgnore.Contains(baseName))
{
return true;
}
if (baseName.IndexOf(".xaml", StringComparison.OrdinalIgnoreCase) >= 0)
{
return true;
}
if (baseName.IndexOf(".g.", StringComparison.OrdinalIgnoreCase) >= 0)
{
return true;
}
if (baseName.IndexOf(".designer.", StringComparison.OrdinalIgnoreCase) >= 0)
{
return true;
}
if (baseName == "ExtensionAttribute.cs")
{
return true;
}
if (baseName == "NUnitAdapter.cs")
{
return true;
}
if (baseName == "LocalizableAttribute.cs")
{
return true;
}
if (baseName == "Annotations.cs")
{
return true;
}
return false;
}
private bool VerifyFileHeader(string filePath)
{
if (FileInObjFolder(filePath))
{
//don't scan files in obj folder
return true;
}
using (StreamReader reader = File.OpenText(filePath))
{
for (int i = 0; i < _licenseLines.Length; ++i)
{
string line = reader.ReadLine();
string expected = "// " + _licenseLines[i];
if (line != expected)
{
return false;
}
}
return true;
}
}
private static bool FileInObjFolder(string path)
{
return path.Contains("/obj/") || path.Contains("\\obj\\")
|| path.StartsWith("obj/", StringComparison.InvariantCultureIgnoreCase) || path.StartsWith("obj\\", StringComparison.InvariantCultureIgnoreCase);
}
private void VerifyClassNames(string path, string expectedNamespace, List<string> errors)
{
if (FileInObjFolder(path))
{
return;
}
foreach (string filePath in Directory.GetFiles(path, "*.cs"))
{
if (ShouldIgnoreFileForVerify(filePath))
{
continue;
}
string expectedClassName = Path.GetFileNameWithoutExtension(filePath);
if (expectedClassName != null)
{
int p = expectedClassName.IndexOf('-');
if (p >= 0)
{
expectedClassName = expectedClassName.Substring(0, p);
}
var fileErrors = VerifySingleFile(filePath, expectedNamespace, expectedClassName);
errors.AddRange(fileErrors.Select(errorMessage => $"{filePath}:{errorMessage}"));
}
}
foreach (string dir in Directory.GetDirectories(path))
{
VerifyClassNames(dir, expectedNamespace + "." + Path.GetFileName(dir), errors);
}
}
///<summary>Verify classname and namespace in a file.</summary>
///<returns>errors</returns>
private IEnumerable<string> VerifySingleFile(string filePath, string expectedNamespace, string expectedClassName)
{
//ignore list
if (filePath != null && !filePath.EndsWith("nunit.cs", StringComparison.InvariantCultureIgnoreCase))
{
HashSet<string> classNames = new HashSet<string>();
using (StreamReader sr = File.OpenText(filePath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (_verifyNamespaces)
{
if (line.StartsWith("namespace ", StringComparison.Ordinal))
{
string ns = line.Substring(10);
if (expectedNamespace != ns)
{
yield return $"Invalid namespace: '{ns}' Expected: '{expectedNamespace}'";
}
}
}
Match match = ClassNameRegex.Match(line);
if (match.Success)
{
classNames.Add(match.Groups["className"].Value);
}
match = DelegateTypeRegex.Match(line);
if (match.Success)
{
classNames.Add(match.Groups["delegateType"].Value);
}
}
}
if (classNames.Count == 0)
{
//Console.WriteLine("No classes found in {0}", file);
//ignore, because of files not used in other projects
}
else if (!classNames.Contains(expectedClassName))
{
yield return $"Invalid class name. Expected '{expectedClassName}', actual: '{string.Join(",", classNames)}'";
}
}
}
private static bool ReportErrors(List<string> errors, string globalErrorMessage)
{
var count = errors.Count;
if (count == 0)
{
return true;
}
var fullMessage = $"{globalErrorMessage}\n{count} errors: \n -------- \n-{string.Join("\n- ", errors)} \n\n";
Console.Error.WriteLine(fullMessage);
return false;
}
}
}
| |
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Thinktecture.IO;
using Thinktecture.Net.Http.Headers;
// ReSharper disable InconsistentNaming
namespace Thinktecture.Net.Http
{
/// <summary>Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. </summary>
// ReSharper disable once PossibleInterfaceMemberAmbiguity
public interface IHttpClient : IHttpMessageInvoker, IAbstraction<HttpClient>
{
/// <summary>Gets the headers which should be sent with each request.</summary>
/// <returns>Returns <see cref="T:System.Net.Http.Headers.HttpRequestHeaders" />.The headers which should be sent with each request.</returns>
IHttpRequestHeaders DefaultRequestHeaders { get; }
/// <summary>Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.</summary>
/// <returns>Returns <see cref="T:System.Uri" />.The base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.</returns>
Uri? BaseAddress { get; set; }
/// <summary>Gets or sets the timespan to wait before the request times out.</summary>
/// <returns>Returns <see cref="T:System.TimeSpan" />.The timespan to wait before the request times out.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException">The timeout specified is less than or equal to zero and is not <see cref="F:System.Threading.Timeout.InfiniteTimeSpan" />.</exception>
/// <exception cref="T:System.InvalidOperationException">An operation has already been started on the current instance. </exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has been disposed.</exception>
TimeSpan Timeout { get; set; }
/// <summary>Gets or sets the maximum number of bytes to buffer when reading the response content.</summary>
/// <returns>Returns <see cref="T:System.Int32" />.The maximum number of bytes to buffer when reading the response content. The default value for this property is 2 gigabytes.</returns>
/// <exception cref="T:System.ArgumentOutOfRangeException">The size specified is less than or equal to zero.</exception>
/// <exception cref="T:System.InvalidOperationException">An operation has already been started on the current instance. </exception>
/// <exception cref="T:System.ObjectDisposedException">The current instance has been disposed. </exception>
long MaxResponseContentBufferSize { get; set; }
/// <summary>Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<string> GetStringAsync(string requestUri);
/// <summary>Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<string> GetStringAsync(Uri requestUri);
/// <summary>Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<byte[]> GetByteArrayAsync(string requestUri);
/// <summary>Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<byte[]> GetByteArrayAsync(Uri requestUri);
/// <summary>Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IStream> GetStreamAsync(string requestUri);
/// <summary>Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IStream> GetStreamAsync(Uri requestUri);
/// <summary>Send a GET request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> GetAsync(string requestUri);
/// <summary>Send a GET request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> GetAsync(Uri requestUri);
/// <summary>Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="completionOption">An HTTP completion option value that indicates when the operation should be considered completed.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption);
/// <summary>Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="completionOption">An HTTP completion option value that indicates when the operation should be considered completed.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption);
/// <summary>Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken);
/// <summary>Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken);
/// <summary>Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="completionOption">An HTTP completion option value that indicates when the operation should be considered completed.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken);
/// <summary>Send a GET request to the specified Uri with an HTTP completion option and a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="completionOption">An HTTP completion option value that indicates when the operation should be considered completed.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken);
/// <summary>Send a POST request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PostAsync(string requestUri, HttpContent content);
/// <summary>Send a POST request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PostAsync(string requestUri, IHttpContent content);
/// <summary>Send a POST request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PostAsync(Uri requestUri, HttpContent content);
/// <summary>Send a POST request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PostAsync(Uri requestUri, IHttpContent content);
/// <summary>Send a POST request with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PostAsync(string requestUri, HttpContent content, CancellationToken cancellationToken);
/// <summary>Send a POST request with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PostAsync(string requestUri, IHttpContent content, CancellationToken cancellationToken);
/// <summary>Send a POST request with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PostAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken);
/// <summary>Send a POST request with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PostAsync(Uri requestUri, IHttpContent content, CancellationToken cancellationToken);
/// <summary>Send a PUT request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PutAsync(string requestUri, HttpContent content);
/// <summary>Send a PUT request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PutAsync(string requestUri, IHttpContent content);
/// <summary>Send a PUT request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PutAsync(Uri requestUri, HttpContent content);
/// <summary>Send a PUT request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PutAsync(Uri requestUri, IHttpContent content);
/// <summary>Send a PUT request with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PutAsync(string requestUri, HttpContent content, CancellationToken cancellationToken);
/// <summary>Send a PUT request with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PutAsync(string requestUri, IHttpContent content, CancellationToken cancellationToken);
/// <summary>Send a PUT request with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PutAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken);
/// <summary>Send a PUT request with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="content">The HTTP request content sent to the server.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
Task<IHttpResponseMessage> PutAsync(Uri requestUri, IHttpContent content, CancellationToken cancellationToken);
/// <summary>Send a DELETE request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
/// <exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient" /> instance.</exception>
Task<IHttpResponseMessage> DeleteAsync(string requestUri);
/// <summary>Send a DELETE request to the specified Uri as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
/// <exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient" /> instance.</exception>
Task<IHttpResponseMessage> DeleteAsync(Uri requestUri);
/// <summary>Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
/// <exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient" /> instance.</exception>
Task<IHttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken);
/// <summary>Send a DELETE request to the specified Uri with a cancellation token as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="requestUri">The Uri the request is sent to.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="requestUri" /> was null.</exception>
/// <exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient" /> instance.</exception>
Task<IHttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken);
/// <summary>Send an HTTP request as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="request">The HTTP request message to send.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception>
/// <exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient" /> instance.</exception>
Task<IHttpResponseMessage> SendAsync(HttpRequestMessage request);
/// <summary>Send an HTTP request as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="request">The HTTP request message to send.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception>
/// <exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient" /> instance.</exception>
Task<IHttpResponseMessage> SendAsync(IHttpRequestMessage request);
/// <summary>Send an HTTP request as an asynchronous operation. </summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="request">The HTTP request message to send.</param>
/// <param name="completionOption">When the operation should complete (as soon as a response is available or after reading the whole response content).</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception>
/// <exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient" /> instance.</exception>
Task<IHttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption);
/// <summary>Send an HTTP request as an asynchronous operation. </summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="request">The HTTP request message to send.</param>
/// <param name="completionOption">When the operation should complete (as soon as a response is available or after reading the whole response content).</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception>
/// <exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient" /> instance.</exception>
Task<IHttpResponseMessage> SendAsync(IHttpRequestMessage request, HttpCompletionOption completionOption);
/// <summary>Send an HTTP request as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="request">The HTTP request message to send.</param>
/// <param name="completionOption">When the operation should complete (as soon as a response is available or after reading the whole response content).</param>
/// <param name="cancellationToken">The cancellation token to cancel operation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception>
/// <exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient" /> instance.</exception>
Task<IHttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken);
/// <summary>Send an HTTP request as an asynchronous operation.</summary>
/// <returns>Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.</returns>
/// <param name="request">The HTTP request message to send.</param>
/// <param name="completionOption">When the operation should complete (as soon as a response is available or after reading the whole response content).</param>
/// <param name="cancellationToken">The cancellation token to cancel operation.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="request" /> was null.</exception>
/// <exception cref="T:System.InvalidOperationException">The request message was already sent by the <see cref="T:System.Net.Http.HttpClient" /> instance.</exception>
Task<IHttpResponseMessage> SendAsync(IHttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken);
/// <summary>Cancel all pending requests on this instance.</summary>
void CancelPendingRequests();
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// A gRPC server.
/// </summary>
public class Server
{
/// <summary>
/// Pass this value as port to have the server choose an unused listening port for you.
/// </summary>
public const int PickUnusedPort = 0;
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>();
readonly GrpcEnvironment environment;
readonly List<ChannelOption> options;
readonly ServerSafeHandle handle;
readonly object myLock = new object();
readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>();
readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>();
bool startRequested;
bool shutdownRequested;
/// <summary>
/// Create a new server.
/// </summary>
/// <param name="options">Channel options.</param>
public Server(IEnumerable<ChannelOption> options = null)
{
this.environment = GrpcEnvironment.GetInstance();
this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>();
using (var channelArgs = ChannelOptions.CreateChannelArgs(this.options))
{
this.handle = ServerSafeHandle.NewServer(environment.CompletionQueue, channelArgs);
}
}
/// <summary>
/// Adds a service definition to the server. This is how you register
/// handlers for a service with the server.
/// Only call this before Start().
/// </summary>
public void AddServiceDefinition(ServerServiceDefinition serviceDefinition)
{
lock (myLock)
{
Preconditions.CheckState(!startRequested);
foreach (var entry in serviceDefinition.CallHandlers)
{
callHandlers.Add(entry.Key, entry.Value);
}
}
}
/// <summary>
/// Add a port on which server should listen.
/// Only call this before Start().
/// </summary>
/// <returns>The port on which server will be listening.</returns>
/// <param name="host">the host</param>
/// <param name="port">the port. If zero, an unused port is chosen automatically.</param>
public int AddPort(string host, int port, ServerCredentials credentials)
{
lock (myLock)
{
Preconditions.CheckNotNull(credentials);
Preconditions.CheckState(!startRequested);
var address = string.Format("{0}:{1}", host, port);
using (var nativeCredentials = credentials.ToNativeCredentials())
{
if (nativeCredentials != null)
{
return handle.AddSecurePort(address, nativeCredentials);
}
else
{
return handle.AddInsecurePort(address);
}
}
}
}
/// <summary>
/// Starts the server.
/// </summary>
public void Start()
{
lock (myLock)
{
Preconditions.CheckState(!startRequested);
startRequested = true;
handle.Start();
AllowOneRpc();
}
}
/// <summary>
/// Requests server shutdown and when there are no more calls being serviced,
/// cleans up used resources. The returned task finishes when shutdown procedure
/// is complete.
/// </summary>
public async Task ShutdownAsync()
{
lock (myLock)
{
Preconditions.CheckState(startRequested);
Preconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
handle.ShutdownAndNotify(HandleServerShutdown, environment);
await shutdownTcs.Task;
handle.Dispose();
}
/// <summary>
/// To allow awaiting termination of the server.
/// </summary>
public Task ShutdownTask
{
get
{
return shutdownTcs.Task;
}
}
/// <summary>
/// Requests server shutdown while cancelling all the in-progress calls.
/// The returned task finishes when shutdown procedure is complete.
/// </summary>
public async Task KillAsync()
{
lock (myLock)
{
Preconditions.CheckState(startRequested);
Preconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
handle.ShutdownAndNotify(HandleServerShutdown, environment);
handle.CancelAllCalls();
await shutdownTcs.Task;
handle.Dispose();
}
/// <summary>
/// Allows one new RPC call to be received by server.
/// </summary>
private void AllowOneRpc()
{
lock (myLock)
{
if (!shutdownRequested)
{
handle.RequestCall(HandleNewServerRpc, environment);
}
}
}
/// <summary>
/// Selects corresponding handler for given call and handles the call.
/// </summary>
private async Task HandleCallAsync(ServerRpcNew newRpc)
{
try
{
IServerCallHandler callHandler;
if (!callHandlers.TryGetValue(newRpc.Method, out callHandler))
{
callHandler = NoSuchMethodCallHandler.Instance;
}
await callHandler.HandleCall(newRpc, environment);
}
catch (Exception e)
{
Logger.Warning(e, "Exception while handling RPC.");
}
}
/// <summary>
/// Handles the native callback.
/// </summary>
private void HandleNewServerRpc(bool success, BatchContextSafeHandle ctx)
{
if (success)
{
ServerRpcNew newRpc = ctx.GetServerRpcNew();
// after server shutdown, the callback returns with null call
if (!newRpc.Call.IsInvalid)
{
Task.Run(async () => await HandleCallAsync(newRpc));
}
}
AllowOneRpc();
}
/// <summary>
/// Handles native callback.
/// </summary>
private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx)
{
shutdownTcs.SetResult(null);
}
}
}
| |
private string FKSelectName(ITable tbl,IForeignKey FK,string sAlias)
{
if(tbl.Name == FK.PrimaryTable.Name)return ChildName(FK) + ClassesName(tbl.Name);
//return ClassesName(tbl.Name) + "By" + ClassName(FK.PrimaryTable) + sAlias;
return ClassesName(tbl.Name) + "By" + ForeignKeyName(FK) + sAlias;
}
private string ForeignKeyName(IForeignKey FK)
{
string retval="";
string sep = "";
foreach(IColumn col in FK.ForeignColumns)
{
retval = retval + sep + ClassName(col.Name);
sep = "_And_";
}
return retval;
}
private string FKFieldName(IForeignKey fk)
{
string cName = ClassName( fk.ForeignTable );
string className=ClassName( fk.PrimaryTable );
if(className==cName)return ChildName(fk);
return ClassName( fk.ForeignTable );
}
private string FKFieldsName(IForeignKey fk)
{
string cName = ClassesName( fk.ForeignTable );
string className=ClassesName( fk.PrimaryTable );
if(className==cName)return ChildrenName(fk);
return cName;
}
private string FKClassesName(IForeignKey fk)
{
string cName = ClassesName( fk.ForeignTable );
string className=ClassesName( fk.PrimaryTable );
if(className==cName)return ChildName(fk) + ClassesName( fk.PrimaryTable );
return ClassName( fk.PrimaryTable ) + cName;
}
private string FKClassName(string className,IForeignKey fk)
{
string cName = ClassName( fk.ForeignTable );
if(className==cName)return ChildName(fk) + cName;
return className + cName;
}
private string FKClassName(IForeignKey fk)
{
string className=ClassName(fk.PrimaryTable);
return FKClassName(className,fk);
}
private string FKBy(IForeignKey fk)
{
if(fk.PrimaryTable.Name==fk.ForeignTable.Name)return ChildrenName(fk);
return "By" +FormatColumns("{prop}",fk.ForeignColumns,"_","");
}
private string FKAndString(string className,IForeignKey fk,string str)
{
string cName = ClassName( fk.ForeignTable );
if(className==cName)return str;
return "";
}
private string FKCountName(ITable tbl,IForeignKey FK,string sAlias)
{
if(tbl.Name == FK.ForeignTable.Name)return ChildName(FK);
return ClassName(FK.ForeignTable) + sAlias;
}
private bool FKParent(ITable tbl)
{
foreach(IForeignKey fk in tbl.ForeignKeys)
{
if(fk.PrimaryTable == fk.ForeignTable)return true;
}
return false;
}
private IForeignKey FKParentFK(ITable tbl)
{
foreach(IForeignKey fk in tbl.ForeignKeys)
{
if(fk.PrimaryTable == fk.ForeignTable)return fk;
}
return null;
}
private bool IsParentCol(IColumn col)
{
IForeignKey fk = FKParentFK(col.Table);
if(fk==null)return false;
foreach(IColumn col1 in fk.ForeignColumns)
{
if(col.Name==col1.Name)return true;
}
return false;
}
private string parentName(IColumn col)
{
IColumn colp = ParentCol(col);
if (colp == null)
{
if(IsRelObj(col))return LocalName(RelObjProp(col)) + "." + RelObjCol(col);
return LocalName(RelObjProp(col));
}
return "my" + ParentName(col.ForeignKeys[0]) + "." + PropertyName(colp.Name);
}
private string ParentName(IColumn col)
{
IColumn colp = ParentCol(col);
if (colp == null)
{
if(IsRelObj(col))return PropertyName(col);
return MemberName(RelObjProp(col));
}
return PropertyName(col.Name);
}
private string ParentRef(IColumn col)
{
IColumn colp = ParentCol(col);
if (colp != null) return ClassName(col.Table) + ".Get(" + RelObjTypeCast(col) + MemberName(col) + ")";
return null;
}
private string ParentTypeName(IColumn col)
{
IColumn colp = ParentCol(col);
if (colp != null) return ClassName(col.Table) + " myParent";
return null;
}
private IColumn ParentCol(IColumn col)
{
IForeignKey fk = FKParentFK(col.Table);
if(fk==null)return null;
return RelatedColumnF(col,fk);
}
private bool IsParentColumn(IColumn col)
{
IForeignKey fk = FKParentFK(col.Table);
if(fk==null)return false;
foreach(IColumn colf in fk.ForeignColumns)
if(colf.Name == col.Name)return true;
return false;
}
private string AutoSeed(IColumn col)
{
IForeignKey fk = FKParentFK(col.Table);
if(fk==null)return null;
IColumn colp = RelatedColumnF(col,fk);
if(colp==null)return "";
return (colp.IsAutoKey?colp.AutoKeySeed.ToString():"");
}
private IColumn RelatedColumn(IColumn column,IForeignKey fk){
if(column.Table.Name == fk.PrimaryTable.Name && fk.ForeignColumns.Count == 1){
return fk.ForeignColumns[0];
}
if(column.Table.Name == fk.ForeignTable.Name && fk.PrimaryColumns.Count == 1){
return fk.PrimaryColumns[0];
}
return null;
}
private IColumn RelatedColumnF(IColumn col,IForeignKey fk){
for(int i =0; i < fk.PrimaryColumns.Count;i++) // Loop through the related columns
{
IColumn pcol=fk.PrimaryColumns[i]; // This is the primary column
IColumn fcol=fk.ForeignColumns[i]; // This is the foreign column
//if(pcol.Name == col.Name && pcol.Table.Name == col.Table.Name)return fcol;
if(fcol.Name == col.Name && fcol.Table.Name == col.Table.Name)return pcol;
}
return null;
}
private IColumn RelatedColumnP(IColumn col,IForeignKey fk){
for(int i =0; i < fk.PrimaryColumns.Count;i++) // Loop through the related columns
{
IColumn pcol=fk.PrimaryColumns[i]; // This is the primary column
IColumn fcol=fk.ForeignColumns[i]; // This is the foreign column
if(pcol.Name == col.Name && pcol.Table.Name == col.Table.Name)return fcol;
//if(fcol.Name == col.Name && fcol.Table.Name == col.Table.Name)return pcol;
}
return null;
}
private IColumn RelatedColumnB(IColumn col,IForeignKey fk){
for(int i =0; i < fk.PrimaryColumns.Count;i++) // Loop through the related columns
{
IColumn pcol=fk.PrimaryColumns[i]; // This is the primary column
IColumn fcol=fk.ForeignColumns[i]; // This is the foreign column
if(pcol.Name == col.Name && pcol.Table.Name == col.Table.Name)return fcol;
if(fcol.Name == col.Name && fcol.Table.Name == col.Table.Name)return pcol;
}
return null;
}
private string ProcessName(Match m)
{
return m.Value.TrimStart("-_ ".ToCharArray()).ToUpper();
}
private string Suffix(IColumn col)
{
//return (PropertyName(col.Name)==_className?"Fld":"");
return (PropertyName(col.Name)==ClassName(col.Table.Name)?"Fld":"");
}
private string PropertyName(IColumn col)
{
return PropertyName(col.Name)+Suffix(col);
}
private string PropertyName(string name)
{
return Regex.Replace(name, "^[a-z]|[-_ ][a-zA-Z0-9]",new MatchEvaluator(ProcessName));
}
private bool MixedCase(string s)
{
bool hasUpper = false;
bool hasLower = false;
foreach (char c in s.ToCharArray())
{
hasUpper |= Char.IsUpper(c);
hasLower |= char.IsLower(c);
if (hasLower && hasUpper) return true;
}
return false;
}
private string MemberName(string name)
{
return _prefix + name;
}
private string MemberName(IColumn c)
{
return MemberName(PropertyName(c));
}
private string LocalName(IColumn col)
{
return LocalName(col.Name)+Suffix(col);
}
private string LocalName(string s)
{
s=PropertyName(s);
if(MixedCase(s))return ToLeadingLower(s);
else return s.ToLower();
}
private string ClassName(string name)
{
return SingularName(PropertyName(name));
}
private string ClassName(ITable table)
{
return ClassName(table.Alias);
}
private string ClassName(IView view)
{
return ClassName(view.Alias);
}
private string ClassName(IColumn column)
{
if(column.Table != null)return ClassName(column.Table);
if(column.View != null)return ClassName(column.View);
return null;
}
private string ClassesName(string name)
{
return PluralName(PropertyName(name));
}
private string ClassesName(ITable table)
{
return ClassesName(table.Alias);
}
private string ClassesName(IView view)
{
return ClassesName(view.Name);
}
private string ClassesName(IColumn column)
{
if(column.Table != null)return ClassesName(column.Table);
if(column.View != null)return ClassesName(column.View);
return null;
}
private string SingularName(string s)
{
if(Regex.IsMatch(s,"crises$"))return Regex.Replace(s,"crises$","crisis");
if(Regex.IsMatch(s,"uses$"))return Regex.Replace(s,"uses$","us");
if(Regex.IsMatch(s,"is$"))return s;
if(Regex.IsMatch(s,"us$"))return s;
if(Regex.IsMatch(s,"sses$"))return Regex.Replace(s,"sses$","ss");
if(Regex.IsMatch(s,"ches$"))return Regex.Replace(s,"ches$","ch");
if(Regex.IsMatch(s,"ies$"))return Regex.Replace(s,"ies$","y");
if(Regex.IsMatch(s,"ss$"))return s;
return Regex.Replace(s,"s$","");
}
private string PluralName(string s)
{
s=SingularName(s);
if(Regex.IsMatch(s,"crisis$"))return Regex.Replace(s,"crisis$","crises");
if(Regex.IsMatch(s,"us$"))return Regex.Replace(s,"us$","uses");
if(Regex.IsMatch(s,"ises$"))return s;
if(Regex.IsMatch(s,"uses$"))return s;
if(Regex.IsMatch(s,"ss$"))return Regex.Replace(s,"ss$","sses");
if(Regex.IsMatch(s,"ch$"))return Regex.Replace(s,"ch$","ches");
if(Regex.IsMatch(s,"y$"))return Regex.Replace(s,"y$","ies");
return s + "s";
}
private string ReturnType(string type)
{
if(type=="SmartDate")type="string";
return type;
}
private string ReturnMember(string type)
{
string member="";
return member;
}
private string CSLAType(IColumn column)
{
return CSLAType(column,(column.IsNullable? "?":""));
}
private string CSLAType(IColumn column,string suffix)
{
string type = column.LanguageType;
switch( column.LanguageType )
{
case "DateTime":
if(column.Description.IndexOf("{datetime}")>=0)
type="DateTime" + suffix;
else
type = "SmartDate";
break;
case "short":
type="Int16" + suffix;
break;
case "string":
break;
case "byte[]":
break; default:
type += suffix;
break;
// case "uint":
// retVal = "int";
// break;
// case "ulong":
// retVal = "long";
// break;
// case "ushort":
// retVal = "short";
// break;
}
return type;
}
string DefaultValue(IColumn column)
{
string s = RemoveParens(column.Default);
switch(s)
{
case "getdate()":
if(CSLAType(column)=="DateTime")
s="DateTime.Now";
else
s="DateTime.Now.ToShortDateString()";
break;
case "upper(suser_sname())":
s= "Environment.UserName.ToUpper()";
break;
case "suser_sname()":
s="Environment.UserName";
break;
default:
if(IsNumeric(s))s="" + s;
else s="";
break;
}
return s;
}
private string InitializeValue( IColumn Column )
{
string retVal=";";
if(Column.DataTypeName=="timestamp")
{
retVal = " = new byte[8];//timestamp";
}
else
{
//if(Column.Default != ""){
// retVal = ConvertDefault(Column) + ";// TODO: Default from DB " + RemoveParens(Column.Default) + " ";
//}
//else
//{
switch( CSLAType(Column ) )
{
case "string":
retVal = " = string.Empty;";
break;
case "DateTime":
retVal = " = new DateTime();";
break;
case "SmartDate":
retVal = " = string.Empty;";
break;
//case "Guid":
// retVal = "=new Guid();";
// break;
default:
// nothing to do here
break;
}
//}
}
return retVal;
}
public static bool IsNumeric(string stringToTest)
{
double newVal;
return double.TryParse(stringToTest, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out newVal);
}
private string RemoveParens(string s)
{
while(s.StartsWith("(") && s.EndsWith(")"))
s=s.Substring(1,s.Length-2);
return s;
}
private string ParameterName(IColumn column)
{
return "@" + PropertyName(column.Name);
}
private string NewParameterName(IColumn column)
{
return "@new" + PropertyName(column.Name);
}
private string ParamKeyName(IColumn column)
{
if(column.IsAutoKey)return NewParameterName(column);
return ParameterName(column);
}
private string ToLeadingLower( string name )
{
char[] chars = name.ToCharArray();
chars[0] = Char.ToLower( chars[0] );
return new string( chars );
}
private string DBType(IColumn column)
{
string s=column.DataTypeNameComplete;
switch(s){
case "text":
s="varchar(MAX)";
break;
case "ntext":
s="nvarchar(MAX)";
break;
}
return s;
}
// Old ----------------------------------------------
// private string ToClassName(string name)
// {
// return Regex.Replace(ToPascalCase(name),"s$","");
// }
// private string ColumnToMemberVariable( IColumn Column )
// {
// return _prefix + UniqueColumn( Column ).ToLower();
// }
//
// private string ColumnToPropertyName( IColumn Column )
// {
// return ToPascalCase( UniqueColumn( Column ) );
// }
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="KeywordPlanCampaignServiceClient"/> instances.</summary>
public sealed partial class KeywordPlanCampaignServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="KeywordPlanCampaignServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="KeywordPlanCampaignServiceSettings"/>.</returns>
public static KeywordPlanCampaignServiceSettings GetDefault() => new KeywordPlanCampaignServiceSettings();
/// <summary>
/// Constructs a new <see cref="KeywordPlanCampaignServiceSettings"/> object with default settings.
/// </summary>
public KeywordPlanCampaignServiceSettings()
{
}
private KeywordPlanCampaignServiceSettings(KeywordPlanCampaignServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetKeywordPlanCampaignSettings = existing.GetKeywordPlanCampaignSettings;
MutateKeywordPlanCampaignsSettings = existing.MutateKeywordPlanCampaignsSettings;
OnCopy(existing);
}
partial void OnCopy(KeywordPlanCampaignServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>KeywordPlanCampaignServiceClient.GetKeywordPlanCampaign</c> and
/// <c>KeywordPlanCampaignServiceClient.GetKeywordPlanCampaignAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetKeywordPlanCampaignSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>KeywordPlanCampaignServiceClient.MutateKeywordPlanCampaigns</c> and
/// <c>KeywordPlanCampaignServiceClient.MutateKeywordPlanCampaignsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateKeywordPlanCampaignsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="KeywordPlanCampaignServiceSettings"/> object.</returns>
public KeywordPlanCampaignServiceSettings Clone() => new KeywordPlanCampaignServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="KeywordPlanCampaignServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class KeywordPlanCampaignServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordPlanCampaignServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public KeywordPlanCampaignServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public KeywordPlanCampaignServiceClientBuilder()
{
UseJwtAccessWithScopes = KeywordPlanCampaignServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref KeywordPlanCampaignServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordPlanCampaignServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override KeywordPlanCampaignServiceClient Build()
{
KeywordPlanCampaignServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<KeywordPlanCampaignServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<KeywordPlanCampaignServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private KeywordPlanCampaignServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return KeywordPlanCampaignServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<KeywordPlanCampaignServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return KeywordPlanCampaignServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => KeywordPlanCampaignServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => KeywordPlanCampaignServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordPlanCampaignServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>KeywordPlanCampaignService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage Keyword Plan campaigns.
/// </remarks>
public abstract partial class KeywordPlanCampaignServiceClient
{
/// <summary>
/// The default endpoint for the KeywordPlanCampaignService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default KeywordPlanCampaignService scopes.</summary>
/// <remarks>
/// The default KeywordPlanCampaignService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="KeywordPlanCampaignServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="KeywordPlanCampaignServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="KeywordPlanCampaignServiceClient"/>.</returns>
public static stt::Task<KeywordPlanCampaignServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new KeywordPlanCampaignServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="KeywordPlanCampaignServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="KeywordPlanCampaignServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="KeywordPlanCampaignServiceClient"/>.</returns>
public static KeywordPlanCampaignServiceClient Create() => new KeywordPlanCampaignServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="KeywordPlanCampaignServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="KeywordPlanCampaignServiceSettings"/>.</param>
/// <returns>The created <see cref="KeywordPlanCampaignServiceClient"/>.</returns>
internal static KeywordPlanCampaignServiceClient Create(grpccore::CallInvoker callInvoker, KeywordPlanCampaignServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
KeywordPlanCampaignService.KeywordPlanCampaignServiceClient grpcClient = new KeywordPlanCampaignService.KeywordPlanCampaignServiceClient(callInvoker);
return new KeywordPlanCampaignServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC KeywordPlanCampaignService client</summary>
public virtual KeywordPlanCampaignService.KeywordPlanCampaignServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordPlanCampaign GetKeywordPlanCampaign(GetKeywordPlanCampaignRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaign> GetKeywordPlanCampaignAsync(GetKeywordPlanCampaignRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaign> GetKeywordPlanCampaignAsync(GetKeywordPlanCampaignRequest request, st::CancellationToken cancellationToken) =>
GetKeywordPlanCampaignAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan campaign to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordPlanCampaign GetKeywordPlanCampaign(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanCampaign(new GetKeywordPlanCampaignRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan campaign to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaign> GetKeywordPlanCampaignAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanCampaignAsync(new GetKeywordPlanCampaignRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan campaign to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaign> GetKeywordPlanCampaignAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetKeywordPlanCampaignAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan campaign to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordPlanCampaign GetKeywordPlanCampaign(gagvr::KeywordPlanCampaignName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanCampaign(new GetKeywordPlanCampaignRequest
{
ResourceNameAsKeywordPlanCampaignName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan campaign to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaign> GetKeywordPlanCampaignAsync(gagvr::KeywordPlanCampaignName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanCampaignAsync(new GetKeywordPlanCampaignRequest
{
ResourceNameAsKeywordPlanCampaignName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the Keyword Plan campaign to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaign> GetKeywordPlanCampaignAsync(gagvr::KeywordPlanCampaignName resourceName, st::CancellationToken cancellationToken) =>
GetKeywordPlanCampaignAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes Keyword Plan campaigns. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanCampaignError]()
/// [KeywordPlanError]()
/// [ListOperationError]()
/// [MutateError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateKeywordPlanCampaignsResponse MutateKeywordPlanCampaigns(MutateKeywordPlanCampaignsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes Keyword Plan campaigns. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanCampaignError]()
/// [KeywordPlanError]()
/// [ListOperationError]()
/// [MutateError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignsResponse> MutateKeywordPlanCampaignsAsync(MutateKeywordPlanCampaignsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes Keyword Plan campaigns. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanCampaignError]()
/// [KeywordPlanError]()
/// [ListOperationError]()
/// [MutateError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignsResponse> MutateKeywordPlanCampaignsAsync(MutateKeywordPlanCampaignsRequest request, st::CancellationToken cancellationToken) =>
MutateKeywordPlanCampaignsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes Keyword Plan campaigns. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanCampaignError]()
/// [KeywordPlanError]()
/// [ListOperationError]()
/// [MutateError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose Keyword Plan campaigns are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan campaigns.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateKeywordPlanCampaignsResponse MutateKeywordPlanCampaigns(string customerId, scg::IEnumerable<KeywordPlanCampaignOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateKeywordPlanCampaigns(new MutateKeywordPlanCampaignsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes Keyword Plan campaigns. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanCampaignError]()
/// [KeywordPlanError]()
/// [ListOperationError]()
/// [MutateError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose Keyword Plan campaigns are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan campaigns.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignsResponse> MutateKeywordPlanCampaignsAsync(string customerId, scg::IEnumerable<KeywordPlanCampaignOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateKeywordPlanCampaignsAsync(new MutateKeywordPlanCampaignsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes Keyword Plan campaigns. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanCampaignError]()
/// [KeywordPlanError]()
/// [ListOperationError]()
/// [MutateError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose Keyword Plan campaigns are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan campaigns.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignsResponse> MutateKeywordPlanCampaignsAsync(string customerId, scg::IEnumerable<KeywordPlanCampaignOperation> operations, st::CancellationToken cancellationToken) =>
MutateKeywordPlanCampaignsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>KeywordPlanCampaignService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage Keyword Plan campaigns.
/// </remarks>
public sealed partial class KeywordPlanCampaignServiceClientImpl : KeywordPlanCampaignServiceClient
{
private readonly gaxgrpc::ApiCall<GetKeywordPlanCampaignRequest, gagvr::KeywordPlanCampaign> _callGetKeywordPlanCampaign;
private readonly gaxgrpc::ApiCall<MutateKeywordPlanCampaignsRequest, MutateKeywordPlanCampaignsResponse> _callMutateKeywordPlanCampaigns;
/// <summary>
/// Constructs a client wrapper for the KeywordPlanCampaignService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="KeywordPlanCampaignServiceSettings"/> used within this client.
/// </param>
public KeywordPlanCampaignServiceClientImpl(KeywordPlanCampaignService.KeywordPlanCampaignServiceClient grpcClient, KeywordPlanCampaignServiceSettings settings)
{
GrpcClient = grpcClient;
KeywordPlanCampaignServiceSettings effectiveSettings = settings ?? KeywordPlanCampaignServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetKeywordPlanCampaign = clientHelper.BuildApiCall<GetKeywordPlanCampaignRequest, gagvr::KeywordPlanCampaign>(grpcClient.GetKeywordPlanCampaignAsync, grpcClient.GetKeywordPlanCampaign, effectiveSettings.GetKeywordPlanCampaignSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetKeywordPlanCampaign);
Modify_GetKeywordPlanCampaignApiCall(ref _callGetKeywordPlanCampaign);
_callMutateKeywordPlanCampaigns = clientHelper.BuildApiCall<MutateKeywordPlanCampaignsRequest, MutateKeywordPlanCampaignsResponse>(grpcClient.MutateKeywordPlanCampaignsAsync, grpcClient.MutateKeywordPlanCampaigns, effectiveSettings.MutateKeywordPlanCampaignsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateKeywordPlanCampaigns);
Modify_MutateKeywordPlanCampaignsApiCall(ref _callMutateKeywordPlanCampaigns);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetKeywordPlanCampaignApiCall(ref gaxgrpc::ApiCall<GetKeywordPlanCampaignRequest, gagvr::KeywordPlanCampaign> call);
partial void Modify_MutateKeywordPlanCampaignsApiCall(ref gaxgrpc::ApiCall<MutateKeywordPlanCampaignsRequest, MutateKeywordPlanCampaignsResponse> call);
partial void OnConstruction(KeywordPlanCampaignService.KeywordPlanCampaignServiceClient grpcClient, KeywordPlanCampaignServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC KeywordPlanCampaignService client</summary>
public override KeywordPlanCampaignService.KeywordPlanCampaignServiceClient GrpcClient { get; }
partial void Modify_GetKeywordPlanCampaignRequest(ref GetKeywordPlanCampaignRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateKeywordPlanCampaignsRequest(ref MutateKeywordPlanCampaignsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::KeywordPlanCampaign GetKeywordPlanCampaign(GetKeywordPlanCampaignRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeywordPlanCampaignRequest(ref request, ref callSettings);
return _callGetKeywordPlanCampaign.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested Keyword Plan campaign in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::KeywordPlanCampaign> GetKeywordPlanCampaignAsync(GetKeywordPlanCampaignRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeywordPlanCampaignRequest(ref request, ref callSettings);
return _callGetKeywordPlanCampaign.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes Keyword Plan campaigns. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanCampaignError]()
/// [KeywordPlanError]()
/// [ListOperationError]()
/// [MutateError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateKeywordPlanCampaignsResponse MutateKeywordPlanCampaigns(MutateKeywordPlanCampaignsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateKeywordPlanCampaignsRequest(ref request, ref callSettings);
return _callMutateKeywordPlanCampaigns.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes Keyword Plan campaigns. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanCampaignError]()
/// [KeywordPlanError]()
/// [ListOperationError]()
/// [MutateError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateKeywordPlanCampaignsResponse> MutateKeywordPlanCampaignsAsync(MutateKeywordPlanCampaignsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateKeywordPlanCampaignsRequest(ref request, ref callSettings);
return _callMutateKeywordPlanCampaigns.Async(request, callSettings);
}
}
}
| |
// Copyright (c) 2009 Bohumir Zamecnik <[email protected]>
// License: The MIT License, see the LICENSE file
using System;
namespace HalftoneLab
{
// TODO: incremental -> normalized (with opposite meaning)
/// <summary>
/// Tileable matrix of threshold values.
/// </summary>
/// <remarks>
/// Coefficients are scaled to 0-255 range.
/// </remarks>
[Serializable]
[Module(TypeName = "Threshold matrix")]
public class ThresholdMatrix : Matrix<int, int>
{
[NonSerialized]
private int[,] _workingMatrix;
protected override int[,] WorkingMatrix {
get { return _workingMatrix; }
set { _workingMatrix = value; }
}
//
private bool _incremental;
/// <summary>
/// Is the definition matrix in incremental form (true) or already
/// normalized (false)?
/// </summary>
public bool Incremental {
get { return _incremental; }
}
/// <summary>
/// Create a threshold matrix from given definition matrix.
/// </summary>
/// <param name="matrix">Definition matrix</param>
/// <param name="incremental">True - matrix is incremental, false - it
/// is normalized</param>
public ThresholdMatrix(int[,] matrix, bool incremental) {
_incremental = incremental;
DefinitionMatrix = matrix;
}
/// <summary>
/// Create a threshold matrix from given incremental matrix.
/// </summary>
/// <param name="matrix">Definition matrix in incremental form</param>
public ThresholdMatrix(int[,] matrix)
: this(matrix, true) { }
/// <summary>
/// Create a default threshold matrix with one coefficient at 128.
/// </summary>
public ThresholdMatrix()
: this(new int[1, 1] { { 128 } }, false) { }
public override Matrix<int, int> Clone() {
return new ThresholdMatrix(DefinitionMatrix, Incremental);
}
protected override void computeWorkingMatrix() {
_workingMatrix = (_incremental) ?
normalizeFromIncrementalMatrix(DefinitionMatrix) :
DefinitionMatrix;
}
/// <summary>
/// Normalize (scale) coefficients from incremental matrix to 0-255
/// range.
/// </summary>
/// <param name="incrMatrix">matrix with coefficients in
/// range 1-(h*w)</param>
/// <returns>scaled matrix with coefficients in 0-255 range</returns>
private static int[,] normalizeFromIncrementalMatrix(int[,] incrMatrix) {
int height = incrMatrix.GetLength(0);
int width = incrMatrix.GetLength(1);
//return normalizeFromIncrementalMatrix(incrMatrix,
// height * width + 1);
// used (the maximum matrix coefficient + 1) as the divisor
int maxCoeff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
maxCoeff = Math.Max(maxCoeff, incrMatrix[y, x]);
}
}
return normalizeFromIncrementalMatrix(incrMatrix, maxCoeff + 1);
}
/// <summary>
/// Normalize (scale) matrix coefficients from incremental form to
/// 0-255 range.
/// </summary>
/// <param name="incrMatrix">Matrix in incremental form</param>
/// <param name="divisor">Divisor</param>
/// <returns>Normalized matrix</returns>
private static int[,] normalizeFromIncrementalMatrix(
int[,] incrMatrix, int divisor)
{
int height = incrMatrix.GetLength(0);
int width = incrMatrix.GetLength(1);
double coeff = 255.0 / (double)divisor;
int[,] matrix = new int[height, width];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
matrix[y, x] = (int)(incrMatrix[y, x] * coeff);
}
}
return matrix;
}
public override void init(HalftoneLab.Image.ImageRunInfo imageRunInfo) {
base.init(imageRunInfo);
}
/// <summary>
/// A utility class for generating threshold matrices.
/// </summary>
public class Samples
{
public static ThresholdMatrix sampleScreenMatrix;
public static ThresholdMatrix simpleThreshold;
static Samples() {
simpleThreshold = new ThresholdMatrix(new int[1, 1] { { 128 } }, false);
sampleScreenMatrix = new ThresholdMatrix(
new int[,] {
//{ 16, 5, 9, 13 },
//{ 12, 1, 2, 6 },
//{ 8, 3, 4, 10 },
//{ 15, 11, 7, 14 }
//{62, 54, 41, 23, 35, 43, 59, 63},
//{58, 50, 25, 20, 29, 38, 51, 55},
//{46, 30, 13, 5, 12, 16, 34, 42},
//{21, 17, 9, 1, 4, 8, 28, 37},
//{26, 18, 6, 2, 3, 11, 23, 33},
//{48, 31, 14, 10, 7, 15, 40, 44},
//{53, 49, 32, 19, 27, 36, 52, 59},
//{61, 57, 45, 22, 39, 47, 56, 64}
//{ 46, 35, 23, 22, 32, 43, 48},
//{ 36, 16, 11, 10, 15, 34, 40},
//{ 24, 12, 4, 3, 8, 20, 28},
//{ 21, 9, 2, 1, 6, 18, 25},
//{ 31, 14, 7, 5, 13, 30, 37},
//{ 42, 33, 19, 17, 29, 41, 44},
//{ 47, 39, 27, 26, 38, 45, 49},
//{ 16, 5, 9, 13, 32, 19, 25, 39 },
//{ 12, 1, 2, 6, 28, 17, 18, 22 },
//{ 8, 4, 3, 10, 24, 20, 19, 26 },
//{ 15, 11, 7, 14, 31, 27, 23, 30 },
//{ 32, 19, 25, 39, 16, 5, 9, 13 },
//{ 28, 17, 18, 22, 12, 1, 2, 6 },
//{ 24, 20, 19, 26, 8, 4, 3, 10 },
//{ 31, 27, 23, 30, 15, 11, 7, 14 }
{ 32, 10, 18, 26, 34, 56, 48, 40 },
{ 24, 2, 4, 12, 42, 64, 62, 54 },
{ 16, 8, 6, 20, 50, 58, 60, 46 },
{ 30, 22, 14, 28, 36, 44, 52, 38 },
{ 34, 56, 48, 40, 32, 10, 18, 26 },
{ 42, 64, 62, 54, 24, 2, 4, 12 },
{ 50, 58, 60, 46, 16, 8, 6, 20 },
{ 36, 44, 52, 38, 30, 22, 14, 28 }
});
}
/// <summary>
/// Create a Bayer dispersed dot matrix (recursive tesselation
/// matrix) of size 2^N x 2^N (where N is magnitude).
/// </summary>
/// <remarks>
/// It is able to represent (2^N*2^N)-1 tones.
/// A recursive algorithm is used.
/// </remarks>
/// <param name="magnitude">log_2 of matrix size, range: [0, 8]</param>
/// <returns>scaled Bayer matrix</returns>
public static ThresholdMatrix createBayerDispersedDotMatrix(int magnitude) {
if ((magnitude < 0) || (magnitude > 8)) {
return null;
}
if (magnitude == 0) {
return new ThresholdMatrix(new int[1, 1] { { 0 } });
} else {
int[,] offsets = { { 0, 0 }, { 1, 1 }, { 0, 1 }, { 1, 0 } };
int[,] matrix = new int[2, 2] { { 0, 2 }, { 3, 1 } };
int[,] newMatrix;
for (int i = 1; i < magnitude; i++) {
int oldSize = matrix.GetLength(0);
newMatrix = new int[oldSize * 2, oldSize * 2];
for (int quadrant = 0; quadrant < 4; quadrant++) {
for (int y = 0; y < oldSize; y++) {
for (int x = 0; x < oldSize; x++) {
newMatrix[offsets[quadrant, 0] * oldSize + y,
offsets[quadrant, 1] * oldSize + x] =
4 * matrix[y, x] + quadrant;
}
}
}
matrix = newMatrix;
}
for (int y = 0; y < matrix.GetLength(0); y++) {
for (int x = 0; x < matrix.GetLength(1); x++) {
matrix[y, x]++;
}
}
return new ThresholdMatrix(matrix);
}
}
}
}
}
| |
// 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.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// HttpServerFailure operations.
/// </summary>
public partial class HttpServerFailure : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpServerFailure
{
/// <summary>
/// Initializes a new instance of the HttpServerFailure class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public HttpServerFailure(AutoRestHttpInfrastructureTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHttpInfrastructureTestService
/// </summary>
public AutoRestHttpInfrastructureTestService Client { get; private set; }
/// <summary>
/// Return 501 status code - should be represented in the client as an error
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Error>> Head501WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Head501", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/501").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("HEAD");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
try
{
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 501 status code - should be represented in the client as an error
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Error>> Get501WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get501", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/501").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
try
{
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 505 status code - should be represented in the client as an error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Error>> Post505WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Post505", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/505").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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 = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
try
{
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 505 status code - should be represented in the client as an error
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Error>> Delete505WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("booleanValue", booleanValue);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete505", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/505").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
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 = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!_httpResponse.IsSuccessStatusCode)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Error>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
try
{
string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using BTDB.KVDBLayer;
using Xunit;
using SnappyCompressionStrategy = BTDB.KVDBLayer.SnappyCompressionStrategy;
namespace BTDBTest
{
public class KeyValueDBCustomTest
{
public KeyValueDBCustomTest()
{
if (Directory.Exists("data"))
{
foreach (string file in Directory.EnumerateFiles("data"))
File.Delete(file);
}
else
Directory.CreateDirectory("data");
}
[Fact(Skip = "Takes too long time")]
public void Reader()
{
IEnumerable<KeyValuePair<long, Tick>> flow = TicksGenerator.GetFlow(1000000, KeysType.Random);
//passed
//using (var fileCollection = new OnDiskFileCollection("data"))
//failed
using (var fileCollection = new OnDiskMemoryMappedFileCollection("data"))
//passed
//using (var fileCollection = new InMemoryFileCollection())
{
using (IKeyValueDB db = new KeyValueDB(fileCollection, new SnappyCompressionStrategy(), (uint)Int16.MaxValue * 10))
{
using (var tr = db.StartTransaction())
{
foreach (KeyValuePair<long, Tick> item in flow)
{
byte[] key = Direct(item.Key);
byte[] value = FromTick(item.Value);
tr.CreateOrUpdateKeyValue(key, value);
}
tr.Commit();
}
flow = TicksGenerator.GetFlow(1000000, KeysType.Random);
foreach (KeyValuePair<long, Tick> item in flow)
{
using (var tr = db.StartTransaction())
{
byte[] key = Direct(item.Key);
bool find = tr.FindExactKey(key);
if (find)
{
var id = Reverse(tr.GetKeyToArray());
var tick = ToTick(tr.GetValue().ToArray());
Assert.Equal(item.Key, id);
}
}
}
}
}
}
byte[] FromTick(Tick tick)
{
using (MemoryStream stream = new MemoryStream())
{
var writer = new BinaryWriter(stream);
writer.Write(tick.Symbol);
writer.Write(tick.Timestamp.Ticks);
writer.Write(tick.Bid);
writer.Write(tick.Ask);
writer.Write(tick.BidSize);
writer.Write(tick.AskSize);
writer.Write(tick.Provider);
return stream.ToArray();
}
}
Tick ToTick(byte[] value)
{
var tick = new Tick();
using (MemoryStream stream = new MemoryStream(value))
{
var reader = new BinaryReader(stream);
tick.Symbol = reader.ReadString();
tick.Timestamp = new DateTime(reader.ReadInt64());
tick.Bid = reader.ReadDouble();
tick.Ask = reader.ReadDouble();
tick.BidSize = reader.ReadInt32();
tick.AskSize = reader.ReadInt32();
tick.Provider = reader.ReadString();
}
return tick;
}
byte[] Direct(Int64 key)
{
var val = (UInt64)(key + Int64.MaxValue + 1);
var index = BitConverter.GetBytes(val);
byte[] buf = new byte[8];
buf[0] = index[7];
buf[1] = index[6];
buf[2] = index[5];
buf[3] = index[4];
buf[4] = index[3];
buf[5] = index[2];
buf[6] = index[1];
buf[7] = index[0];
return buf;
}
Int64 Reverse(byte[] index)
{
byte[] buf = new byte[8];
buf[0] = index[7];
buf[1] = index[6];
buf[2] = index[5];
buf[3] = index[4];
buf[4] = index[3];
buf[5] = index[2];
buf[6] = index[1];
buf[7] = index[0];
UInt64 val = BitConverter.ToUInt64(buf, 0);
return (Int64)(val - (UInt64)Int64.MaxValue - 1);
}
}
public static class TicksGenerator
{
static readonly string[] symbols;
static readonly int[] digits;
static readonly double[] pipsizes;
static readonly double[] prices;
static readonly string[] providers;
static TicksGenerator()
{
//2013-11-12 13:00
var data = new string[] { "USDCHF;4;0.9197", "GBPUSD;4;1.5880", "EURUSD;4;1.3403", "USDJPY;2;99.73", "EURCHF;4;1.2324", "AUDBGN;4;1.3596", "AUDCHF;4;0.8567", "AUDJPY;2;92.96",
"BGNJPY;2;68.31", "BGNUSD;4;0.6848", "CADBGN;4;1.3901", "CADCHF;4;0.8759", "CADUSD;4;0.9527", "CHFBGN;4;1.5862", "CHFJPY;2;108.44", "CHFUSD;4;1.0875", "EURAUD;4;1.4375", "EURCAD;4;1.4064",
"EURGBP;4;0.8438", "EURJPY;4;133.66", "GBPAUD;4;1.7031", "GBPBGN;4;2.3169", "GBPCAD;4;1.6661", "GBPCHF;4;1.4603", "GBPJPY;2;158.37", "NZDUSD;4;0.8217", "USDBGN;4;1.4594", "USDCAD;4;1.0493",
"XAUUSD;2;1281.15", "XAGUSD;2;21.21", "$DAX;2;9078.20","$FTSE;2;6707.49","$NASDAQ;2;3361.02","$SP500;2;1771.32"};
symbols = new string[data.Length];
digits = new int[data.Length];
pipsizes = new double[data.Length];
prices = new double[data.Length];
providers = new string[] { "eSignal", "Gain", "NYSE", "TSE", "NASDAQ", "Euronext", "LSE", "SSE", "ASE", "SE", "NSEI" };
var format = new NumberFormatInfo();
format.NumberDecimalSeparator = ".";
for (int i = 0; i < data.Length; i++)
{
var tokens = data[i].Split(';'); //symbol;digits;price
symbols[i] = tokens[0];
digits[i] = Int32.Parse(tokens[1]);
pipsizes[i] = Math.Round(Math.Pow(10, -digits[i]), digits[i]);
prices[i] = Math.Round(Double.Parse(tokens[2], format), digits[i]);
}
}
public static IEnumerable<KeyValuePair<long, Tick>> GetFlow(long number, KeysType keysType)
{
var random = new Random(0);
//init startup prices
var prices = TicksGenerator.prices.ToArray();
DateTime timestamp = DateTime.Now;
//generate ticks
for (long i = 0; i < number; i++)
{
int id = random.Next(symbols.Length);
//random movement (Random Walk)
int direction = random.Next() % 2 == 0 ? 1 : -1;
int pips = random.Next(0, 10);
int spread = random.Next(2, 30);
int seconds = random.Next(1, 30);
string symbol = symbols[id];
int d = digits[id];
double pipSize = pipsizes[id];
//generate values
timestamp = timestamp.AddSeconds(seconds);
double bid = Math.Round(prices[id] + direction * pips * pipSize, d);
double ask = Math.Round(bid + spread * pipSize, d);
int bidSize = random.Next(0, 10000);
int askSize = random.Next(0, 10000);
string provider = providers[random.Next(providers.Length)];
//create tick
var tick = new Tick(symbol, timestamp, bid, ask, bidSize, askSize, provider);
var key = keysType == KeysType.Sequential ? i : unchecked(random.Next() * i);
var kv = new KeyValuePair<long, Tick>(key, tick);
yield return kv;
prices[id] = bid;
}
}
}
public enum KeysType : byte
{
Sequential,
Random
}
public class Tick : IComparable<Tick>
{
public string Symbol { get; set; }
public DateTime Timestamp { get; set; }
public double Bid { get; set; }
public double Ask { get; set; }
public int BidSize { get; set; }
public int AskSize { get; set; }
public string Provider { get; set; }
public Tick()
{
}
public Tick(string symbol, DateTime time, double bid, double ask, int bidSize, int askSize, string provider)
{
Symbol = symbol;
Timestamp = time;
Bid = bid;
Ask = ask;
BidSize = bidSize;
AskSize = askSize;
Provider = provider;
}
public override string ToString()
{
return $"{Symbol};{Timestamp:yyyy-MM-dd HH:mm:ss};{Bid};{Ask};{BidSize};{AskSize};{Provider}";
}
public int CompareTo(Tick other)
{
if (other.Ask.CompareTo(this.Ask) != 0)
return -1;
if (other.AskSize != this.AskSize)
return -1;
if (Math.Abs(other.Bid - this.Bid) > 1e-50)
return -1;
if (other.BidSize != this.BidSize)
return -1;
if (!other.Provider.Equals(this.Provider))
return -1;
if (!other.Symbol.Equals(this.Symbol))
return -1;
if (!other.Timestamp.Equals(this.Timestamp))
return -1;
return 0;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//#define EMBEDDED_CONFIGURATION // this is the case when we want the app.config in the resources
#define HARDCODED_CONFIGURATION // configuration done programmatically
// none (exe app.config) // configuration from the app.config of the project
// We do not use Visual Studio Service Reference because it is not able to share service interfaces
using System;
using System.IO;
using System.Collections.Generic;
using System.ServiceModel;
using Microsoft.Research.Cloudot.Common;
using Clousot2_ServiceClient;
using Microsoft.Research.DataStructures;
using System.Diagnostics.Contracts;
using System.Diagnostics;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
#if EMBEDDED_CONFIGURATION
using System.Configuration;
using System.Reflection;
#endif
namespace Microsoft.Research.CodeAnalysis
{
public static class ClousotViaService
{
private static readonly RetryOptions defaultRetryOptions = new RetryOptions
{
FirstMinTime = TimeSpan.FromSeconds(1),
FirstMaxTime = TimeSpan.FromSeconds(2),
MaxTime = TimeSpan.FromSeconds(20),
MultiplyingFactor = 1.5,
NumberOfRetries = 2
};
#if EMBEDDED_CONFIGURATION
private static readonly Configuration configuration;
private static ClousotViaService()
{
var configFileName = "Microsoft.Research.CodeAnalysis.app.config";
// It is not possible to load a resource as a configuration file
// it has to be a real file on disk, that's why we use a temporary file
var assembly = Assembly.GetExecutingAssembly();
string contents;
using (var configFileReader = new StreamReader(assembly.GetManifestResourceStream(configFileName)))
contents = configFileReader.ReadToEnd();
var tempFileName = Path.GetTempFileName();
using (var tempFileWriter = new StreamWriter(tempFileName))
tempFileWriter.Write(contents);
var configFileMap = new ConfigurationFileMap(tempFileName);
configuration = ConfigurationManager.OpenMappedMachineConfiguration(configFileMap);
}
#endif
// We have a dictionary because we can have different concrete types as ILineWriters
private static readonly Dictionary<Type, DuplexChannelFactory<IClousotService>> channelFactoryForType = new Dictionary<Type, DuplexChannelFactory<IClousotService>>();
private static readonly object LockChannelFactoryForType = new object();
private static readonly TimeSpan TimeToWaitBeforeClosing = new TimeSpan(0, 0, 6); // 6 seconds
// We need only one channel, but the WCF protocol requires us to provide a factory...
private static DuplexChannelFactory<IClousotService> GetChannelFactoryForType(Type type)
{
lock (LockChannelFactoryForType)
{
DuplexChannelFactory<IClousotService> channelFactory;
if (channelFactoryForType.TryGetValue(type, out channelFactory))
return channelFactory;
#if EMBEDDED_CONFIGURATION
channelFactory = new CustomDuplexChannelFactory<IClousotService>(configuration, type);
#elif HARDCODED_CONFIGURATION
var binding = ClousotWCFServiceCommon.NewBinding(ClousotWCFServiceCommon.SecurityMode);
binding.ReceiveTimeout = TimeSpan.FromDays(2);
binding.SendTimeout = TimeSpan.FromDays(2);
var endpointAddress = new EndpointAddress(ClousotWCFServiceCommon.BaseUri, ClousotWCFServiceCommon.Identity);
channelFactory = new DuplexChannelFactory<IClousotService>(type, binding, endpointAddress);
#else
channelFactory = new DuplexChannelFactory<IClousotService>(type);
#endif
channelFactoryForType.Add(type, channelFactory);
return channelFactory;
}
}
static public string GetTmpDirectory
{
get
{
return @"C:\tmp\CloudotTest"; // TODO: use .net GetTmpDirectory
}
}
public static int Main(string[] args, string forceServiceAddress = null)
{
string[] dummy;
return Main2(args, Console.Out, out dummy, forceServiceAddress);
}
public static int Main(string[] args, out string[] clousotArgs, string forceServiceAddress = null)
{
return Main2(args, Console.Out, out clousotArgs, forceServiceAddress);
}
public static int Main2(string[] args, TextWriter textWriter, out string[] clousotArgs, string forceServiceAddress = null)
{
using(var tw = textWriter.AsLineWriter())
{
return Main2(args, tw, out clousotArgs, forceServiceAddress);
}
}
/// <param name="forceServiceAddress">If != null, overwrites the service address, and do not not create the analysis package</param>
public static int Main2(string[] args, IVerySimpleLineWriterWithEncoding lineWriter, out string[] clousotArgs, string forceServiceAddress = null)
{
Contract.Requires(lineWriter != null);
int result = -1;
var options = new ClousotServiceOptions(args, forceServiceAddress);
clousotArgs = options.remainingArgs.ToArray();
if (options.windowsService)
{
ClousotViaWindowsService.EnsureWindowsService();
}
var retryOptions = defaultRetryOptions.Clone();
retryOptions.NumberOfRetries = options.serviceRetries;
// Here we create the callback object, starting from the lineWriter provided by the caller
var channelFactory = GetChannelFactoryForType(lineWriter.GetType());
var channelAddress = String.IsNullOrWhiteSpace(options.serviceAddress)
? channelFactory.Endpoint.Address
: new EndpointAddress(new Uri(options.serviceAddress), channelFactory.Endpoint.Address.Identity); // WCF wants us to provide the address for the factory but also for the instance...
// We create the callback object
var callbackInstanceContext = new InstanceContext(lineWriter);
Func<IClousotService> GetAndOpenClousotService = () =>
{
// Let's create a channel with my callback and the address computed above
var channel = channelFactory.CreateChannel(callbackInstanceContext, channelAddress);
lineWriter.WriteLine(("Connecting to Cloudot at address " + channelAddress).PrefixWithCurrentTime());
channel.Open(); // can throw an exception
// Add an event that will be fired when the connection will enter a fault state.
// Useful for debugging
var channelAsDuplex = channel as IDuplexContextChannel;
if (channelAsDuplex != null)
{
channelAsDuplex.Faulted +=
(object sender, EventArgs e) =>
{
// This message is useful for debugging, so that we can see when the error happened
Console.WriteLine("The connection to Cloudot entered a fault state!".PrefixWithCurrentTime());
};
}
else
{
Contract.Assume(false, "We expect the service to be an instance of IDuplexContextChannel");
}
return channel;
};
IClousotService clousotService = null;
try
{
// Step 0: We connect to the server
if (!Retry<ServerTooBusyException>.RetryOnException(GetAndOpenClousotService, retryOptions, out clousotService))
{
return -6666; // server too busy, could not connect
}
lineWriter.WriteLine("Connection with Cloudot established".PrefixWithCurrentTime());
var clousotSpecificOptions = options.remainingArgs.ToArray();
// Step 0.5: Are we simply requested to re-run an existing analysis? If this is the case just invoke cloudot
if(forceServiceAddress != null)
{
result = clousotService.Main(args, lineWriter.Encoding.WebName);
goto ok;
}
// Step 1: We pack all the files on the local machine and send them to the server
FileTransfer.AnalysisPackageInfo packageInfo;
var createThePackage = !options.useSharedDirs;
if (FileTransfer.TryProcessPathsAndCreateAnalysisPackage(GetTmpDirectory, clousotSpecificOptions, createThePackage, out packageInfo))
{
clousotArgs = packageInfo.ExpandedClousotOptionsNormalized;
// Step 2 -- First option: use shared dirs. We do not really want to use it, but it is interesting for debugging
// We have all the command line options normalized to UNCs, and use them for the server
if (!createThePackage)
{
if (packageInfo.ExpandedClousotOptionsNormalized != null)
{
// Step 2: We invoke the analysis on the server
lineWriter.WriteLine("Invoking the analysis on cloudot using shared dirs".PrefixWithCurrentTime());
lineWriter.WriteLine("Parameters: {0}".PrefixWithCurrentTime(), String.Join(" ", clousotArgs));
result = clousotService.Main(clousotArgs, lineWriter.Encoding.WebName); // can throw an exception
goto ok;
}
}
// Step 2 -- Second option: use a package
// We have create a zip file with all the references. We copy it where the server tells us to.
// Then, we invoke cloudot to perform the analysis
else
{
var serverOut = clousotService.GetOutputDirectory();
string fileOnTheServer;
if (serverOut != null && FileTransfer.TrySendTheFile(packageInfo.PackageFileNameLocal, serverOut, out fileOnTheServer))
{
if (packageInfo.AssembliesToAnalyze != null && packageInfo.AssembliesToAnalyze.Length > 0)
{
packageInfo.PackageFileNameServer = fileOnTheServer;
var name = Path.GetFileName(packageInfo.AssembliesToAnalyze[0]);
#if false
// Just for debug
string[] p;
FileTransfer.TryRestoreAnalysisPackage(fileOnTheServer, Path.Combine(serverOut, "tmp"), out p);
#endif
// Step 2: We invoke the analysis on the server
lineWriter.WriteLine("Invoking the analysis on cloudot using analysis package (on server at {0})".PrefixWithCurrentTime(), fileOnTheServer);
result = clousotService.AnalyzeUsingAnalysisPackage(name, fileOnTheServer, lineWriter.Encoding.WebName);
goto ok;
}
else
{
lineWriter.WriteLine("Cannot figure out the assembly to analyze. We abort.");
}
}
}
}
return -1;
ok:
// Step * : Close the service
// We moved the Close action here, as it may be the case that the background thread is still writing something on the callback, while we close it
// I do not really know how to see if this is the case, but it appears when we output a lot of information via a remote server
// From what I saw on the internet, for similar cases, it seems the best solution is to use the Try-Catch-Abort pattern
// Waiting also helps, but how much is a problem.
clousotService.Close(TimeToWaitBeforeClosing);
return result;
}
// We use the Try-Catch-Abort pattern for WCF
catch (ActionNotSupportedException actionNotSupported)
{
Console.WriteLine("Something is wrong with the client/server contract");
Console.WriteLine("This is the exception {0}", actionNotSupported);
return -1;
}
catch (CommunicationException)
{
if (clousotService != null)
{
var channelAsDuplex = clousotService as IDuplexContextChannel;
if (channelAsDuplex != null)
{
if (channelAsDuplex.State == CommunicationState.Faulted)
{
Console.WriteLine("The communication is a faulted state. Is Cloudot down?");
}
}
(clousotService as IDuplexContextChannel).Abort();
}
else
{
Console.WriteLine("Something has gone very wrong. I did not expected clousotService to be null here");
}
return -1;
}
catch (TimeoutException)
{
Console.WriteLine("Hit a timeout in the communication with Cloudot");
(clousotService as IDuplexContextChannel).Abort();
return -1;
}
catch (Exception e)
{
var errMsg = e.Message + (e.InnerException != null ? string.Format("{0} -- {1}", Environment.NewLine, e.InnerException.Message) : "");
Console.WriteLine(("Analysis terminated because of an error: " + errMsg).PrefixWithCurrentTime());
return -1;
}
finally
{
if (clousotService != null)
{
clousotService.TryDispose();
}
}
}
/// <summary>
/// Just an hack. We should have a better story for sending files to the server
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
static private string[] AdjustPaths(string[] args)
{
Contract.Requires(args != null);
Contract.Requires(Contract.ForAll(args, a => a != null));
var result = new string[args.Length];
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.Length > 0)
{
if (arg[0] == '@')
{
var path = arg.Substring(1, arg.Length - 1);
while (i < args.Length && !File.Exists(path))
{
i++;
if (i < args.Length)
{
path += " " + args[i];
}
}
if (i == args.Length)
{
return args;
}
var fullPath = Path.GetFullPath(path);
string unc;
if (FileSystemAbstractions.TryGetUniversalName(fullPath, out unc))
{
result[i] = "@" + unc;
continue;
}
}
else if (arg[0] != '-' && arg[0] != '/')
{
string unc;
if (FileSystemAbstractions.TryGetUniversalName(arg, out unc))
{
result[i] = unc;
continue;
}
}
}
result[i] = args[i];
}
return result;
}
}
static class ClousotServiceExtensions
{
// ChannelFactory.CreateChannel returns a proxy that is at the same time a IClousotService, a IDuplexContextChannel, a IClientChannel, and maybe other things too
public static void Open(this IClousotService channel)
{
Contract.Requires(channel != null);
((IDuplexContextChannel)channel).Open();
}
[SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant", Justification = "Thread sleeping")]
public static bool Close(this IClousotService channel, TimeSpan wait)
{
Contract.Requires(channel != null);
var channelAsDuplex = channel as IDuplexContextChannel;
if (channelAsDuplex != null)
{
if (channelAsDuplex.State != CommunicationState.Faulted)
{
Console.WriteLine("Waiting {0} before closing the channel (in a state {1})", wait, channelAsDuplex.State);
Thread.Sleep(wait);
// It may be the case that while sleeping, the channel was closed
if (channelAsDuplex.State != CommunicationState.Faulted)
{
Console.WriteLine("Now we close the channel");
channelAsDuplex.Close(wait);
return true;
}
}
}
return false;
}
}
static class ObjectExtensions
{
public static bool TryDispose(this Object obj)
{
var disposable = obj as IDisposable;
if (disposable == null)
return false;
disposable.Dispose();
return true;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// <OWNER>[....]</OWNER>
/*
* This files defines the following types:
* - NativeOverlapped
* - _IOCompletionCallback
* - OverlappedData
* - Overlapped
* - OverlappedDataCache
*/
/*=============================================================================
**
** Class: Overlapped
**
**
** Purpose: Class for converting information to and from the native
** overlapped structure used in asynchronous file i/o
**
**
=============================================================================*/
namespace System.Threading
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics.Contracts;
using System.Collections.Concurrent;
#region struct NativeOverlapped
// Valuetype that represents the (unmanaged) Win32 OVERLAPPED structure
// the layout of this structure must be identical to OVERLAPPED.
// The first five matches OVERLAPPED structure.
// The remaining are reserved at the end
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.InteropServices.ComVisible(true)]
public struct NativeOverlapped
{
public IntPtr InternalLow;
public IntPtr InternalHigh;
public int OffsetLow;
public int OffsetHigh;
public IntPtr EventHandle;
}
#endregion struct NativeOverlapped
#region class _IOCompletionCallback
unsafe internal class _IOCompletionCallback
{
[System.Security.SecurityCritical] // auto-generated
IOCompletionCallback _ioCompletionCallback;
ExecutionContext _executionContext;
uint _errorCode; // Error code
uint _numBytes; // No. of bytes transferred
[SecurityCritical]
NativeOverlapped* _pOVERLAP;
[System.Security.SecuritySafeCritical] // auto-generated
static _IOCompletionCallback()
{
}
[System.Security.SecurityCritical] // auto-generated
internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ref StackCrawlMark stackMark)
{
_ioCompletionCallback = ioCompletionCallback;
// clone the exection context
_executionContext = ExecutionContext.Capture(
ref stackMark,
ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
}
// Context callback: same sig for SendOrPostCallback and ContextCallback
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
static internal ContextCallback _ccb = new ContextCallback(IOCompletionCallback_Context);
[System.Security.SecurityCritical]
static internal void IOCompletionCallback_Context(Object state)
{
_IOCompletionCallback helper = (_IOCompletionCallback)state;
Contract.Assert(helper != null,"_IOCompletionCallback cannot be null");
helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP);
}
// call back helper
[System.Security.SecurityCritical] // auto-generated
static unsafe internal void PerformIOCompletionCallback(uint errorCode, // Error code
uint numBytes, // No. of bytes transferred
NativeOverlapped* pOVERLAP // ptr to OVERLAP structure
)
{
Overlapped overlapped;
_IOCompletionCallback helper;
do
{
overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped;
helper = overlapped.iocbHelper;
if (helper == null || helper._executionContext == null || helper._executionContext.IsDefaultFTContext(true))
{
// We got here because of UnsafePack (or) Pack with EC flow supressed
IOCompletionCallback callback = overlapped.UserCallback;
callback( errorCode, numBytes, pOVERLAP);
}
else
{
// We got here because of Pack
helper._errorCode = errorCode;
helper._numBytes = numBytes;
helper._pOVERLAP = pOVERLAP;
using (ExecutionContext executionContext = helper._executionContext.CreateCopy())
ExecutionContext.Run(executionContext, _ccb, helper, true);
}
//Quickly check the VM again, to see if a packet has arrived.
OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes);
} while (pOVERLAP != null);
}
}
#endregion class _IOCompletionCallback
#region class OverlappedData
sealed internal class OverlappedData
{
// ! If you make any change to the layout here, you need to make matching change
// ! to OverlappedObject in vm\nativeoverlapped.h
internal IAsyncResult m_asyncResult;
[System.Security.SecurityCritical] // auto-generated
internal IOCompletionCallback m_iocb;
internal _IOCompletionCallback m_iocbHelper;
internal Overlapped m_overlapped;
private Object m_userObject;
private IntPtr m_pinSelf;
private IntPtr m_userObjectInternal;
private int m_AppDomainId;
#pragma warning disable 414 // Field is not used from managed.
#pragma warning disable 169
private byte m_isArray;
private byte m_toBeCleaned;
#pragma warning restore 414
#pragma warning restore 169
internal NativeOverlapped m_nativeOverlapped;
#if FEATURE_CORECLR
// Adding an empty default ctor for annotation purposes
[System.Security.SecuritySafeCritical] // auto-generated
internal OverlappedData(){}
#endif // FEATURE_CORECLR
[System.Security.SecurityCritical]
internal void ReInitialize()
{
m_asyncResult = null;
m_iocb = null;
m_iocbHelper = null;
m_overlapped = null;
m_userObject = null;
Contract.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf");
m_pinSelf = (IntPtr)0;
m_userObjectInternal = (IntPtr)0;
Contract.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain");
m_AppDomainId = 0;
m_nativeOverlapped.EventHandle = (IntPtr)0;
m_isArray = 0;
m_nativeOverlapped.InternalLow = (IntPtr)0;
m_nativeOverlapped.InternalHigh = (IntPtr)0;
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.AppDomain)]
[ResourceConsumption(ResourceScope.AppDomain)]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
unsafe internal NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
if (!m_pinSelf.IsNull()) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack"));
}
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
if (iocb != null)
{
m_iocbHelper = new _IOCompletionCallback(iocb, ref stackMark);
m_iocb = iocb;
}
else
{
m_iocbHelper = null;
m_iocb = null;
}
m_userObject = userData;
if (m_userObject != null)
{
if (m_userObject.GetType() == typeof(Object[]))
{
m_isArray = 1;
}
else
{
m_isArray = 0;
}
}
return AllocateNativeOverlapped();
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.AppDomain)]
[ResourceConsumption(ResourceScope.AppDomain)]
unsafe internal NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
{
if (!m_pinSelf.IsNull()) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack"));
}
m_userObject = userData;
if (m_userObject != null)
{
if (m_userObject.GetType() == typeof(Object[]))
{
m_isArray = 1;
}
else
{
m_isArray = 0;
}
}
m_iocb = iocb;
m_iocbHelper = null;
return AllocateNativeOverlapped();
}
[ComVisible(false)]
internal IntPtr UserHandle
{
get { return m_nativeOverlapped.EventHandle; }
set { m_nativeOverlapped.EventHandle = value; }
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.AppDomain)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private extern NativeOverlapped* AllocateNativeOverlapped();
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr);
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr);
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern void CheckVMForIOPacket(out NativeOverlapped* pOVERLAP, out uint errorCode, out uint numBytes);
}
#endregion class OverlappedData
#region class Overlapped
/// <internalonly/>
[System.Runtime.InteropServices.ComVisible(true)]
public class Overlapped
{
private OverlappedData m_overlappedData;
private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", ()=> new OverlappedData());
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#endif
public Overlapped()
{
m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate();
m_overlappedData.m_overlapped = this;
}
public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar)
{
m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate();
m_overlappedData.m_overlapped = this;
m_overlappedData.m_nativeOverlapped.OffsetLow = offsetLo;
m_overlappedData.m_nativeOverlapped.OffsetHigh = offsetHi;
m_overlappedData.UserHandle = hEvent;
m_overlappedData.m_asyncResult = ar;
}
[Obsolete("This constructor is not 64-bit compatible. Use the constructor that takes an IntPtr for the event handle. http://go.microsoft.com/fwlink/?linkid=14202")]
public Overlapped(int offsetLo, int offsetHi, int hEvent, IAsyncResult ar) : this(offsetLo, offsetHi, new IntPtr(hEvent), ar)
{
}
public IAsyncResult AsyncResult
{
get { return m_overlappedData.m_asyncResult; }
set { m_overlappedData.m_asyncResult = value; }
}
public int OffsetLow
{
get { return m_overlappedData.m_nativeOverlapped.OffsetLow; }
set { m_overlappedData.m_nativeOverlapped.OffsetLow = value; }
}
public int OffsetHigh
{
get { return m_overlappedData.m_nativeOverlapped.OffsetHigh; }
set { m_overlappedData.m_nativeOverlapped.OffsetHigh = value; }
}
[Obsolete("This property is not 64-bit compatible. Use EventHandleIntPtr instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int EventHandle
{
get { return m_overlappedData.UserHandle.ToInt32(); }
set { m_overlappedData.UserHandle = new IntPtr(value); }
}
[ComVisible(false)]
public IntPtr EventHandleIntPtr
{
get { return m_overlappedData.UserHandle; }
set { m_overlappedData.UserHandle = value; }
}
internal _IOCompletionCallback iocbHelper
{
get { return m_overlappedData.m_iocbHelper; }
}
internal IOCompletionCallback UserCallback
{
[System.Security.SecurityCritical]
get { return m_overlappedData.m_iocb; }
}
/*====================================================================
* Packs a managed overlapped class into native Overlapped struct.
* Roots the iocb and stores it in the ReservedCOR field of native Overlapped
* Pins the native Overlapped struct and returns the pinned index.
====================================================================*/
[System.Security.SecurityCritical] // auto-generated
[Obsolete("This method is not safe. Use Pack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
[ResourceExposure(ResourceScope.AppDomain)]
[ResourceConsumption(ResourceScope.AppDomain)]
unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb)
{
return Pack (iocb, null);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false),ComVisible(false)]
[ResourceExposure(ResourceScope.AppDomain)]
[ResourceConsumption(ResourceScope.AppDomain)]
unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
return m_overlappedData.Pack(iocb, userData);
}
[System.Security.SecurityCritical] // auto-generated_required
[Obsolete("This method is not safe. Use UnsafePack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
[ResourceExposure(ResourceScope.AppDomain)]
[ResourceConsumption(ResourceScope.AppDomain)]
unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb)
{
return UnsafePack (iocb, null);
}
[System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false), ComVisible(false)]
[ResourceExposure(ResourceScope.AppDomain)]
[ResourceConsumption(ResourceScope.AppDomain)]
unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
{
return m_overlappedData.UnsafePack(iocb, userData);
}
/*====================================================================
* Unpacks an unmanaged native Overlapped struct.
* Unpins the native Overlapped struct
====================================================================*/
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
unsafe public static Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr)
{
if (nativeOverlappedPtr == null)
throw new ArgumentNullException("nativeOverlappedPtr");
Contract.EndContractBlock();
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
return overlapped;
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
unsafe public static void Free(NativeOverlapped* nativeOverlappedPtr)
{
if (nativeOverlappedPtr == null)
throw new ArgumentNullException("nativeOverlappedPtr");
Contract.EndContractBlock();
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr);
OverlappedData overlappedData = overlapped.m_overlappedData;
overlapped.m_overlappedData = null;
overlappedData.ReInitialize();
s_overlappedDataCache.Free(overlappedData);
}
}
#endregion class Overlapped
} // namespace
| |
//
// System.Data.TdsTypes.TdsSingle
//
// Author:
// Tim Coleman <[email protected]>
//
// (C) Copyright 2002 Tim Coleman
//
//
// 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 Mono.Data.TdsClient;
using System;
using System.Data.SqlTypes;
using System.Globalization;
namespace Mono.Data.TdsTypes {
public struct TdsSingle : INullable, IComparable
{
#region Fields
float value;
private bool notNull;
public static readonly TdsSingle MaxValue = new TdsSingle (3.40282346638528859e38);
public static readonly TdsSingle MinValue = new TdsSingle (-3.40282346638528859e38);
public static readonly TdsSingle Null;
public static readonly TdsSingle Zero = new TdsSingle (0);
#endregion
#region Constructors
public TdsSingle (double value)
{
this.value = (float)value;
notNull = true;
}
public TdsSingle (float value)
{
this.value = value;
notNull = true;
}
#endregion
#region Properties
public bool IsNull {
get { return !notNull; }
}
public float Value {
get {
if (this.IsNull)
throw new TdsNullValueException ();
else
return value;
}
}
#endregion
#region Methods
public static TdsSingle Add (TdsSingle x, TdsSingle y)
{
return (x + y);
}
public int CompareTo (object value)
{
if (value == null)
return 1;
else if (!(value is TdsSingle))
throw new ArgumentException (Locale.GetText ("Value is not a System.Data.TdsTypes.TdsSingle"));
else if (((TdsSingle)value).IsNull)
return 1;
else
return this.value.CompareTo (((TdsSingle)value).Value);
}
public static TdsSingle Divide (TdsSingle x, TdsSingle y)
{
return (x / y);
}
public override bool Equals (object value)
{
if (!(value is TdsSingle))
return false;
else
return (bool) (this == (TdsSingle)value);
}
public static TdsBoolean Equals (TdsSingle x, TdsSingle y)
{
return (x == y);
}
public override int GetHashCode ()
{
long LongValue = (long) value;
return (int)(LongValue ^ (LongValue >> 32));
}
public static TdsBoolean GreaterThan (TdsSingle x, TdsSingle y)
{
return (x > y);
}
public static TdsBoolean GreaterThanOrEqual (TdsSingle x, TdsSingle y)
{
return (x >= y);
}
public static TdsBoolean LessThan (TdsSingle x, TdsSingle y)
{
return (x < y);
}
public static TdsBoolean LessThanOrEqual (TdsSingle x, TdsSingle y)
{
return (x <= y);
}
public static TdsSingle Multiply (TdsSingle x, TdsSingle y)
{
return (x * y);
}
public static TdsBoolean NotEquals (TdsSingle x, TdsSingle y)
{
return (x != y);
}
public static TdsSingle Parse (string s)
{
return new TdsSingle (Single.Parse (s));
}
public static TdsSingle Subtract (TdsSingle x, TdsSingle y)
{
return (x - y);
}
public TdsBoolean ToTdsBoolean ()
{
return ((TdsBoolean)this);
}
public TdsByte ToTdsByte ()
{
return ((TdsByte)this);
}
public TdsDecimal ToTdsDecimal ()
{
return ((TdsDecimal)this);
}
public TdsDouble ToTdsDouble ()
{
return ((TdsDouble)this);
}
public TdsInt16 ToTdsInt16 ()
{
return ((TdsInt16)this);
}
public TdsInt32 ToTdsInt32 ()
{
return ((TdsInt32)this);
}
public TdsInt64 ToTdsInt64 ()
{
return ((TdsInt64)this);
}
public TdsMoney ToTdsMoney ()
{
return ((TdsMoney)this);
}
public TdsString ToTdsString ()
{
return ((TdsString)this);
}
public override string ToString ()
{
return value.ToString ();
}
public static TdsSingle operator + (TdsSingle x, TdsSingle y)
{
return new TdsSingle (x.Value + y.Value);
}
public static TdsSingle operator / (TdsSingle x, TdsSingle y)
{
return new TdsSingle (x.Value / y.Value);
}
public static TdsBoolean operator == (TdsSingle x, TdsSingle y)
{
if (x.IsNull || y .IsNull) return TdsBoolean.Null;
return new TdsBoolean (x.Value == y.Value);
}
public static TdsBoolean operator > (TdsSingle x, TdsSingle y)
{
if (x.IsNull || y .IsNull) return TdsBoolean.Null;
return new TdsBoolean (x.Value > y.Value);
}
public static TdsBoolean operator >= (TdsSingle x, TdsSingle y)
{
if (x.IsNull || y .IsNull) return TdsBoolean.Null;
return new TdsBoolean (x.Value >= y.Value);
}
public static TdsBoolean operator != (TdsSingle x, TdsSingle y)
{
if (x.IsNull || y .IsNull) return TdsBoolean.Null;
return new TdsBoolean (!(x.Value == y.Value));
}
public static TdsBoolean operator < (TdsSingle x, TdsSingle y)
{
if (x.IsNull || y .IsNull) return TdsBoolean.Null;
return new TdsBoolean (x.Value < y.Value);
}
public static TdsBoolean operator <= (TdsSingle x, TdsSingle y)
{
if (x.IsNull || y .IsNull) return TdsBoolean.Null;
return new TdsBoolean (x.Value <= y.Value);
}
public static TdsSingle operator * (TdsSingle x, TdsSingle y)
{
return new TdsSingle (x.Value * y.Value);
}
public static TdsSingle operator - (TdsSingle x, TdsSingle y)
{
return new TdsSingle (x.Value - y.Value);
}
public static TdsSingle operator - (TdsSingle n)
{
return new TdsSingle (-(n.Value));
}
public static explicit operator TdsSingle (TdsBoolean x)
{
return new TdsSingle((float)x.ByteValue);
}
public static explicit operator TdsSingle (TdsDouble x)
{
return new TdsSingle((float)x.Value);
}
public static explicit operator float (TdsSingle x)
{
return x.Value;
}
public static explicit operator TdsSingle (TdsString x)
{
return TdsSingle.Parse (x.Value);
}
public static implicit operator TdsSingle (float x)
{
return new TdsSingle (x);
}
public static implicit operator TdsSingle (TdsByte x)
{
if (x.IsNull)
return Null;
else
return new TdsSingle((float)x.Value);
}
public static implicit operator TdsSingle (TdsDecimal x)
{
if (x.IsNull)
return Null;
else
return new TdsSingle((float)x.Value);
}
public static implicit operator TdsSingle (TdsInt16 x)
{
if (x.IsNull)
return Null;
else
return new TdsSingle((float)x.Value);
}
public static implicit operator TdsSingle (TdsInt32 x)
{
if (x.IsNull)
return Null;
else
return new TdsSingle((float)x.Value);
}
public static implicit operator TdsSingle (TdsInt64 x)
{
if (x.IsNull)
return Null;
else
return new TdsSingle((float)x.Value);
}
public static implicit operator TdsSingle (TdsMoney x)
{
if (x.IsNull)
return Null;
else
return new TdsSingle((float)x.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.Globalization;
using System.Runtime.InteropServices;
#if !FEATURE_SLJ_PROJECTION_COMPAT
#pragma warning disable 436 // Redefining types from Windows.Foundation
#endif // !FEATURE_SLJ_PROJECTION_COMPAT
#if FEATURE_SLJ_PROJECTION_COMPAT
namespace System.Windows
#else // !FEATURE_SLJ_PROJECTION_COMPAT
namespace Windows.Foundation
#endif // FEATURE_SLJ_PROJECTION_COMPAT
{
//
// Rect is the managed projection of Windows.Foundation.Rect. Any changes to the layout
// of this type must be exactly mirrored on the native WinRT side as well.
//
// Note that this type is owned by the Jupiter team. Please contact them before making any
// changes here.
//
[StructLayout(LayoutKind.Sequential)]
public struct Rect : IFormattable
{
private float _x;
private float _y;
private float _width;
private float _height;
private const double EmptyX = Double.PositiveInfinity;
private const double EmptyY = Double.PositiveInfinity;
private const double EmptyWidth = Double.NegativeInfinity;
private const double EmptyHeight = Double.NegativeInfinity;
private readonly static Rect s_empty = CreateEmptyRect();
public Rect(double x,
double y,
double width,
double height)
{
if (width < 0)
throw new ArgumentException("width");
if (height < 0)
throw new ArgumentException("height");
_x = (float)x;
_y = (float)y;
_width = (float)width;
_height = (float)height;
}
public Rect(Point point1,
Point point2)
{
_x = (float)Math.Min(point1.X, point2.X);
_y = (float)Math.Min(point1.Y, point2.Y);
_width = (float)Math.Max(Math.Max(point1.X, point2.X) - _x, 0);
_height = (float)Math.Max(Math.Max(point1.Y, point2.Y) - _y, 0);
}
public Rect(Point location, Size size)
{
if (size.IsEmpty)
{
this = s_empty;
}
else
{
_x = (float)location.X;
_y = (float)location.Y;
_width = (float)size.Width;
_height = (float)size.Height;
}
}
internal static Rect Create(double x,
double y,
double width,
double height)
{
if (x == EmptyX && y == EmptyY && width == EmptyWidth && height == EmptyHeight)
{
return Rect.Empty;
}
else
{
return new Rect(x, y, width, height);
}
}
public double X
{
get { return _x; }
set { _x = (float)value; }
}
public double Y
{
get { return _y; }
set { _y = (float)value; }
}
public double Width
{
get { return _width; }
set
{
if (value < 0)
throw new ArgumentException("Width");
_width = (float)value;
}
}
public double Height
{
get { return _height; }
set
{
if (value < 0)
throw new ArgumentException("Height");
_height = (float)value;
}
}
public double Left
{
get { return _x; }
}
public double Top
{
get { return _y; }
}
public double Right
{
get
{
if (IsEmpty)
{
return Double.NegativeInfinity;
}
return _x + _width;
}
}
public double Bottom
{
get
{
if (IsEmpty)
{
return Double.NegativeInfinity;
}
return _y + _height;
}
}
public static Rect Empty
{
get { return s_empty; }
}
public bool IsEmpty
{
get { return _width < 0; }
}
public bool Contains(Point point)
{
return ContainsInternal(point.X, point.Y);
}
public void Intersect(Rect rect)
{
if (!this.IntersectsWith(rect))
{
this = s_empty;
}
else
{
double left = Math.Max(X, rect.X);
double top = Math.Max(Y, rect.Y);
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
Width = Math.Max(Math.Min(X + Width, rect.X + rect.Width) - left, 0);
Height = Math.Max(Math.Min(Y + Height, rect.Y + rect.Height) - top, 0);
X = left;
Y = top;
}
}
public void Union(Rect rect)
{
if (IsEmpty)
{
this = rect;
}
else if (!rect.IsEmpty)
{
double left = Math.Min(Left, rect.Left);
double top = Math.Min(Top, rect.Top);
// We need this check so that the math does not result in NaN
if ((rect.Width == Double.PositiveInfinity) || (Width == Double.PositiveInfinity))
{
Width = Double.PositiveInfinity;
}
else
{
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
double maxRight = Math.Max(Right, rect.Right);
Width = Math.Max(maxRight - left, 0);
}
// We need this check so that the math does not result in NaN
if ((rect.Height == Double.PositiveInfinity) || (Height == Double.PositiveInfinity))
{
Height = Double.PositiveInfinity;
}
else
{
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
double maxBottom = Math.Max(Bottom, rect.Bottom);
Height = Math.Max(maxBottom - top, 0);
}
X = left;
Y = top;
}
}
public void Union(Point point)
{
Union(new Rect(point, point));
}
private bool ContainsInternal(double x, double y)
{
return ((x >= X) && (x - Width <= X) &&
(y >= Y) && (y - Height <= Y));
}
internal bool IntersectsWith(Rect rect)
{
if (Width < 0 || rect.Width < 0)
{
return false;
}
return (rect.X <= X + Width) &&
(rect.X + rect.Width >= X) &&
(rect.Y <= Y + Height) &&
(rect.Y + rect.Height >= Y);
}
private static Rect CreateEmptyRect()
{
Rect rect = new Rect();
// TODO: for consistency with width/height we should change these
// to assign directly to the backing fields.
rect.X = EmptyX;
rect.Y = EmptyY;
// the width and height properties prevent assignment of
// negative numbers so assign directly to the backing fields.
rect._width = (float)EmptyWidth;
rect._height = (float)EmptyHeight;
return rect;
}
public override string ToString()
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, null /* format provider */);
}
public string ToString(IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, provider);
}
string IFormattable.ToString(string format, IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
internal string ConvertToString(string format, IFormatProvider provider)
{
if (IsEmpty)
{
return SR.DirectUI_Empty;
}
// Helper to get the numeric list separator for a given culture.
char separator = TokenizerHelper.GetNumericListSeparator(provider);
return String.Format(provider,
"{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}",
separator,
_x,
_y,
_width,
_height);
}
public bool Equals(Rect value)
{
return (this == value);
}
public static bool operator ==(Rect rect1, Rect rect2)
{
return rect1.X == rect2.X &&
rect1.Y == rect2.Y &&
rect1.Width == rect2.Width &&
rect1.Height == rect2.Height;
}
public static bool operator !=(Rect rect1, Rect rect2)
{
return !(rect1 == rect2);
}
public override bool Equals(object o)
{
if ((null == o) || !(o is Rect))
{
return false;
}
Rect value = (Rect)o;
return (this == value);
}
public override int GetHashCode()
{
// Perform field-by-field XOR of HashCodes
return X.GetHashCode() ^
Y.GetHashCode() ^
Width.GetHashCode() ^
Height.GetHashCode();
}
}
}
#if !FEATURE_SLJ_PROJECTION_COMPAT
#pragma warning restore 436
#endif // !FEATURE_SLJ_PROJECTION_COMPAT
| |
// -------------------------------------
// Domain : IBT / Realtime.co
// Author : Nicholas Ventimiglia
// Product : Messaging and Storage
// Published : 2014
// -------------------------------------
#if !UNITY_WSA
using System;
using WebSocketSharp;
namespace Realtime.Messaging.Internal
{
public class WebSocketConnection : IDisposable
{
#region Attributes (1)
WebSocket _websocket;
#endregion
#region Methods - Public (3)
public void Connect(string url)
{
Uri uri;
var connectionId = Strings.RandomString(8);
var serverId = Strings.RandomNumber(1, 1000);
try
{
uri = new Uri(url);
}
catch (Exception)
{
throw new OrtcException(OrtcExceptionReason.InvalidArguments, String.Format("Invalid URL: {0}", url));
}
var prefix = "https".Equals(uri.Scheme) ? "wss" : "ws";
var connectionUrl = new Uri(String.Format("{0}://{1}:{2}/broadcast/{3}/{4}/websocket", prefix, uri.DnsSafeHost, uri.Port, serverId, connectionId));
if (_websocket != null)
Dispose();
_websocket = new WebSocket(connectionUrl.AbsoluteUri);
_websocket.OnOpen += _websocket_OnOpen;
_websocket.OnError += _websocket_OnError;
_websocket.OnClose += _websocket_OnClose;
_websocket.OnMessage += _websocket_OnMessage;
_websocket.Connect();
}
public void Close()
{
if (_websocket != null)
{
_websocket.Close();
}
}
public void Send(string message)
{
if (_websocket != null)
{
// Wrap in quotes, escape inner quotes
_websocket.Send(string.Format("\"{0}\"", message.Replace("\"", "\\\"")));
}
}
#endregion
#region Methods - Private (1)
#endregion
#region Delegates (4)
public delegate void OnOpenedDelegate();
public delegate void OnClosedDelegate();
public delegate void OnErrorDelegate(string error);
public delegate void OnMessageReceivedDelegate(string message);
#endregion
#region Events (4)
event OnOpenedDelegate _onOpened;
public event OnOpenedDelegate OnOpened
{
add
{
_onOpened = (OnOpenedDelegate)Delegate.Combine(_onOpened, value);
}
remove
{
_onOpened = (OnOpenedDelegate)Delegate.Remove(_onOpened, value);
}
}
event OnClosedDelegate _onClosed;
public event OnClosedDelegate OnClosed
{
add
{
_onClosed = (OnClosedDelegate)Delegate.Combine(_onClosed, value);
}
remove
{
_onClosed = (OnClosedDelegate)Delegate.Remove(_onClosed, value);
}
}
event OnErrorDelegate _onError;
public event OnErrorDelegate OnError
{
add
{
_onError = (OnErrorDelegate)Delegate.Combine(_onError, value);
}
remove
{
_onError = (OnErrorDelegate)Delegate.Remove(_onError, value);
}
}
event OnMessageReceivedDelegate _onMessageReceived;
public event OnMessageReceivedDelegate OnMessageReceived
{
add
{
_onMessageReceived = (OnMessageReceivedDelegate)Delegate.Combine(_onMessageReceived, value);
}
remove
{
_onMessageReceived = (OnMessageReceivedDelegate)Delegate.Remove(_onMessageReceived, value);
}
}
#endregion
#region Events Handles (4)
void _websocket_OnMessage(object sender, MessageEventArgs e)
{
var ev = _onMessageReceived;
if (ev != null)
{
ev(e.Data);
}
}
void _websocket_OnClose(object sender, CloseEventArgs e)
{
var ev = _onClosed;
if (ev != null)
{
ev();
}
}
void _websocket_OnError(object sender, ErrorEventArgs e)
{
var ev = _onError;
if (ev != null)
{
ev(e.Message);
}
}
void _websocket_OnOpen(object sender, EventArgs e)
{
var ev = _onOpened;
if (ev != null)
{
ev();}
}
#endregion
public void Dispose()
{
if (_websocket != null)
{
_websocket.Close();
_websocket.OnOpen -= _websocket_OnOpen;
_websocket.OnError -= _websocket_OnError;
_websocket.OnClose -= _websocket_OnClose;
_websocket.OnMessage -= _websocket_OnMessage;
}
_websocket = null;
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.AspNetCore.Http.Abstractions;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// Represents the host portion of a URI can be used to construct URI's properly formatted and encoded for use in
/// HTTP headers.
/// </summary>
public readonly struct HostString : IEquatable<HostString>
{
private readonly string _value;
/// <summary>
/// Creates a new HostString without modification. The value should be Unicode rather than punycode, and may have a port.
/// IPv4 and IPv6 addresses are also allowed, and also may have ports.
/// </summary>
/// <param name="value"></param>
public HostString(string value)
{
_value = value;
}
/// <summary>
/// Creates a new HostString from its host and port parts.
/// </summary>
/// <param name="host">The value should be Unicode rather than punycode. IPv6 addresses must use square braces.</param>
/// <param name="port">A positive, greater than 0 value representing the port in the host string.</param>
public HostString(string host, int port)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
if (port <= 0)
{
throw new ArgumentOutOfRangeException(nameof(port), Resources.Exception_PortMustBeGreaterThanZero);
}
int index;
if (host.IndexOf('[') == -1
&& (index = host.IndexOf(':')) >= 0
&& index < host.Length - 1
&& host.IndexOf(':', index + 1) >= 0)
{
// IPv6 without brackets ::1 is the only type of host with 2 or more colons
host = $"[{host}]";
}
_value = host + ":" + port.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Returns the original value from the constructor.
/// </summary>
public string Value
{
get { return _value; }
}
/// <summary>
/// Returns true if the host is set.
/// </summary>
public bool HasValue
{
get { return !string.IsNullOrEmpty(_value); }
}
/// <summary>
/// Returns the value of the host part of the value. The port is removed if it was present.
/// IPv6 addresses will have brackets added if they are missing.
/// </summary>
/// <returns>The host portion of the value.</returns>
public string Host
{
get
{
GetParts(_value, out var host, out var port);
return host.ToString();
}
}
/// <summary>
/// Returns the value of the port part of the host, or <value>null</value> if none is found.
/// </summary>
/// <returns>The port portion of the value.</returns>
public int? Port
{
get
{
GetParts(_value, out var host, out var port);
if (!StringSegment.IsNullOrEmpty(port)
&& int.TryParse(port.AsSpan(), NumberStyles.None, CultureInfo.InvariantCulture, out var p))
{
return p;
}
return null;
}
}
/// <summary>
/// Returns the value as normalized by ToUriComponent().
/// </summary>
/// <returns>The value as normalized by <see cref="ToUriComponent"/>.</returns>
public override string ToString()
{
return ToUriComponent();
}
/// <summary>
/// Returns the value properly formatted and encoded for use in a URI in a HTTP header.
/// Any Unicode is converted to punycode. IPv6 addresses will have brackets added if they are missing.
/// </summary>
/// <returns>The <see cref="HostString"/> value formated for use in a URI or HTTP header.</returns>
public string ToUriComponent()
{
if (string.IsNullOrEmpty(_value))
{
return string.Empty;
}
int i;
for (i = 0; i < _value.Length; ++i)
{
if (!HostStringHelper.IsSafeHostStringChar(_value[i]))
{
break;
}
}
if (i != _value.Length)
{
GetParts(_value, out var host, out var port);
var mapping = new IdnMapping();
var encoded = mapping.GetAscii(host.Buffer!, host.Offset, host.Length);
return StringSegment.IsNullOrEmpty(port)
? encoded
: string.Concat(encoded, ":", port.ToString());
}
return _value;
}
/// <summary>
/// Creates a new HostString from the given URI component.
/// Any punycode will be converted to Unicode.
/// </summary>
/// <param name="uriComponent">The URI component string to create a <see cref="HostString"/> from.</param>
/// <returns>The <see cref="HostString"/> that was created.</returns>
public static HostString FromUriComponent(string uriComponent)
{
if (!string.IsNullOrEmpty(uriComponent))
{
int index;
if (uriComponent.IndexOf('[') >= 0)
{
// IPv6 in brackets [::1], maybe with port
}
else if ((index = uriComponent.IndexOf(':')) >= 0
&& index < uriComponent.Length - 1
&& uriComponent.IndexOf(':', index + 1) >= 0)
{
// IPv6 without brackets ::1 is the only type of host with 2 or more colons
}
else if (uriComponent.IndexOf("xn--", StringComparison.Ordinal) >= 0)
{
// Contains punycode
if (index >= 0)
{
// Has a port
string port = uriComponent.Substring(index);
var mapping = new IdnMapping();
uriComponent = mapping.GetUnicode(uriComponent, 0, index) + port;
}
else
{
var mapping = new IdnMapping();
uriComponent = mapping.GetUnicode(uriComponent);
}
}
}
return new HostString(uriComponent);
}
/// <summary>
/// Creates a new HostString from the host and port of the give Uri instance.
/// Punycode will be converted to Unicode.
/// </summary>
/// <param name="uri">The <see cref="Uri"/> to create a <see cref="HostString"/> from.</param>
/// <returns>The <see cref="HostString"/> that was created.</returns>
public static HostString FromUriComponent(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
return new HostString(uri.GetComponents(
UriComponents.NormalizedHost | // Always convert punycode to Unicode.
UriComponents.HostAndPort, UriFormat.Unescaped));
}
/// <summary>
/// Matches the host portion of a host header value against a list of patterns.
/// The host may be the encoded punycode or decoded unicode form so long as the pattern
/// uses the same format.
/// </summary>
/// <param name="value">Host header value with or without a port.</param>
/// <param name="patterns">A set of pattern to match, without ports.</param>
/// <remarks>
/// The port on the given value is ignored. The patterns should not have ports.
/// The patterns may be exact matches like "example.com", a top level wildcard "*"
/// that matches all hosts, or a subdomain wildcard like "*.example.com" that matches
/// "abc.example.com:443" but not "example.com:443".
/// Matching is case insensitive.
/// </remarks>
/// <returns><see langword="true" /> if <paramref name="value"/> matches any of the patterns.</returns>
public static bool MatchesAny(StringSegment value, IList<StringSegment> patterns)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (patterns == null)
{
throw new ArgumentNullException(nameof(patterns));
}
// Drop the port
GetParts(value, out var host, out var port);
for (int i = 0; i < port.Length; i++)
{
if (port[i] < '0' || '9' < port[i])
{
throw new FormatException($"The given host value '{value}' has a malformed port.");
}
}
var count = patterns.Count;
for (int i = 0; i < count; i++)
{
var pattern = patterns[i];
if (pattern == "*")
{
return true;
}
if (StringSegment.Equals(pattern, host, StringComparison.OrdinalIgnoreCase))
{
return true;
}
// Sub-domain wildcards: *.example.com
if (pattern.StartsWith("*.", StringComparison.Ordinal) && host.Length >= pattern.Length)
{
// .example.com
var allowedRoot = pattern.Subsegment(1);
var hostRoot = host.Subsegment(host.Length - allowedRoot.Length);
if (hostRoot.Equals(allowedRoot, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Compares the equality of the Value property, ignoring case.
/// </summary>
/// <param name="other">The <see cref="HostString"/> to compare against.</param>
/// <returns><see langword="true" /> if they have the same value.</returns>
public bool Equals(HostString other)
{
if (!HasValue && !other.HasValue)
{
return true;
}
return string.Equals(_value, other._value, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Compares against the given object only if it is a HostString.
/// </summary>
/// <param name="obj">The <see cref="object"/> to compare against.</param>
/// <returns><see langword="true" /> if they have the same value.</returns>
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj))
{
return !HasValue;
}
return obj is HostString && Equals((HostString)obj);
}
/// <summary>
/// Gets a hash code for the value.
/// </summary>
/// <returns>The hash code as an <see cref="int"/>.</returns>
public override int GetHashCode()
{
return (HasValue ? StringComparer.OrdinalIgnoreCase.GetHashCode(_value) : 0);
}
/// <summary>
/// Compares the two instances for equality.
/// </summary>
/// <param name="left">The left parameter.</param>
/// <param name="right">The right parameter.</param>
/// <returns><see langword="true" /> if both <see cref="HostString"/>'s have the same value.</returns>
public static bool operator ==(HostString left, HostString right)
{
return left.Equals(right);
}
/// <summary>
/// Compares the two instances for inequality.
/// </summary>
/// <param name="left">The left parameter.</param>
/// <param name="right">The right parameter.</param>
/// <returns><see langword="true" /> if both <see cref="HostString"/>'s values are not equal.</returns>
public static bool operator !=(HostString left, HostString right)
{
return !left.Equals(right);
}
/// <summary>
/// Parses the current value. IPv6 addresses will have brackets added if they are missing.
/// </summary>
/// <param name="value">The value to get the parts of.</param>
/// <param name="host">The portion of the <paramref name="value"/> which represents the host.</param>
/// <param name="port">The portion of the <paramref name="value"/> which represents the port.</param>
private static void GetParts(StringSegment value, out StringSegment host, out StringSegment port)
{
int index;
port = null;
host = null;
if (StringSegment.IsNullOrEmpty(value))
{
return;
}
else if ((index = value.IndexOf(']')) >= 0)
{
// IPv6 in brackets [::1], maybe with port
host = value.Subsegment(0, index + 1);
// Is there a colon and at least one character?
if (index + 2 < value.Length && value[index + 1] == ':')
{
port = value.Subsegment(index + 2);
}
}
else if ((index = value.IndexOf(':')) >= 0
&& index < value.Length - 1
&& value.IndexOf(':', index + 1) >= 0)
{
// IPv6 without brackets ::1 is the only type of host with 2 or more colons
host = $"[{value}]";
port = null;
}
else if (index >= 0)
{
// Has a port
host = value.Subsegment(0, index);
port = value.Subsegment(index + 1);
}
else
{
host = value;
port = 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.
// --------------------------------------------------------------------------------------
//
// A class that provides a simple, lightweight implementation of lazy initialization,
// obviating the need for a developer to implement a custom, thread-safe lazy initialization
// solution.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.ExceptionServices;
using System.Threading;
namespace System
{
internal enum LazyState
{
NoneViaConstructor = 0,
NoneViaFactory = 1,
NoneException = 2,
PublicationOnlyViaConstructor = 3,
PublicationOnlyViaFactory = 4,
PublicationOnlyWait = 5,
PublicationOnlyException = 6,
ExecutionAndPublicationViaConstructor = 7,
ExecutionAndPublicationViaFactory = 8,
ExecutionAndPublicationException = 9,
}
/// <summary>
/// LazyHelper serves multiples purposes
/// - minimizing code size of Lazy<T> by implementing as much of the code that is not generic
/// this reduces generic code bloat, making faster class initialization
/// - contains singleton objects that are used to handle threading primitives for PublicationOnly mode
/// - allows for instantiation for ExecutionAndPublication so as to create an object for locking on
/// - holds exception information.
/// </summary>
internal class LazyHelper
{
internal static readonly LazyHelper NoneViaConstructor = new LazyHelper(LazyState.NoneViaConstructor);
internal static readonly LazyHelper NoneViaFactory = new LazyHelper(LazyState.NoneViaFactory);
internal static readonly LazyHelper PublicationOnlyViaConstructor = new LazyHelper(LazyState.PublicationOnlyViaConstructor);
internal static readonly LazyHelper PublicationOnlyViaFactory = new LazyHelper(LazyState.PublicationOnlyViaFactory);
internal static readonly LazyHelper PublicationOnlyWaitForOtherThreadToPublish = new LazyHelper(LazyState.PublicationOnlyWait);
internal LazyState State { get; }
private readonly ExceptionDispatchInfo? _exceptionDispatch;
/// <summary>
/// Constructor that defines the state
/// </summary>
internal LazyHelper(LazyState state)
{
State = state;
}
/// <summary>
/// Constructor used for exceptions
/// </summary>
internal LazyHelper(LazyThreadSafetyMode mode, Exception exception)
{
switch (mode)
{
case LazyThreadSafetyMode.ExecutionAndPublication:
State = LazyState.ExecutionAndPublicationException;
break;
case LazyThreadSafetyMode.None:
State = LazyState.NoneException;
break;
case LazyThreadSafetyMode.PublicationOnly:
State = LazyState.PublicationOnlyException;
break;
default:
Debug.Fail("internal constructor, this should never occur");
break;
}
_exceptionDispatch = ExceptionDispatchInfo.Capture(exception);
}
[DoesNotReturn]
internal void ThrowException()
{
Debug.Assert(_exceptionDispatch != null, "execution path is invalid");
_exceptionDispatch.Throw();
}
private LazyThreadSafetyMode GetMode()
{
switch (State)
{
case LazyState.NoneViaConstructor:
case LazyState.NoneViaFactory:
case LazyState.NoneException:
return LazyThreadSafetyMode.None;
case LazyState.PublicationOnlyViaConstructor:
case LazyState.PublicationOnlyViaFactory:
case LazyState.PublicationOnlyWait:
case LazyState.PublicationOnlyException:
return LazyThreadSafetyMode.PublicationOnly;
case LazyState.ExecutionAndPublicationViaConstructor:
case LazyState.ExecutionAndPublicationViaFactory:
case LazyState.ExecutionAndPublicationException:
return LazyThreadSafetyMode.ExecutionAndPublication;
default:
Debug.Fail("Invalid logic; State should always have a valid value");
return default;
}
}
internal static LazyThreadSafetyMode? GetMode(LazyHelper? state)
{
if (state == null)
return null; // we don't know the mode anymore
return state.GetMode();
}
internal static bool GetIsValueFaulted(LazyHelper? state) => state?._exceptionDispatch != null;
internal static LazyHelper Create(LazyThreadSafetyMode mode, bool useDefaultConstructor)
{
switch (mode)
{
case LazyThreadSafetyMode.None:
return useDefaultConstructor ? NoneViaConstructor : NoneViaFactory;
case LazyThreadSafetyMode.PublicationOnly:
return useDefaultConstructor ? PublicationOnlyViaConstructor : PublicationOnlyViaFactory;
case LazyThreadSafetyMode.ExecutionAndPublication:
// we need to create an object for ExecutionAndPublication because we use Monitor-based locking
LazyState state = useDefaultConstructor ?
LazyState.ExecutionAndPublicationViaConstructor :
LazyState.ExecutionAndPublicationViaFactory;
return new LazyHelper(state);
default:
throw new ArgumentOutOfRangeException(nameof(mode), SR.Lazy_ctor_ModeInvalid);
}
}
internal static T CreateViaDefaultConstructor<T>()
{
try
{
return Activator.CreateInstance<T>();
}
catch (MissingMethodException)
{
throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
}
internal static LazyThreadSafetyMode GetModeFromIsThreadSafe(bool isThreadSafe)
{
return isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None;
}
}
/// <summary>
/// Provides support for lazy initialization.
/// </summary>
/// <typeparam name="T">Specifies the type of element being lazily initialized.</typeparam>
/// <remarks>
/// <para>
/// By default, all public and protected members of <see cref="Lazy{T}"/> are thread-safe and may be used
/// concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance
/// using parameters to the type's constructors.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(LazyDebugView<>))]
[DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")]
public class Lazy<T>
{
private static T CreateViaDefaultConstructor() => LazyHelper.CreateViaDefaultConstructor<T>();
// _state, a volatile reference, is set to null after _value has been set
private volatile LazyHelper? _state;
// we ensure that _factory when finished is set to null to allow garbage collector to clean up
// any referenced items
private Func<T>? _factory;
// _value eventually stores the lazily created value. It is valid when _state = null.
private T _value = default!;
/// <summary>
/// Initializes a new instance of the <see cref="System.Lazy{T}"/> class that
/// uses <typeparamref name="T"/>'s default constructor for lazy initialization.
/// </summary>
/// <remarks>
/// An instance created with this constructor may be used concurrently from multiple threads.
/// </remarks>
public Lazy()
: this(null, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor: true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="System.Lazy{T}"/> class that
/// uses a pre-initialized specified value.
/// </summary>
/// <remarks>
/// An instance created with this constructor should be usable by multiple threads
/// concurrently.
/// </remarks>
public Lazy(T value)
{
_value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="System.Lazy{T}"/> class that uses a
/// specified initialization function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="System.Func{T}"/> invoked to produce the lazily-initialized value when it is
/// needed.
/// </param>
/// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <remarks>
/// An instance created with this constructor may be used concurrently from multiple threads.
/// </remarks>
public Lazy(Func<T> valueFactory)
: this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor: false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="System.Lazy{T}"/>
/// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode.
/// </summary>
/// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time.
/// </param>
public Lazy(bool isThreadSafe) :
this(null, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor: true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="System.Lazy{T}"/>
/// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode.
/// </summary>
/// <param name="mode">The lazy thread-safety mode</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception>
public Lazy(LazyThreadSafetyMode mode) :
this(null, mode, useDefaultConstructor: true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="System.Lazy{T}"/> class
/// that uses a specified initialization function and a specified thread-safety mode.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed.
/// </param>
/// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time.
/// </param>
/// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is
/// a null reference (Nothing in Visual Basic).</exception>
public Lazy(Func<T> valueFactory, bool isThreadSafe) :
this(valueFactory, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor: false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="System.Lazy{T}"/> class
/// that uses a specified initialization function and a specified thread-safety mode.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed.
/// </param>
/// <param name="mode">The lazy thread-safety mode.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is
/// a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid value.</exception>
public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode)
: this(valueFactory, mode, useDefaultConstructor: false)
{
}
private Lazy(Func<T>? valueFactory, LazyThreadSafetyMode mode, bool useDefaultConstructor)
{
if (valueFactory == null && !useDefaultConstructor)
throw new ArgumentNullException(nameof(valueFactory));
_factory = valueFactory;
_state = LazyHelper.Create(mode, useDefaultConstructor);
}
private void ViaConstructor()
{
_value = CreateViaDefaultConstructor();
_state = null; // volatile write, must occur after setting _value
}
private void ViaFactory(LazyThreadSafetyMode mode)
{
try
{
Func<T>? factory = _factory;
if (factory == null)
throw new InvalidOperationException(SR.Lazy_Value_RecursiveCallsToValue);
_factory = null;
_value = factory();
_state = null; // volatile write, must occur after setting _value
}
catch (Exception exception)
{
_state = new LazyHelper(mode, exception);
throw;
}
}
private void ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor)
{
lock (executionAndPublication)
{
// it's possible for multiple calls to have piled up behind the lock, so we need to check
// to see if the ExecutionAndPublication object is still the current implementation.
if (ReferenceEquals(_state, executionAndPublication))
{
if (useDefaultConstructor)
{
ViaConstructor();
}
else
{
ViaFactory(LazyThreadSafetyMode.ExecutionAndPublication);
}
}
}
}
private void PublicationOnly(LazyHelper publicationOnly, T possibleValue)
{
LazyHelper? previous = Interlocked.CompareExchange(ref _state, LazyHelper.PublicationOnlyWaitForOtherThreadToPublish, publicationOnly);
if (previous == publicationOnly)
{
_factory = null;
_value = possibleValue;
_state = null; // volatile write, must occur after setting _value
}
}
private void PublicationOnlyViaConstructor(LazyHelper initializer)
{
PublicationOnly(initializer, CreateViaDefaultConstructor());
}
private void PublicationOnlyViaFactory(LazyHelper initializer)
{
Func<T>? factory = _factory;
if (factory == null)
{
PublicationOnlyWaitForOtherThreadToPublish();
}
else
{
PublicationOnly(initializer, factory());
}
}
private void PublicationOnlyWaitForOtherThreadToPublish()
{
var spinWait = new SpinWait();
while (!ReferenceEquals(_state, null))
{
// We get here when PublicationOnly temporarily sets _state to LazyHelper.PublicationOnlyWaitForOtherThreadToPublish.
// This temporary state should be quickly followed by _state being set to null.
spinWait.SpinOnce();
}
}
private T CreateValue()
{
// we have to create a copy of state here, and use the copy exclusively from here on in
// so as to ensure thread safety.
LazyHelper? state = _state;
if (state != null)
{
switch (state.State)
{
case LazyState.NoneViaConstructor:
ViaConstructor();
break;
case LazyState.NoneViaFactory:
ViaFactory(LazyThreadSafetyMode.None);
break;
case LazyState.PublicationOnlyViaConstructor:
PublicationOnlyViaConstructor(state);
break;
case LazyState.PublicationOnlyViaFactory:
PublicationOnlyViaFactory(state);
break;
case LazyState.PublicationOnlyWait:
PublicationOnlyWaitForOtherThreadToPublish();
break;
case LazyState.ExecutionAndPublicationViaConstructor:
ExecutionAndPublication(state, useDefaultConstructor: true);
break;
case LazyState.ExecutionAndPublicationViaFactory:
ExecutionAndPublication(state, useDefaultConstructor: false);
break;
default:
state.ThrowException();
break;
}
}
return Value;
}
/// <summary>Creates and returns a string representation of this instance.</summary>
/// <returns>The result of calling <see cref="object.ToString"/> on the <see
/// cref="Value"/>.</returns>
/// <exception cref="System.NullReferenceException">
/// The <see cref="Value"/> is null.
/// </exception>
public override string? ToString()
{
return IsValueCreated ?
Value!.ToString() : // Throws NullReferenceException as if caller called ToString on the value itself
SR.Lazy_ToString_ValueNotCreated;
}
/// <summary>Gets the value of the Lazy<T> for debugging display purposes.</summary>
[MaybeNull]
internal T ValueForDebugDisplay
{
get
{
if (!IsValueCreated)
{
return default!;
}
return _value;
}
}
/// <summary>
/// Gets a value indicating whether this instance may be used concurrently from multiple threads.
/// </summary>
internal LazyThreadSafetyMode? Mode => LazyHelper.GetMode(_state);
/// <summary>
/// Gets whether the value creation is faulted or not
/// </summary>
internal bool IsValueFaulted => LazyHelper.GetIsValueFaulted(_state);
/// <summary>Gets a value indicating whether the <see cref="System.Lazy{T}"/> has been initialized.
/// </summary>
/// <value>true if the <see cref="System.Lazy{T}"/> instance has been initialized;
/// otherwise, false.</value>
/// <remarks>
/// The initialization of a <see cref="System.Lazy{T}"/> instance may result in either
/// a value being produced or an exception being thrown. If an exception goes unhandled during initialization,
/// <see cref="IsValueCreated"/> will return false.
/// </remarks>
public bool IsValueCreated => _state == null;
/// <summary>Gets the lazily initialized value of the current <see
/// cref="System.Lazy{T}"/>.</summary>
/// <value>The lazily initialized value of the current <see
/// cref="System.Lazy{T}"/>.</value>
/// <exception cref="System.MissingMemberException">
/// The <see cref="System.Lazy{T}"/> was initialized to use the default constructor
/// of the type being lazily initialized, and that type does not have a public, parameterless constructor.
/// </exception>
/// <exception cref="System.MemberAccessException">
/// The <see cref="System.Lazy{T}"/> was initialized to use the default constructor
/// of the type being lazily initialized, and permissions to access the constructor were missing.
/// </exception>
/// <exception cref="System.InvalidOperationException">
/// The <see cref="System.Lazy{T}"/> was constructed with the <see cref="System.Threading.LazyThreadSafetyMode.ExecutionAndPublication"/> or
/// <see cref="System.Threading.LazyThreadSafetyMode.None"/> and the initialization function attempted to access <see cref="Value"/> on this instance.
/// </exception>
/// <remarks>
/// If <see cref="IsValueCreated"/> is false, accessing <see cref="Value"/> will force initialization.
/// Please <see cref="System.Threading.LazyThreadSafetyMode"/> for more information on how <see cref="System.Lazy{T}"/> will behave if an exception is thrown
/// from initialization delegate.
/// </remarks>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Value => _state == null ? _value : CreateValue();
}
/// <summary>A debugger view of the Lazy<T> to surface additional debugging properties and
/// to ensure that the Lazy<T> does not become initialized if it was not already.</summary>
internal sealed class LazyDebugView<T>
{
// The Lazy object being viewed.
private readonly Lazy<T> _lazy;
/// <summary>Constructs a new debugger view object for the provided Lazy object.</summary>
/// <param name="lazy">A Lazy object to browse in the debugger.</param>
public LazyDebugView(Lazy<T> lazy)
{
_lazy = lazy;
}
/// <summary>Returns whether the Lazy object is initialized or not.</summary>
public bool IsValueCreated => _lazy.IsValueCreated;
/// <summary>Returns the value of the Lazy object.</summary>
public T Value => _lazy.ValueForDebugDisplay;
/// <summary>Returns the execution mode of the Lazy object</summary>
public LazyThreadSafetyMode? Mode => _lazy.Mode;
/// <summary>Returns the execution mode of the Lazy object</summary>
public bool IsValueFaulted => _lazy.IsValueFaulted;
}
}
| |
// 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.Net.Security;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class SspiCli
{
// TODO (Issue #3114): Throughout the entire file: replace with OS names from <sspi.h> and <schannel.h>
internal const uint SECQOP_WRAP_NO_ENCRYPT = 0x80000001;
internal const int SEC_I_RENEGOTIATE = 0x90321;
internal const int SECPKG_NEGOTIATION_COMPLETE = 0;
internal const int SECPKG_NEGOTIATION_OPTIMISTIC = 1;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct SSPIHandle
{
private IntPtr _handleHi;
private IntPtr _handleLo;
public bool IsZero
{
get { return _handleHi == IntPtr.Zero && HandleLo1 == IntPtr.Zero; }
}
public IntPtr HandleLo1
{
get
{
return _handleLo;
}
set
{
_handleLo = value;
}
}
internal void SetToInvalid()
{
_handleHi = IntPtr.Zero;
HandleLo1 = IntPtr.Zero;
}
public override string ToString()
{
{ return _handleHi.ToString("x") + ":" + HandleLo1.ToString("x"); }
}
}
internal enum ContextAttribute
{
Sizes = 0x00,
Names = 0x01,
Lifespan = 0x02,
DceInfo = 0x03,
StreamSizes = 0x04,
//KeyInfo = 0x05, must not be used, see ConnectionInfo instead
Authority = 0x06,
// SECPKG_ATTR_PROTO_INFO = 7,
// SECPKG_ATTR_PASSWORD_EXPIRY = 8,
// SECPKG_ATTR_SESSION_KEY = 9,
PackageInfo = 0x0A,
// SECPKG_ATTR_USER_FLAGS = 11,
NegotiationInfo = 0x0C,
// SECPKG_ATTR_NATIVE_NAMES = 13,
// SECPKG_ATTR_FLAGS = 14,
// SECPKG_ATTR_USE_VALIDATED = 15,
// SECPKG_ATTR_CREDENTIAL_NAME = 16,
// SECPKG_ATTR_TARGET_INFORMATION = 17,
// SECPKG_ATTR_ACCESS_TOKEN = 18,
// SECPKG_ATTR_TARGET = 19,
// SECPKG_ATTR_AUTHENTICATION_ID = 20,
UniqueBindings = 0x19,
EndpointBindings = 0x1A,
ClientSpecifiedSpn = 0x1B, // SECPKG_ATTR_CLIENT_SPECIFIED_TARGET = 27
RemoteCertificate = 0x53,
LocalCertificate = 0x54,
RootStore = 0x55,
IssuerListInfoEx = 0x59,
ConnectionInfo = 0x5A,
// SECPKG_ATTR_EAP_KEY_BLOCK 0x5b // returns SecPkgContext_EapKeyBlock
// SECPKG_ATTR_MAPPED_CRED_ATTR 0x5c // returns SecPkgContext_MappedCredAttr
// SECPKG_ATTR_SESSION_INFO 0x5d // returns SecPkgContext_SessionInfo
// SECPKG_ATTR_APP_DATA 0x5e // sets/returns SecPkgContext_SessionAppData
// SECPKG_ATTR_REMOTE_CERTIFICATES 0x5F // returns SecPkgContext_Certificates
// SECPKG_ATTR_CLIENT_CERT_POLICY 0x60 // sets SecPkgCred_ClientCertCtlPolicy
// SECPKG_ATTR_CC_POLICY_RESULT 0x61 // returns SecPkgContext_ClientCertPolicyResult
// SECPKG_ATTR_USE_NCRYPT 0x62 // Sets the CRED_FLAG_USE_NCRYPT_PROVIDER FLAG on cred group
// SECPKG_ATTR_LOCAL_CERT_INFO 0x63 // returns SecPkgContext_CertInfo
// SECPKG_ATTR_CIPHER_INFO 0x64 // returns new CNG SecPkgContext_CipherInfo
// SECPKG_ATTR_EAP_PRF_INFO 0x65 // sets SecPkgContext_EapPrfInfo
// SECPKG_ATTR_SUPPORTED_SIGNATURES 0x66 // returns SecPkgContext_SupportedSignatures
// SECPKG_ATTR_REMOTE_CERT_CHAIN 0x67 // returns PCCERT_CONTEXT
UiInfo = 0x68, // sets SEcPkgContext_UiInfo
}
// #define ISC_REQ_DELEGATE 0x00000001
// #define ISC_REQ_MUTUAL_AUTH 0x00000002
// #define ISC_REQ_REPLAY_DETECT 0x00000004
// #define ISC_REQ_SEQUENCE_DETECT 0x00000008
// #define ISC_REQ_CONFIDENTIALITY 0x00000010
// #define ISC_REQ_USE_SESSION_KEY 0x00000020
// #define ISC_REQ_PROMPT_FOR_CREDS 0x00000040
// #define ISC_REQ_USE_SUPPLIED_CREDS 0x00000080
// #define ISC_REQ_ALLOCATE_MEMORY 0x00000100
// #define ISC_REQ_USE_DCE_STYLE 0x00000200
// #define ISC_REQ_DATAGRAM 0x00000400
// #define ISC_REQ_CONNECTION 0x00000800
// #define ISC_REQ_CALL_LEVEL 0x00001000
// #define ISC_REQ_FRAGMENT_SUPPLIED 0x00002000
// #define ISC_REQ_EXTENDED_ERROR 0x00004000
// #define ISC_REQ_STREAM 0x00008000
// #define ISC_REQ_INTEGRITY 0x00010000
// #define ISC_REQ_IDENTIFY 0x00020000
// #define ISC_REQ_NULL_SESSION 0x00040000
// #define ISC_REQ_MANUAL_CRED_VALIDATION 0x00080000
// #define ISC_REQ_RESERVED1 0x00100000
// #define ISC_REQ_FRAGMENT_TO_FIT 0x00200000
// #define ISC_REQ_HTTP 0x10000000
// Win7 SP1 +
// #define ISC_REQ_UNVERIFIED_TARGET_NAME 0x20000000
// #define ASC_REQ_DELEGATE 0x00000001
// #define ASC_REQ_MUTUAL_AUTH 0x00000002
// #define ASC_REQ_REPLAY_DETECT 0x00000004
// #define ASC_REQ_SEQUENCE_DETECT 0x00000008
// #define ASC_REQ_CONFIDENTIALITY 0x00000010
// #define ASC_REQ_USE_SESSION_KEY 0x00000020
// #define ASC_REQ_ALLOCATE_MEMORY 0x00000100
// #define ASC_REQ_USE_DCE_STYLE 0x00000200
// #define ASC_REQ_DATAGRAM 0x00000400
// #define ASC_REQ_CONNECTION 0x00000800
// #define ASC_REQ_CALL_LEVEL 0x00001000
// #define ASC_REQ_EXTENDED_ERROR 0x00008000
// #define ASC_REQ_STREAM 0x00010000
// #define ASC_REQ_INTEGRITY 0x00020000
// #define ASC_REQ_LICENSING 0x00040000
// #define ASC_REQ_IDENTIFY 0x00080000
// #define ASC_REQ_ALLOW_NULL_SESSION 0x00100000
// #define ASC_REQ_ALLOW_NON_USER_LOGONS 0x00200000
// #define ASC_REQ_ALLOW_CONTEXT_REPLAY 0x00400000
// #define ASC_REQ_FRAGMENT_TO_FIT 0x00800000
// #define ASC_REQ_FRAGMENT_SUPPLIED 0x00002000
// #define ASC_REQ_NO_TOKEN 0x01000000
// #define ASC_REQ_HTTP 0x10000000
[Flags]
internal enum ContextFlags
{
Zero = 0,
// The server in the transport application can
// build new security contexts impersonating the
// client that will be accepted by other servers
// as the client's contexts.
Delegate = 0x00000001,
// The communicating parties must authenticate
// their identities to each other. Without MutualAuth,
// the client authenticates its identity to the server.
// With MutualAuth, the server also must authenticate
// its identity to the client.
MutualAuth = 0x00000002,
// The security package detects replayed packets and
// notifies the caller if a packet has been replayed.
// The use of this flag implies all of the conditions
// specified by the Integrity flag.
ReplayDetect = 0x00000004,
// The context must be allowed to detect out-of-order
// delivery of packets later through the message support
// functions. Use of this flag implies all of the
// conditions specified by the Integrity flag.
SequenceDetect = 0x00000008,
// The context must protect data while in transit.
// Confidentiality is supported for NTLM with Microsoft
// Windows NT version 4.0, SP4 and later and with the
// Kerberos protocol in Microsoft Windows 2000 and later.
Confidentiality = 0x00000010,
UseSessionKey = 0x00000020,
AllocateMemory = 0x00000100,
// Connection semantics must be used.
Connection = 0x00000800,
// Client applications requiring extended error messages specify the
// ISC_REQ_EXTENDED_ERROR flag when calling the InitializeSecurityContext
// Server applications requiring extended error messages set
// the ASC_REQ_EXTENDED_ERROR flag when calling AcceptSecurityContext.
InitExtendedError = 0x00004000,
AcceptExtendedError = 0x00008000,
// A transport application requests stream semantics
// by setting the ISC_REQ_STREAM and ASC_REQ_STREAM
// flags in the calls to the InitializeSecurityContext
// and AcceptSecurityContext functions
InitStream = 0x00008000,
AcceptStream = 0x00010000,
// Buffer integrity can be verified; however, replayed
// and out-of-sequence messages will not be detected
InitIntegrity = 0x00010000, // ISC_REQ_INTEGRITY
AcceptIntegrity = 0x00020000, // ASC_REQ_INTEGRITY
InitManualCredValidation = 0x00080000, // ISC_REQ_MANUAL_CRED_VALIDATION
InitUseSuppliedCreds = 0x00000080, // ISC_REQ_USE_SUPPLIED_CREDS
InitIdentify = 0x00020000, // ISC_REQ_IDENTIFY
AcceptIdentify = 0x00080000, // ASC_REQ_IDENTIFY
ProxyBindings = 0x04000000, // ASC_REQ_PROXY_BINDINGS
AllowMissingBindings = 0x10000000, // ASC_REQ_ALLOW_MISSING_BINDINGS
UnverifiedTargetName = 0x20000000, // ISC_REQ_UNVERIFIED_TARGET_NAME
}
internal enum Endianness
{
Network = 0x00,
Native = 0x10,
}
internal enum CredentialUse
{
Inbound = 0x1,
Outbound = 0x2,
Both = 0x3,
}
[StructLayout(LayoutKind.Sequential)]
internal struct _CERT_CHAIN_ELEMENT
{
public uint cbSize;
public IntPtr pCertContext;
// Since this structure is allocated by unmanaged code, we can
// omit the fields below since we don't need to access them
// CERT_TRUST_STATUS TrustStatus;
// IntPtr pRevocationInfo;
// IntPtr pIssuanceUsage;
// IntPtr pApplicationUsage;
}
// SecPkgContext_IssuerListInfoEx
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct IssuerListInfoEx
{
public SafeHandle aIssuers;
public uint cIssuers;
public unsafe IssuerListInfoEx(SafeHandle handle, byte[] nativeBuffer)
{
aIssuers = handle;
fixed (byte* voidPtr = nativeBuffer)
{
// TODO (Issue #3114): Properly marshal the struct instead of assuming no padding.
cIssuers = *((uint*)(voidPtr + IntPtr.Size));
}
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct SecureCredential
{
/*
typedef struct _SCHANNEL_CRED
{
DWORD dwVersion; // always SCHANNEL_CRED_VERSION
DWORD cCreds;
PCCERT_CONTEXT *paCred;
HCERTSTORE hRootStore;
DWORD cMappers;
struct _HMAPPER **aphMappers;
DWORD cSupportedAlgs;
ALG_ID * palgSupportedAlgs;
DWORD grbitEnabledProtocols;
DWORD dwMinimumCipherStrength;
DWORD dwMaximumCipherStrength;
DWORD dwSessionLifespan;
DWORD dwFlags;
DWORD reserved;
} SCHANNEL_CRED, *PSCHANNEL_CRED;
*/
public const int CurrentVersion = 0x4;
public int version;
public int cCreds;
// ptr to an array of pointers
// There is a hack done with this field. AcquireCredentialsHandle requires an array of
// certificate handles; we only ever use one. In order to avoid pinning a one element array,
// we copy this value onto the stack, create a pointer on the stack to the copied value,
// and replace this field with the pointer, during the call to AcquireCredentialsHandle.
// Then we fix it up afterwards. Fine as long as all the SSPI credentials are not
// supposed to be threadsafe.
public IntPtr certContextArray;
public IntPtr rootStore; // == always null, OTHERWISE NOT RELIABLE
public int cMappers;
public IntPtr phMappers; // == always null, OTHERWISE NOT RELIABLE
public int cSupportedAlgs;
public IntPtr palgSupportedAlgs; // == always null, OTHERWISE NOT RELIABLE
public int grbitEnabledProtocols;
public int dwMinimumCipherStrength;
public int dwMaximumCipherStrength;
public int dwSessionLifespan;
public SecureCredential.Flags dwFlags;
public int reserved;
[Flags]
public enum Flags
{
Zero = 0,
NoSystemMapper = 0x02,
NoNameCheck = 0x04,
ValidateManual = 0x08,
NoDefaultCred = 0x10,
ValidateAuto = 0x20,
SendAuxRecord = 0x00200000,
UseStrongCrypto = 0x00400000,
}
} // SecureCredential
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct SecurityBufferStruct
{
public int count;
public SecurityBufferType type;
public IntPtr token;
public static readonly int Size = sizeof(SecurityBufferStruct);
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe class SecurityBufferDescriptor
{
/*
typedef struct _SecBufferDesc {
ULONG ulVersion;
ULONG cBuffers;
PSecBuffer pBuffers;
} SecBufferDesc, * PSecBufferDesc;
*/
public readonly int Version;
public readonly int Count;
public void* UnmanagedPointer;
public SecurityBufferDescriptor(int count)
{
Version = 0;
Count = count;
UnmanagedPointer = null;
}
} // SecurityBufferDescriptor
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct AuthIdentity
{
// see SEC_WINNT_AUTH_IDENTITY_W
internal string UserName;
internal int UserNameLength;
internal string Domain;
internal int DomainLength;
internal string Password;
internal int PasswordLength;
internal int Flags;
}
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal static extern int EncryptMessage(
ref SSPIHandle contextHandle,
[In] uint qualityOfProtection,
[In, Out] SecurityBufferDescriptor inputOutput,
[In] uint sequenceNumber
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal static unsafe extern int DecryptMessage(
[In] ref SSPIHandle contextHandle,
[In, Out] SecurityBufferDescriptor inputOutput,
[In] uint sequenceNumber,
uint* qualityOfProtection
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal static extern int QuerySecurityContextToken(
ref SSPIHandle phContext,
[Out] out SecurityContextTokenHandle handle);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal static extern int FreeContextBuffer(
[In] IntPtr contextBuffer);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal static extern int FreeCredentialsHandle(
ref SSPIHandle handlePtr
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal static extern int DeleteSecurityContext(
ref SSPIHandle handlePtr
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal unsafe static extern int AcceptSecurityContext(
ref SSPIHandle credentialHandle,
[In] void* inContextPtr,
[In] SecurityBufferDescriptor inputBuffer,
[In] ContextFlags inFlags,
[In] Endianness endianness,
ref SSPIHandle outContextPtr,
[In, Out] SecurityBufferDescriptor outputBuffer,
[In, Out] ref ContextFlags attributes,
out long timeStamp
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal unsafe static extern int QueryContextAttributesW(
ref SSPIHandle contextHandle,
[In] ContextAttribute attribute,
[In] void* buffer);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal unsafe static extern int SetContextAttributesW(
ref SSPIHandle contextHandle,
[In] ContextAttribute attribute,
[In] byte[] buffer,
[In] int bufferSize);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal static extern int EnumerateSecurityPackagesW(
[Out] out int pkgnum,
[Out] out SafeFreeContextBuffer_SECURITY handle);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
internal unsafe static extern int AcquireCredentialsHandleW(
[In] string principal,
[In] string moduleName,
[In] int usage,
[In] void* logonID,
[In] ref AuthIdentity authdata,
[In] void* keyCallback,
[In] void* keyArgument,
ref SSPIHandle handlePtr,
[Out] out long timeStamp
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
internal unsafe static extern int AcquireCredentialsHandleW(
[In] string principal,
[In] string moduleName,
[In] int usage,
[In] void* logonID,
[In] IntPtr zero,
[In] void* keyCallback,
[In] void* keyArgument,
ref SSPIHandle handlePtr,
[Out] out long timeStamp
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
internal unsafe static extern int AcquireCredentialsHandleW(
[In] string principal,
[In] string moduleName,
[In] int usage,
[In] void* logonID,
[In] SafeSspiAuthDataHandle authdata,
[In] void* keyCallback,
[In] void* keyArgument,
ref SSPIHandle handlePtr,
[Out] out long timeStamp
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
internal unsafe static extern int AcquireCredentialsHandleW(
[In] string principal,
[In] string moduleName,
[In] int usage,
[In] void* logonID,
[In] ref SecureCredential authData,
[In] void* keyCallback,
[In] void* keyArgument,
ref SSPIHandle handlePtr,
[Out] out long timeStamp
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal unsafe static extern int InitializeSecurityContextW(
ref SSPIHandle credentialHandle,
[In] void* inContextPtr,
[In] byte* targetName,
[In] ContextFlags inFlags,
[In] int reservedI,
[In] Endianness endianness,
[In] SecurityBufferDescriptor inputBuffer,
[In] int reservedII,
ref SSPIHandle outContextPtr,
[In, Out] SecurityBufferDescriptor outputBuffer,
[In, Out] ref ContextFlags attributes,
out long timeStamp
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal unsafe static extern int CompleteAuthToken(
[In] void* inContextPtr,
[In, Out] SecurityBufferDescriptor inputBuffers
);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal unsafe static extern SecurityStatus SspiFreeAuthIdentity(
[In] IntPtr authData);
[DllImport(Interop.Libraries.Sspi, ExactSpelling = true, SetLastError = true)]
internal unsafe static extern SecurityStatus SspiEncodeStringsAsAuthIdentity(
[In] string userName,
[In] string domainName,
[In] string password,
[Out] out SafeSspiAuthDataHandle authData);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
namespace System.Xml
{
// Represents an entire document. An XmlDocument contains XML data.
public class XmlDocument : XmlNode
{
private XmlImplementation _implementation;
private DomNameTable _domNameTable; // hash table of XmlName
private XmlLinkedNode _lastChild;
private XmlNamedNodeMap _entities;
private Dictionary<string, List<WeakReference<XmlElement>>> _htElementIdMap;
//This variable represents the actual loading status. Since, IsLoading will
//be manipulated sometimes for adding content to EntityReference this variable
//has been added which would always represent the loading status of document.
private bool _actualLoadingStatus;
private XmlNodeChangedEventHandler _onNodeInsertingDelegate;
private XmlNodeChangedEventHandler _onNodeInsertedDelegate;
private XmlNodeChangedEventHandler _onNodeRemovingDelegate;
private XmlNodeChangedEventHandler _onNodeRemovedDelegate;
private XmlNodeChangedEventHandler _onNodeChangingDelegate;
private XmlNodeChangedEventHandler _onNodeChangedDelegate;
// false if there are no ent-ref present, true if ent-ref nodes are or were present (i.e. if all ent-ref were removed, the doc will not clear this flag)
internal bool fEntRefNodesPresent;
internal bool fCDataNodesPresent;
private bool _preserveWhitespace;
private bool _isLoading;
// special name strings for
internal string strDocumentName;
internal string strDocumentFragmentName;
internal string strCommentName;
internal string strTextName;
internal string strCDataSectionName;
internal string strEntityName;
internal string strID;
internal string strXmlns;
internal string strXml;
internal string strSpace;
internal string strLang;
internal string strEmpty;
internal string strNonSignificantWhitespaceName;
internal string strSignificantWhitespaceName;
internal string strReservedXmlns;
internal string strReservedXml;
internal String baseURI;
internal object objLock;
static internal EmptyEnumerator EmptyEnumerator = new EmptyEnumerator();
// Initializes a new instance of the XmlDocument class.
public XmlDocument() : this(new XmlImplementation())
{
}
// Initializes a new instance
// of the XmlDocument class with the specified XmlNameTable.
public XmlDocument(XmlNameTable nt) : this(new XmlImplementation(nt))
{
}
protected internal XmlDocument(XmlImplementation imp) : base()
{
_implementation = imp;
_domNameTable = new DomNameTable(this);
// force the following string instances to be default in the nametable
XmlNameTable nt = this.NameTable;
nt.Add(string.Empty);
strDocumentName = nt.Add("#document");
strDocumentFragmentName = nt.Add("#document-fragment");
strCommentName = nt.Add("#comment");
strTextName = nt.Add("#text");
strCDataSectionName = nt.Add("#cdata-section");
strEntityName = nt.Add("#entity");
strID = nt.Add("id");
strNonSignificantWhitespaceName = nt.Add("#whitespace");
strSignificantWhitespaceName = nt.Add("#significant-whitespace");
strXmlns = nt.Add("xmlns");
strXml = nt.Add("xml");
strSpace = nt.Add("space");
strLang = nt.Add("lang");
strReservedXmlns = nt.Add(XmlConst.ReservedNsXmlNs);
strReservedXml = nt.Add(XmlConst.ReservedNsXml);
strEmpty = nt.Add(String.Empty);
baseURI = String.Empty;
objLock = new object();
}
// NOTE: This does not correctly check start name char, but we cannot change it since it would be a breaking change.
internal static void CheckName(String name)
{
int endPos = ValidateNames.ParseNmtoken(name, 0);
if (endPos < name.Length)
{
throw new XmlException(SR.Format(SR.Xml_BadNameChar, XmlExceptionHelper.BuildCharExceptionArgs(name, endPos)));
}
}
internal XmlName AddXmlName(string prefix, string localName, string namespaceURI)
{
XmlName n = _domNameTable.AddName(prefix, localName, namespaceURI);
Debug.Assert((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix));
Debug.Assert(n.LocalName == localName);
Debug.Assert((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI));
return n;
}
internal XmlName GetXmlName(string prefix, string localName, string namespaceURI)
{
XmlName n = _domNameTable.GetName(prefix, localName, namespaceURI);
Debug.Assert(n == null || ((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix)));
Debug.Assert(n == null || n.LocalName == localName);
Debug.Assert(n == null || ((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI)));
return n;
}
internal XmlName AddAttrXmlName(string prefix, string localName, string namespaceURI)
{
XmlName xmlName = AddXmlName(prefix, localName, namespaceURI);
Debug.Assert((prefix == null) ? (xmlName.Prefix.Length == 0) : (prefix == xmlName.Prefix));
Debug.Assert(xmlName.LocalName == localName);
Debug.Assert((namespaceURI == null) ? (xmlName.NamespaceURI.Length == 0) : (xmlName.NamespaceURI == namespaceURI));
if (!this.IsLoading)
{
// Use atomized versions instead of prefix, localName and nsURI
object oPrefix = xmlName.Prefix;
object oNamespaceURI = xmlName.NamespaceURI;
object oLocalName = xmlName.LocalName;
if ((oPrefix == (object)strXmlns || (oPrefix == (object)strEmpty && oLocalName == (object)strXmlns)) ^ (oNamespaceURI == (object)strReservedXmlns))
throw new ArgumentException(SR.Format(SR.Xdom_Attr_Reserved_XmlNS, namespaceURI));
}
return xmlName;
}
// This function returns null because it is implication of removing schema.
// If removed more methods would have to be removed as well and it would make adding schema back much harder.
internal XmlName GetIDInfoByElement(XmlName eleName)
{
return null;
}
private WeakReference<XmlElement> GetElement(List<WeakReference<XmlElement>> elementList, XmlElement elem)
{
List<WeakReference<XmlElement>> gcElemRefs = new List<WeakReference<XmlElement>>();
foreach (WeakReference<XmlElement> elemRef in elementList)
{
XmlElement target;
if (!elemRef.TryGetTarget(out target))
//take notes on the garbage collected nodes
gcElemRefs.Add(elemRef);
else
{
if (target == elem)
return elemRef;
}
}
//Clear out the gced elements
foreach (WeakReference<XmlElement> elemRef in gcElemRefs)
elementList.Remove(elemRef);
return null;
}
internal void AddElementWithId(string id, XmlElement elem)
{
if (_htElementIdMap == null || !_htElementIdMap.ContainsKey(id))
{
if (_htElementIdMap == null)
_htElementIdMap = new Dictionary<string, List<WeakReference<XmlElement>>>();
List<WeakReference<XmlElement>> elementList = new List<WeakReference<XmlElement>>();
elementList.Add(new WeakReference<XmlElement>(elem));
_htElementIdMap.Add(id, elementList);
}
else
{
// there are other element(s) that has the same id
List<WeakReference<XmlElement>> elementList = _htElementIdMap[id];
if (GetElement(elementList, elem) == null)
elementList.Add(new WeakReference<XmlElement>(elem));
}
}
internal void RemoveElementWithId(string id, XmlElement elem)
{
if (_htElementIdMap != null && _htElementIdMap.ContainsKey(id))
{
List<WeakReference<XmlElement>> elementList = _htElementIdMap[id];
WeakReference<XmlElement> elemRef = GetElement(elementList, elem);
if (elemRef != null)
{
elementList.Remove(elemRef);
if (elementList.Count == 0)
_htElementIdMap.Remove(id);
}
}
}
// Creates a duplicate of this node.
public override XmlNode CloneNode(bool deep)
{
XmlDocument clone = Implementation.CreateDocument();
clone.SetBaseURI(this.baseURI);
if (deep)
clone.ImportChildren(this, clone, deep);
return clone;
}
// Gets the type of the current node.
public override XmlNodeType NodeType
{
get { return XmlNodeType.Document; }
}
public override XmlNode ParentNode
{
get { return null; }
}
// Gets the node for the DOCTYPE declaration.
internal virtual XmlDocumentType DocumentType
{
get { return (XmlDocumentType)FindChild(XmlNodeType.DocumentType); }
}
internal virtual XmlDeclaration Declaration
{
get
{
if (HasChildNodes)
{
XmlDeclaration dec = FirstChild as XmlDeclaration;
return dec;
}
return null;
}
}
// Gets the XmlImplementation object for this document.
public XmlImplementation Implementation
{
get { return _implementation; }
}
// Gets the name of the node.
public override String Name
{
get { return strDocumentName; }
}
// Gets the name of the current node without the namespace prefix.
public override String LocalName
{
get { return strDocumentName; }
}
// Gets the root XmlElement for the document.
public XmlElement DocumentElement
{
get { return (XmlElement)FindChild(XmlNodeType.Element); }
}
internal override bool IsContainer
{
get { return true; }
}
internal override XmlLinkedNode LastNode
{
get { return _lastChild; }
set { _lastChild = value; }
}
// Gets the XmlDocument that contains this node.
public override XmlDocument OwnerDocument
{
get { return null; }
}
internal override bool IsValidChildType(XmlNodeType type)
{
switch (type)
{
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return true;
case XmlNodeType.DocumentType:
if (DocumentType != null)
throw new InvalidOperationException(SR.Xdom_DualDocumentTypeNode);
return true;
case XmlNodeType.Element:
if (DocumentElement != null)
throw new InvalidOperationException(SR.Xdom_DualDocumentElementNode);
return true;
case XmlNodeType.XmlDeclaration:
if (Declaration != null)
throw new InvalidOperationException(SR.Xdom_DualDeclarationNode);
return true;
default:
return false;
}
}
// the function examines all the siblings before the refNode
// if any of the nodes has type equals to "nt", return true; otherwise, return false;
private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode refNode)
{
if (refNode == null)
return false;
XmlNode node = null;
if (refNode.ParentNode != null)
node = refNode.ParentNode.FirstChild;
while (node != null)
{
if (node.NodeType == nt)
return true;
if (node == refNode)
break;
node = node.NextSibling;
}
return false;
}
// the function examines all the siblings after the refNode
// if any of the nodes has the type equals to "nt", return true; otherwise, return false;
private bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode refNode)
{
XmlNode node = refNode;
while (node != null)
{
if (node.NodeType == nt)
return true;
node = node.NextSibling;
}
return false;
}
internal override bool CanInsertBefore(XmlNode newChild, XmlNode refChild)
{
if (refChild == null)
refChild = FirstChild;
if (refChild == null)
return true;
switch (newChild.NodeType)
{
case XmlNodeType.XmlDeclaration:
return (refChild == FirstChild);
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
return refChild.NodeType != XmlNodeType.XmlDeclaration;
case XmlNodeType.DocumentType:
{
if (refChild.NodeType != XmlNodeType.XmlDeclaration)
{
//if refChild is not the XmlDeclaration node, only need to go through the sibling before and including refChild to
// make sure no Element ( rootElem node ) before the current position
return !HasNodeTypeInPrevSiblings(XmlNodeType.Element, refChild.PreviousSibling);
}
}
break;
case XmlNodeType.Element:
{
if (refChild.NodeType != XmlNodeType.XmlDeclaration)
{
//if refChild is not the XmlDeclaration node, only need to go through the siblings after and including the refChild to
// make sure no DocType node and XmlDeclaration node after the current position.
return !HasNodeTypeInNextSiblings(XmlNodeType.DocumentType, refChild);
}
}
break;
}
return false;
}
internal override bool CanInsertAfter(XmlNode newChild, XmlNode refChild)
{
if (refChild == null)
refChild = LastChild;
if (refChild == null)
return true;
switch (newChild.NodeType)
{
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return true;
case XmlNodeType.DocumentType:
{
//we will have to go through all the siblings before the refChild just to make sure no Element node ( rootElem )
// before the current position
return !HasNodeTypeInPrevSiblings(XmlNodeType.Element, refChild);
}
case XmlNodeType.Element:
{
return !HasNodeTypeInNextSiblings(XmlNodeType.DocumentType, refChild.NextSibling);
}
}
return false;
}
// Creates an XmlAttribute with the specified name.
public XmlAttribute CreateAttribute(String name)
{
String prefix = String.Empty;
String localName = String.Empty;
String namespaceURI = String.Empty;
SplitName(name, out prefix, out localName);
SetDefaultNamespace(prefix, localName, ref namespaceURI);
return CreateAttribute(prefix, localName, namespaceURI);
}
internal void SetDefaultNamespace(String prefix, String localName, ref String namespaceURI)
{
if (prefix == strXmlns || (prefix.Length == 0 && localName == strXmlns))
{
namespaceURI = strReservedXmlns;
}
else if (prefix == strXml)
{
namespaceURI = strReservedXml;
}
}
// Creates a XmlCDataSection containing the specified data.
public virtual XmlCDataSection CreateCDataSection(String data)
{
fCDataNodesPresent = true;
return new XmlCDataSection(data, this);
}
// Creates an XmlComment containing the specified data.
public virtual XmlComment CreateComment(String data)
{
return new XmlComment(data, this);
}
// Returns a new XmlDocumentType object.
internal virtual XmlDocumentType CreateDocumentType(string name, string publicId, string systemId, string internalSubset)
{
return new XmlDocumentType(name, publicId, systemId, internalSubset, this);
}
// Creates an XmlDocumentFragment.
public virtual XmlDocumentFragment CreateDocumentFragment()
{
return new XmlDocumentFragment(this);
}
// Creates an element with the specified name.
public XmlElement CreateElement(String name)
{
string prefix = String.Empty;
string localName = String.Empty;
SplitName(name, out prefix, out localName);
return CreateElement(prefix, localName, string.Empty);
}
// Creates an XmlEntityReference with the specified name.
internal virtual XmlEntityReference CreateEntityReference(String name)
{
return new XmlEntityReference(name, this);
}
// Creates a XmlProcessingInstruction with the specified name
// and data strings.
public virtual XmlProcessingInstruction CreateProcessingInstruction(String target, String data)
{
return new XmlProcessingInstruction(target, data, this);
}
// Creates a XmlDeclaration node with the specified values.
public virtual XmlDeclaration CreateXmlDeclaration(String version, string encoding, string standalone)
{
return new XmlDeclaration(version, encoding, standalone, this);
}
// Creates an XmlText with the specified text.
public virtual XmlText CreateTextNode(String text)
{
return new XmlText(text, this);
}
// Creates a XmlSignificantWhitespace node.
public virtual XmlSignificantWhitespace CreateSignificantWhitespace(string text)
{
return new XmlSignificantWhitespace(text, this);
}
// Creates a XmlWhitespace node.
public virtual XmlWhitespace CreateWhitespace(string text)
{
return new XmlWhitespace(text, this);
}
// Returns an XmlNodeList containing
// a list of all descendant elements that match the specified name.
public virtual XmlNodeList GetElementsByTagName(String name)
{
return new XmlElementList(this, name);
}
// DOM Level 2
// Creates an XmlAttribute with the specified LocalName
// and NamespaceURI.
public XmlAttribute CreateAttribute(String qualifiedName, String namespaceURI)
{
string prefix = String.Empty;
string localName = String.Empty;
SplitName(qualifiedName, out prefix, out localName);
return CreateAttribute(prefix, localName, namespaceURI);
}
// Creates an XmlElement with the specified LocalName and
// NamespaceURI.
public XmlElement CreateElement(String qualifiedName, String namespaceURI)
{
string prefix = String.Empty;
string localName = String.Empty;
SplitName(qualifiedName, out prefix, out localName);
return CreateElement(prefix, localName, namespaceURI);
}
// Returns a XmlNodeList containing
// a list of all descendant elements that match the specified name.
public virtual XmlNodeList GetElementsByTagName(String localName, String namespaceURI)
{
return new XmlElementList(this, localName, namespaceURI);
}
// Returns the XmlElement with the specified ID.
internal virtual XmlElement GetElementById(string elementId)
{
if (_htElementIdMap != null)
{
List<WeakReference<XmlElement>> elementList;
if (_htElementIdMap.TryGetValue(elementId, out elementList))
{
foreach (WeakReference<XmlElement> elemRef in elementList)
{
XmlElement elem;
if (elemRef.TryGetTarget(out elem))
{
if (elem != null
&& elem.IsConnected())
return elem;
}
}
}
}
return null;
}
// Imports a node from another document to this document.
public virtual XmlNode ImportNode(XmlNode node, bool deep)
{
return ImportNodeInternal(node, deep);
}
private XmlNode ImportNodeInternal(XmlNode node, bool deep)
{
XmlNode newNode = null;
if (node == null)
{
throw new InvalidOperationException(SR.Xdom_Import_NullNode);
}
else
{
switch (node.NodeType)
{
case XmlNodeType.Element:
newNode = CreateElement(node.Prefix, node.LocalName, node.NamespaceURI);
ImportAttributes(node, newNode);
if (deep)
ImportChildren(node, newNode, deep);
break;
case XmlNodeType.Attribute:
Debug.Assert(((XmlAttribute)node).Specified);
newNode = CreateAttribute(node.Prefix, node.LocalName, node.NamespaceURI);
ImportChildren(node, newNode, true);
break;
case XmlNodeType.Text:
newNode = CreateTextNode(node.Value);
break;
case XmlNodeType.Comment:
newNode = CreateComment(node.Value);
break;
case XmlNodeType.ProcessingInstruction:
newNode = CreateProcessingInstruction(node.Name, node.Value);
break;
case XmlNodeType.XmlDeclaration:
XmlDeclaration decl = (XmlDeclaration)node;
newNode = CreateXmlDeclaration(decl.Version, decl.Encoding, decl.Standalone);
break;
case XmlNodeType.CDATA:
newNode = CreateCDataSection(node.Value);
break;
case XmlNodeType.DocumentType:
XmlDocumentType docType = (XmlDocumentType)node;
newNode = CreateDocumentType(docType.Name, docType.PublicId, docType.SystemId, docType.InternalSubset);
break;
case XmlNodeType.DocumentFragment:
newNode = CreateDocumentFragment();
if (deep)
ImportChildren(node, newNode, deep);
break;
case XmlNodeType.EntityReference:
newNode = CreateEntityReference(node.Name);
// we don't import the children of entity reference because they might result in different
// children nodes given different namespace context in the new document.
break;
case XmlNodeType.Whitespace:
newNode = CreateWhitespace(node.Value);
break;
case XmlNodeType.SignificantWhitespace:
newNode = CreateSignificantWhitespace(node.Value);
break;
default:
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, SR.Xdom_Import, node.NodeType.ToString()));
}
}
return newNode;
}
private void ImportAttributes(XmlNode fromElem, XmlNode toElem)
{
int cAttr = fromElem.Attributes.Count;
for (int iAttr = 0; iAttr < cAttr; iAttr++)
{
if (fromElem.Attributes[iAttr].Specified)
toElem.Attributes.SetNamedItem(ImportNodeInternal(fromElem.Attributes[iAttr], true));
}
}
private void ImportChildren(XmlNode fromNode, XmlNode toNode, bool deep)
{
Debug.Assert(toNode.NodeType != XmlNodeType.EntityReference);
for (XmlNode n = fromNode.FirstChild; n != null; n = n.NextSibling)
{
toNode.AppendChild(ImportNodeInternal(n, deep));
}
}
// Microsoft extensions
// Gets the XmlNameTable associated with this
// implementation.
public XmlNameTable NameTable
{
get { return _implementation.NameTable; }
}
// Creates a XmlAttribute with the specified Prefix, LocalName,
// and NamespaceURI.
public virtual XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI)
{
return new XmlAttribute(AddAttrXmlName(prefix, localName, namespaceURI), this);
}
internal virtual XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI)
{
return new XmlUnspecifiedAttribute(prefix, localName, namespaceURI, this);
}
public virtual XmlElement CreateElement(string prefix, string localName, string namespaceURI)
{
XmlElement elem = new XmlElement(AddXmlName(prefix, localName, namespaceURI), true, this);
return elem;
}
// Gets or sets a value indicating whether to preserve whitespace.
public bool PreserveWhitespace
{
get { return _preserveWhitespace; }
set { _preserveWhitespace = value; }
}
// Gets a value indicating whether the node is read-only.
public override bool IsReadOnly
{
get { return false; }
}
internal XmlNamedNodeMap Entities
{
get
{
if (_entities == null)
_entities = new XmlNamedNodeMap(this);
return _entities;
}
}
internal bool IsLoading
{
get { return _isLoading; }
set { _isLoading = value; }
}
internal bool ActualLoadingStatus
{
get { return _actualLoadingStatus; }
}
// Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI.
public virtual XmlNode CreateNode(XmlNodeType type, string prefix, string name, string namespaceURI)
{
switch (type)
{
case XmlNodeType.Element:
if (prefix != null)
return CreateElement(prefix, name, namespaceURI);
else
return CreateElement(name, namespaceURI);
case XmlNodeType.Attribute:
if (prefix != null)
return CreateAttribute(prefix, name, namespaceURI);
else
return CreateAttribute(name, namespaceURI);
case XmlNodeType.Text:
return CreateTextNode(string.Empty);
case XmlNodeType.CDATA:
return CreateCDataSection(string.Empty);
case XmlNodeType.EntityReference:
return CreateEntityReference(name);
case XmlNodeType.ProcessingInstruction:
return CreateProcessingInstruction(name, string.Empty);
case XmlNodeType.XmlDeclaration:
return CreateXmlDeclaration("1.0", null, null);
case XmlNodeType.Comment:
return CreateComment(string.Empty);
case XmlNodeType.DocumentFragment:
return CreateDocumentFragment();
case XmlNodeType.DocumentType:
return CreateDocumentType(name, string.Empty, string.Empty, string.Empty);
case XmlNodeType.Document:
return new XmlDocument();
case XmlNodeType.SignificantWhitespace:
return CreateSignificantWhitespace(string.Empty);
case XmlNodeType.Whitespace:
return CreateWhitespace(string.Empty);
default:
throw new ArgumentException(SR.Format(SR.Arg_CannotCreateNode, type));
}
}
// Creates an XmlNode with the specified node type, Name, and
// NamespaceURI.
public virtual XmlNode CreateNode(string nodeTypeString, string name, string namespaceURI)
{
return CreateNode(ConvertToNodeType(nodeTypeString), name, namespaceURI);
}
// Creates an XmlNode with the specified XmlNodeType, Name, and
// NamespaceURI.
public virtual XmlNode CreateNode(XmlNodeType type, string name, string namespaceURI)
{
return CreateNode(type, null, name, namespaceURI);
}
// Creates an XmlNode object based on the information in the XmlReader.
// The reader must be positioned on a node or attribute.
public virtual XmlNode ReadNode(XmlReader reader)
{
XmlNode node = null;
try
{
IsLoading = true;
XmlLoader loader = new XmlLoader();
node = loader.ReadCurrentNode(this, reader);
}
finally
{
IsLoading = false;
}
return node;
}
internal XmlNodeType ConvertToNodeType(string nodeTypeString)
{
if (nodeTypeString == "element")
{
return XmlNodeType.Element;
}
else if (nodeTypeString == "attribute")
{
return XmlNodeType.Attribute;
}
else if (nodeTypeString == "text")
{
return XmlNodeType.Text;
}
else if (nodeTypeString == "cdatasection")
{
return XmlNodeType.CDATA;
}
else if (nodeTypeString == "entityreference")
{
return XmlNodeType.EntityReference;
}
else if (nodeTypeString == "entity")
{
return XmlNodeType.Entity;
}
else if (nodeTypeString == "processinginstruction")
{
return XmlNodeType.ProcessingInstruction;
}
else if (nodeTypeString == "comment")
{
return XmlNodeType.Comment;
}
else if (nodeTypeString == "document")
{
return XmlNodeType.Document;
}
else if (nodeTypeString == "documenttype")
{
return XmlNodeType.DocumentType;
}
else if (nodeTypeString == "documentfragment")
{
return XmlNodeType.DocumentFragment;
}
else if (nodeTypeString == "notation")
{
return XmlNodeType.Notation;
}
else if (nodeTypeString == "significantwhitespace")
{
return XmlNodeType.SignificantWhitespace;
}
else if (nodeTypeString == "whitespace")
{
return XmlNodeType.Whitespace;
}
throw new ArgumentException(SR.Format(SR.Xdom_Invalid_NT_String, nodeTypeString));
}
public virtual void Load(Stream inStream)
{
XmlReader reader = XmlReader.Create(inStream);
try
{
Load(reader);
}
finally
{
reader.Dispose();
}
}
// Loads the XML document from the specified TextReader.
public virtual void Load(TextReader txtReader)
{
XmlReader reader = XmlReader.Create(txtReader);
try
{
Load(reader);
}
finally
{
reader.Dispose();
}
}
// Loads the XML document from the specified XmlReader.
public virtual void Load(XmlReader reader)
{
try
{
IsLoading = true;
_actualLoadingStatus = true;
RemoveAll();
fEntRefNodesPresent = false;
fCDataNodesPresent = false;
XmlLoader loader = new XmlLoader();
loader.Load(this, reader, _preserveWhitespace);
}
finally
{
IsLoading = false;
_actualLoadingStatus = false;
}
}
// Loads the XML document from the specified string.
public virtual void LoadXml(string xml)
{
XmlReader reader = XmlReader.Create(new StringReader(xml));
try
{
Load(reader);
}
finally
{
reader.Dispose();
}
}
//TextEncoding is the one from XmlDeclaration if there is any
internal Encoding TextEncoding
{
get
{
if (Declaration != null)
{
string value = Declaration.Encoding;
if (value.Length > 0)
{
return System.Text.Encoding.GetEncoding(value);
}
}
return null;
}
}
public override string InnerText
{
set
{
throw new InvalidOperationException(SR.Xdom_Document_Innertext);
}
}
public override string InnerXml
{
get
{
return base.InnerXml;
}
set
{
LoadXml(value);
}
}
//Saves out the to the file with exact content in the XmlDocument.
public virtual void Save(Stream outStream)
{
XmlDOMTextWriter xw = new XmlDOMTextWriter(outStream, TextEncoding);
if (_preserveWhitespace == false)
xw.Formatting = Formatting.Indented;
WriteTo(xw);
xw.Flush();
}
// Saves the XML document to the specified TextWriter.
//
//Saves out the file with xmldeclaration which has encoding value equal to
//that of textwriter's encoding
public virtual void Save(TextWriter writer)
{
XmlDOMTextWriter xw = new XmlDOMTextWriter(writer);
if (_preserveWhitespace == false)
xw.Formatting = Formatting.Indented;
Save(xw);
}
// Saves the XML document to the specified XmlWriter.
//
//Saves out the file with xmldeclaration which has encoding value equal to
//that of textwriter's encoding
public virtual void Save(XmlWriter w)
{
XmlNode n = this.FirstChild;
if (n == null)
return;
if (w.WriteState == WriteState.Start)
{
if (n is XmlDeclaration)
{
if (Standalone.Length == 0)
w.WriteStartDocument();
else if (Standalone == "yes")
w.WriteStartDocument(true);
else if (Standalone == "no")
w.WriteStartDocument(false);
n = n.NextSibling;
}
else
{
w.WriteStartDocument();
}
}
while (n != null)
{
n.WriteTo(w);
n = n.NextSibling;
}
w.Flush();
}
// Saves the node to the specified XmlWriter.
//
//Writes out the to the file with exact content in the XmlDocument.
public override void WriteTo(XmlWriter w)
{
WriteContentTo(w);
}
// Saves all the children of the node to the specified XmlWriter.
//
//Writes out the to the file with exact content in the XmlDocument.
public override void WriteContentTo(XmlWriter xw)
{
foreach (XmlNode n in this)
{
n.WriteTo(xw);
}
}
public event XmlNodeChangedEventHandler NodeInserting
{
add
{
_onNodeInsertingDelegate += value;
}
remove
{
_onNodeInsertingDelegate -= value;
}
}
public event XmlNodeChangedEventHandler NodeInserted
{
add
{
_onNodeInsertedDelegate += value;
}
remove
{
_onNodeInsertedDelegate -= value;
}
}
public event XmlNodeChangedEventHandler NodeRemoving
{
add
{
_onNodeRemovingDelegate += value;
}
remove
{
_onNodeRemovingDelegate -= value;
}
}
public event XmlNodeChangedEventHandler NodeRemoved
{
add
{
_onNodeRemovedDelegate += value;
}
remove
{
_onNodeRemovedDelegate -= value;
}
}
public event XmlNodeChangedEventHandler NodeChanging
{
add
{
_onNodeChangingDelegate += value;
}
remove
{
_onNodeChangingDelegate -= value;
}
}
public event XmlNodeChangedEventHandler NodeChanged
{
add
{
_onNodeChangedDelegate += value;
}
remove
{
_onNodeChangedDelegate -= value;
}
}
internal override XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action)
{
switch (action)
{
case XmlNodeChangedAction.Insert:
if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null)
{
return null;
}
break;
case XmlNodeChangedAction.Remove:
if (_onNodeRemovingDelegate == null && _onNodeRemovedDelegate == null)
{
return null;
}
break;
case XmlNodeChangedAction.Change:
if (_onNodeChangingDelegate == null && _onNodeChangedDelegate == null)
{
return null;
}
break;
}
return new XmlNodeChangedEventArgs(node, oldParent, newParent, oldValue, newValue, action);
}
internal XmlNodeChangedEventArgs GetInsertEventArgsForLoad(XmlNode node, XmlNode newParent)
{
if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null)
{
return null;
}
string nodeValue = node.Value;
return new XmlNodeChangedEventArgs(node, null, newParent, nodeValue, nodeValue, XmlNodeChangedAction.Insert);
}
internal override void BeforeEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
{
switch (args.Action)
{
case XmlNodeChangedAction.Insert:
if (_onNodeInsertingDelegate != null)
_onNodeInsertingDelegate(this, args);
break;
case XmlNodeChangedAction.Remove:
if (_onNodeRemovingDelegate != null)
_onNodeRemovingDelegate(this, args);
break;
case XmlNodeChangedAction.Change:
if (_onNodeChangingDelegate != null)
_onNodeChangingDelegate(this, args);
break;
}
}
}
internal override void AfterEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
{
switch (args.Action)
{
case XmlNodeChangedAction.Insert:
if (_onNodeInsertedDelegate != null)
_onNodeInsertedDelegate(this, args);
break;
case XmlNodeChangedAction.Remove:
if (_onNodeRemovedDelegate != null)
_onNodeRemovedDelegate(this, args);
break;
case XmlNodeChangedAction.Change:
if (_onNodeChangedDelegate != null)
_onNodeChangedDelegate(this, args);
break;
}
}
}
// The function such through schema info to find out if there exists a default attribute with passed in names in the passed in element
// If so, return the newly created default attribute (with children tree);
// Otherwise, return null.
// This function returns null because it is implication of removing schema.
// If removed more methods would have to be removed as well and it would make adding schema back much harder.
internal XmlAttribute GetDefaultAttribute(XmlElement elem, string attrPrefix, string attrLocalname, string attrNamespaceURI)
{
return null;
}
internal String Standalone
{
get
{
XmlDeclaration decl = Declaration;
if (decl != null)
return decl.Standalone;
return null;
}
}
internal XmlEntity GetEntityNode(String name)
{
if (DocumentType != null)
{
XmlNamedNodeMap entites = DocumentType.Entities;
if (entites != null)
return (XmlEntity)(entites.GetNamedItem(name));
}
return null;
}
public override String BaseURI
{
get { return baseURI; }
}
internal void SetBaseURI(String inBaseURI)
{
baseURI = inBaseURI;
}
internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc)
{
Debug.Assert(doc == this);
if (!IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict);
if (!CanInsertAfter(newChild, LastChild))
throw new InvalidOperationException(SR.Xdom_Node_Insert_Location);
XmlNodeChangedEventArgs args = GetInsertEventArgsForLoad(newChild, this);
if (args != null)
BeforeEvent(args);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (_lastChild == null)
{
newNode.next = newNode;
}
else
{
newNode.next = _lastChild.next;
_lastChild.next = newNode;
}
_lastChild = newNode;
newNode.SetParentForLoad(this);
if (args != null)
AfterEvent(args);
return newNode;
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright [email protected]
// Copyright iced contributors
using System;
using System.Linq;
using System.Text;
using Generator.Documentation.Rust;
using Generator.Enums;
using Generator.Enums.Encoder;
using Generator.IO;
namespace Generator.Encoder.Rust {
[Generator(TargetLanguage.Rust)]
sealed class RustInstrCreateGen : InstrCreateGen {
readonly GeneratorContext generatorContext;
readonly IdentifierConverter idConverter;
readonly RustDocCommentWriter docWriter;
readonly InstrCreateGenImpl gen;
readonly GenCreateNameArgs genNames;
readonly StringBuilder sb;
public RustInstrCreateGen(GeneratorContext generatorContext)
: base(generatorContext.Types) {
this.generatorContext = generatorContext;
idConverter = RustIdentifierConverter.Create();
docWriter = new RustDocCommentWriter(idConverter);
gen = new InstrCreateGenImpl(genTypes, idConverter, docWriter);
genNames = GenCreateNameArgs.RustNames;
sb = new StringBuilder();
}
protected override (TargetLanguage language, string id, string filename) GetFileInfo() =>
(TargetLanguage.Rust, "Create", generatorContext.Types.Dirs.GetRustFilename("instruction.rs"));
enum TryMethodKind {
// Can never fail
Normal,
// Calls 'Result' method then unwraps() the result to panic. Marked as deprecated.
Panic,
// Returns a Result<T, E> with a `try_` method name prefix
Result,
}
void WriteDocs(FileWriter writer, CreateMethod method, TryMethodKind kind = TryMethodKind.Normal, Action? writeSection = null) {
if (kind != TryMethodKind.Normal && writeSection is null)
throw new InvalidOperationException();
var sectionTitle = kind switch {
TryMethodKind.Normal => string.Empty,
TryMethodKind.Panic => "Panics",
TryMethodKind.Result => "Errors",
_ => throw new InvalidOperationException(),
};
gen.WriteDocs(writer, method, sectionTitle, writeSection);
}
static void WriteMethodAttributes(FileWriter writer, CreateMethod method, bool inline, bool canFail, GenTryFlags flags) {
if (!canFail)
writer.WriteLine(RustConstants.AttributeMustUse);
writer.WriteLine(inline ? RustConstants.AttributeInline : RustConstants.AttributeAllowMissingInlineInPublicItems);
writer.WriteLine(RustConstants.AttributeNoRustFmt);
if ((flags & GenTryFlags.TrivialCasts) != 0)
writer.WriteLine(RustConstants.AttributeAllowTrivialCasts);
}
void WriteMethod(FileWriter writer, CreateMethod method, string name, TryMethodKind kind, GenTryFlags flags) {
bool inline = kind == TryMethodKind.Panic || (flags & GenTryFlags.NoFooter) != 0;
WriteMethodAttributes(writer, method, inline, kind == TryMethodKind.Result, flags);
writer.Write($"pub fn {name}(");
gen.WriteMethodDeclArgs(writer, method);
if (kind == TryMethodKind.Result)
writer.WriteLine(") -> Result<Self, IcedError> {");
else
writer.WriteLine(") -> Self {");
}
void WriteInitializeInstruction(FileWriter writer, CreateMethod method) {
writer.WriteLine("let mut instruction = Self::default();");
var args = method.Args;
if (args.Count == 0 || args[0].Type != MethodArgType.Code)
throw new InvalidOperationException();
var codeName = idConverter.Argument(args[0].Name);
writer.WriteLine($"super::instruction_internal::internal_set_code(&mut instruction, {codeName});");
}
void WriteInitializeInstruction(FileWriter writer, EnumValue code) {
writer.WriteLine("let mut instruction = Self::default();");
writer.WriteLine($"super::instruction_internal::internal_set_code(&mut instruction, {code.DeclaringType.Name(idConverter)}::{code.Name(idConverter)});");
}
static void WriteMethodFooter(FileWriter writer, int opCount, TryMethodKind kind) {
writer.WriteLine();
writer.WriteLine($"debug_assert_eq!(instruction.op_count(), {opCount});");
if (kind == TryMethodKind.Result)
writer.WriteLine("Ok(instruction)");
else
writer.WriteLine("instruction");
}
readonly struct GenerateTryMethodContext {
public readonly FileWriter Writer;
public readonly CreateMethod Method;
public readonly int OpCount;
public readonly string MethodName;
public readonly string TryMethodName;
public GenerateTryMethodContext(FileWriter writer, CreateMethod method, int opCount, string methodName) {
Writer = writer;
Method = method;
OpCount = opCount;
MethodName = methodName;
TryMethodName = "try_" + methodName;
}
}
readonly struct RustDeprecatedInfo {
public readonly string Version;
public readonly string Message;
public RustDeprecatedInfo(string version, string message) {
Version = version;
Message = message;
}
}
[Flags]
enum GenTryFlags : uint {
None = 0,
CanFail = 1,
NoFooter = 2,
TrivialCasts = 4,
}
void GenerateTryMethods(FileWriter writer, CreateMethod method, int opCount, GenTryFlags flags, Action<GenerateTryMethodContext, TryMethodKind> genBody, Action<TryMethodKind>? writeError, string? methodName = null, RustDeprecatedInfo? deprecatedInfo = null) {
if (((flags & GenTryFlags.CanFail) != 0) != (writeError is not null))
throw new InvalidOperationException();
methodName ??= gen.GetCreateName(method, genNames);
var ctx = new GenerateTryMethodContext(writer, method, opCount, methodName);
string? deprecMsg = null;
if (deprecatedInfo is RustDeprecatedInfo deprec)
deprecMsg = $"#[deprecated(since = \"{deprec.Version}\", note = \"{deprec.Message}\")]";
if ((flags & GenTryFlags.CanFail) != 0) {
if (writeError is null)
throw new InvalidOperationException();
const TryMethodKind kind = TryMethodKind.Result;
Action docsWriteError = () => writeError(kind);
WriteDocs(ctx.Writer, ctx.Method, kind, docsWriteError);
if (deprecMsg is not null)
ctx.Writer.WriteLine(deprecMsg);
WriteMethod(ctx.Writer, ctx.Method, ctx.TryMethodName, kind, flags);
using (ctx.Writer.Indent()) {
genBody(ctx, kind);
if ((flags & GenTryFlags.NoFooter) == 0)
WriteMethodFooter(ctx.Writer, ctx.OpCount, kind);
}
ctx.Writer.WriteLine("}");
}
else {
const TryMethodKind kind = TryMethodKind.Normal;
WriteDocs(ctx.Writer, ctx.Method);
if (deprecMsg is not null)
ctx.Writer.WriteLine(deprecMsg);
WriteMethod(ctx.Writer, ctx.Method, ctx.MethodName, kind, flags);
using (ctx.Writer.Indent()) {
genBody(ctx, kind);
if ((flags & GenTryFlags.NoFooter) == 0)
WriteMethodFooter(ctx.Writer, ctx.OpCount, kind);
}
ctx.Writer.WriteLine("}");
}
if ((flags & GenTryFlags.CanFail) != 0) {
ctx.Writer.WriteLine();
if (writeError is null)
throw new InvalidOperationException();
const TryMethodKind kind = TryMethodKind.Panic;
Action docsWriteError = () => writeError(kind);
WriteDocs(ctx.Writer, ctx.Method, kind, docsWriteError);
ctx.Writer.WriteLine($"#[deprecated(since = \"1.10.0\", note = \"This method can panic, use {ctx.TryMethodName}() instead\")]");
ctx.Writer.WriteLine(RustConstants.AttributeAllowUnwrapUsed);
WriteMethod(ctx.Writer, ctx.Method, ctx.MethodName, kind, GenTryFlags.None);
using (ctx.Writer.Indent()) {
sb.Clear();
sb.Append("Instruction::");
sb.Append(ctx.TryMethodName);
sb.Append('(');
for (int i = 0; i < ctx.Method.Args.Count; i++) {
if (i > 0)
sb.Append(", ");
var argName = idConverter.Argument(ctx.Method.Args[i].Name);
sb.Append(argName);
}
sb.Append(").unwrap()");
ctx.Writer.WriteLine(sb.ToString());
}
ctx.Writer.WriteLine("}");
}
}
static string GetErrorString(TryMethodKind kind, string message) {
string word = kind switch {
TryMethodKind.Panic => "Panics",
TryMethodKind.Result => "Fails",
_ => throw new InvalidOperationException(),
};
return $"{word} {message}";
}
protected override void GenCreate(FileWriter writer, CreateMethod method, InstructionGroup group) {
int opCount = method.Args.Count - 1;
if (InstrCreateGenImpl.HasTryMethod(method)) {
Action<TryMethodKind> writeError = kind => docWriter.WriteLine(writer, GetErrorString(kind, "if the immediate is invalid"));
GenerateTryMethods(writer, method, opCount, GenTryFlags.CanFail, GenCreateBody, writeError);
}
else
GenerateTryMethods(writer, method, opCount, GenTryFlags.None, GenCreateBody, null);
}
void GenCreateBody(GenerateTryMethodContext ctx, TryMethodKind kind) {
WriteInitializeInstruction(ctx.Writer, ctx.Method);
var args = ctx.Method.Args;
var codeName = idConverter.Argument(args[0].Name);
var opKindStr = genTypes[TypeIds.OpKind].Name(idConverter);
var registerStr = genTypes[TypeIds.OpKind][nameof(OpKind.Register)].Name(idConverter);
var memoryStr = genTypes[TypeIds.OpKind][nameof(OpKind.Memory)].Name(idConverter);
var immediate64Str = genTypes[TypeIds.OpKind][nameof(OpKind.Immediate64)].Name(idConverter);
var immediate8_2ndStr = genTypes[TypeIds.OpKind][nameof(OpKind.Immediate8_2nd)].Name(idConverter);
bool multipleInts = args.Where(a => a.Type == MethodArgType.Int32 || a.Type == MethodArgType.UInt32).Count() > 1;
string methodName;
for (int i = 1; i < args.Count; i++) {
int op = i - 1;
var arg = args[i];
ctx.Writer.WriteLine();
switch (arg.Type) {
case MethodArgType.Register:
ctx.Writer.WriteLine($"const_assert_eq!({opKindStr}::{registerStr} as u32, 0);");
ctx.Writer.WriteLine($"//super::instruction_internal::internal_set_op{op}_kind(&mut instruction, {opKindStr}::{registerStr});");
ctx.Writer.WriteLine($"super::instruction_internal::internal_set_op{op}_register(&mut instruction, {idConverter.Argument(arg.Name)});");
break;
case MethodArgType.Memory:
ctx.Writer.WriteLine($"super::instruction_internal::internal_set_op{op}_kind(&mut instruction, {opKindStr}::{memoryStr});");
ctx.Writer.WriteLine($"Instruction::init_memory_operand(&mut instruction, &{idConverter.Argument(arg.Name)});");
break;
case MethodArgType.Int32:
case MethodArgType.UInt32:
methodName = arg.Type == MethodArgType.Int32 ? "initialize_signed_immediate" : "initialize_unsigned_immediate";
var castType = arg.Type == MethodArgType.Int32 ? " as i64" : " as u64";
ctx.Writer.WriteLine($"super::instruction_internal::{methodName}(&mut instruction, {op}, {idConverter.Argument(arg.Name)}{castType})?;");
break;
case MethodArgType.Int64:
case MethodArgType.UInt64:
methodName = arg.Type == MethodArgType.Int64 ? "initialize_signed_immediate" : "initialize_unsigned_immediate";
ctx.Writer.WriteLine($"super::instruction_internal::{methodName}(&mut instruction, {op}, {idConverter.Argument(arg.Name)})?;");
break;
case MethodArgType.Code:
case MethodArgType.RepPrefixKind:
case MethodArgType.UInt8:
case MethodArgType.UInt16:
case MethodArgType.PreferedInt32:
case MethodArgType.ArrayIndex:
case MethodArgType.ArrayLength:
case MethodArgType.ByteArray:
case MethodArgType.WordArray:
case MethodArgType.DwordArray:
case MethodArgType.QwordArray:
case MethodArgType.ByteSlice:
case MethodArgType.WordSlice:
case MethodArgType.DwordSlice:
case MethodArgType.QwordSlice:
case MethodArgType.BytePtr:
case MethodArgType.WordPtr:
case MethodArgType.DwordPtr:
case MethodArgType.QwordPtr:
default:
throw new InvalidOperationException();
}
}
}
protected override void GenCreateBranch(FileWriter writer, CreateMethod method) {
if (method.Args.Count != 2)
throw new InvalidOperationException();
Action<TryMethodKind> writeError = kind => docWriter.WriteLine(writer, GetErrorString(kind, "if the created instruction doesn't have a near branch operand"));
GenerateTryMethods(writer, method, 1, GenTryFlags.CanFail, GenCreateBranch, writeError, RustInstrCreateGenNames.with_branch);
}
void GenCreateBranch(GenerateTryMethodContext ctx, TryMethodKind kind) {
WriteInitializeInstruction(ctx.Writer, ctx.Method);
ctx.Writer.WriteLine();
ctx.Writer.WriteLine($"super::instruction_internal::internal_set_op0_kind(&mut instruction, super::instruction_internal::get_near_branch_op_kind({idConverter.Argument(ctx.Method.Args[0].Name)}, 0)?);");
ctx.Writer.WriteLine($"instruction.set_near_branch64({idConverter.Argument(ctx.Method.Args[1].Name)});");
}
protected override void GenCreateFarBranch(FileWriter writer, CreateMethod method) {
if (method.Args.Count != 3)
throw new InvalidOperationException();
Action<TryMethodKind> writeError = kind => docWriter.WriteLine(writer, GetErrorString(kind, "if the created instruction doesn't have a far branch operand"));
GenerateTryMethods(writer, method, 1, GenTryFlags.CanFail, GenCreateFarBranch, writeError, RustInstrCreateGenNames.with_far_branch);
}
void GenCreateFarBranch(GenerateTryMethodContext ctx, TryMethodKind kind) {
WriteInitializeInstruction(ctx.Writer, ctx.Method);
ctx.Writer.WriteLine();
ctx.Writer.WriteLine($"super::instruction_internal::internal_set_op0_kind(&mut instruction, super::instruction_internal::get_far_branch_op_kind({idConverter.Argument(ctx.Method.Args[0].Name)}, 0)?);");
ctx.Writer.WriteLine($"instruction.set_far_branch_selector({idConverter.Argument(ctx.Method.Args[1].Name)});");
ctx.Writer.WriteLine($"instruction.set_far_branch32({idConverter.Argument(ctx.Method.Args[2].Name)});");
}
protected override void GenCreateXbegin(FileWriter writer, CreateMethod method) {
if (method.Args.Count != 2)
throw new InvalidOperationException();
Action<TryMethodKind> writeError = kind => WriteAddrSizeOrBitnessPanic(writer, method, kind);
GenerateTryMethods(writer, method, 1, GenTryFlags.CanFail, GenCreateXbegin, writeError, RustInstrCreateGenNames.with_xbegin);
}
void GenCreateXbegin(GenerateTryMethodContext ctx, TryMethodKind kind) {
ctx.Writer.WriteLine($"let mut instruction = Self::default();");
var opKindName = genTypes[TypeIds.OpKind].Name(idConverter);
var codeName = codeType.Name(idConverter);
ctx.Writer.WriteLine();
ctx.Writer.WriteLine($"match bitness {{");
ctx.Writer.WriteLine($" 16 => {{");
ctx.Writer.WriteLine($" super::instruction_internal::internal_set_code(&mut instruction, {codeName}::{codeType[nameof(Code.Xbegin_rel16)].Name(idConverter)});");
ctx.Writer.WriteLine($" super::instruction_internal::internal_set_op0_kind(&mut instruction, {opKindName}::{genTypes[TypeIds.OpKind][nameof(OpKind.NearBranch32)].Name(idConverter)});");
ctx.Writer.WriteLine($" instruction.set_near_branch32({idConverter.Argument(ctx.Method.Args[1].Name)} as u32);");
ctx.Writer.WriteLine($" }}");
ctx.Writer.WriteLine();
ctx.Writer.WriteLine($" 32 => {{");
ctx.Writer.WriteLine($" super::instruction_internal::internal_set_code(&mut instruction, {codeName}::{codeType[nameof(Code.Xbegin_rel32)].Name(idConverter)});");
ctx.Writer.WriteLine($" super::instruction_internal::internal_set_op0_kind(&mut instruction, {opKindName}::{genTypes[TypeIds.OpKind][nameof(OpKind.NearBranch32)].Name(idConverter)});");
ctx.Writer.WriteLine($" instruction.set_near_branch32({idConverter.Argument(ctx.Method.Args[1].Name)} as u32);");
ctx.Writer.WriteLine($" }}");
ctx.Writer.WriteLine();
ctx.Writer.WriteLine($" 64 => {{");
ctx.Writer.WriteLine($" super::instruction_internal::internal_set_code(&mut instruction, {codeName}::{codeType[nameof(Code.Xbegin_rel32)].Name(idConverter)});");
ctx.Writer.WriteLine($" super::instruction_internal::internal_set_op0_kind(&mut instruction, {opKindName}::{genTypes[TypeIds.OpKind][nameof(OpKind.NearBranch64)].Name(idConverter)});");
ctx.Writer.WriteLine($" instruction.set_near_branch64({idConverter.Argument(ctx.Method.Args[1].Name)});");
ctx.Writer.WriteLine($" }}");
ctx.Writer.WriteLine();
ctx.Writer.WriteLine($" _ => return Err(IcedError::new(\"Invalid bitness\")),");
ctx.Writer.WriteLine($"}}");
}
protected override bool CallGenCreateMemory64 => true;
protected override void GenCreateMemory64(FileWriter writer, CreateMethod method) {
if (method.Args.Count != 4)
throw new InvalidOperationException();
int memOp, regOp;
string name, newName;
if (method.Args[1].Type == MethodArgType.UInt64) {
memOp = 0;
regOp = 1;
name = RustInstrCreateGenNames.with_mem64_reg;
newName = "with_mem_reg";
}
else {
memOp = 1;
regOp = 0;
name = RustInstrCreateGenNames.with_reg_mem64;
newName = "with_reg_mem";
}
var deprec = new RustDeprecatedInfo("1.11.0", $"Use {newName}() with a MemoryOperand arg instead");
GenerateTryMethods(writer, method, 2, GenTryFlags.NoFooter, (ctx, _) => GenCreateMemory64(ctx, memOp, regOp), null, name, deprecatedInfo: deprec);
}
void GenCreateMemory64(GenerateTryMethodContext ctx, int memOp, int regOp) {
var regNone = genTypes[TypeIds.Register][nameof(Register.None)];
var regStr = $"{regNone.DeclaringType.Name(idConverter)}::{regNone.Name(idConverter)}";
var addrStr = idConverter.Argument(ctx.Method.Args[1 + memOp].Name);
var segPrefStr = idConverter.Argument(ctx.Method.Args[3].Name);
var memOpStr = $"MemoryOperand::with_base_displ_size_bcst_seg({regStr}, {addrStr} as i64, 8, false, {segPrefStr})";
var regOpStr = idConverter.Argument(ctx.Method.Args[1 + regOp].Name);
var codeStr = idConverter.Argument(ctx.Method.Args[0].Name);
if (memOp == 0)
ctx.Writer.WriteLine($"Instruction::with_mem_reg({codeStr}, {memOpStr}, {regOpStr})");
else
ctx.Writer.WriteLine($"Instruction::with_reg_mem({codeStr}, {regOpStr}, {memOpStr})");
}
static void WriteComma(FileWriter writer) => writer.Write(", ");
void Write(FileWriter writer, EnumValue value) => writer.Write($"{value.DeclaringType.Name(idConverter)}::{value.Name(idConverter)}");
void Write(FileWriter writer, MethodArg arg) => writer.Write(idConverter.Argument(arg.Name));
void WriteAddrSizeOrBitnessPanic(FileWriter writer, CreateMethod method, TryMethodKind kind) {
var arg = method.Args[0];
if (arg.Name != "addressSize" && arg.Name != "bitness")
throw new InvalidOperationException();
docWriter.WriteLine(writer, GetErrorString(kind, $"if `{idConverter.Argument(arg.Name)}` is not one of 16, 32, 64."));
}
protected override void GenCreateString_Reg_SegRSI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register) {
var methodName = idConverter.Method("With" + methodBaseName);
Action<TryMethodKind> writeError = kind => WriteAddrSizeOrBitnessPanic(writer, method, kind);
GenerateTryMethods(writer, method, 1, GenTryFlags.CanFail | GenTryFlags.NoFooter, (ctx, _) => GenCreateString_Reg_SegRSI(ctx, kind, code, register), writeError, methodName);
}
void GenCreateString_Reg_SegRSI(GenerateTryMethodContext ctx, StringMethodKind kind, EnumValue code, EnumValue register) {
ctx.Writer.Write("super::instruction_internal::with_string_reg_segrsi(");
switch (kind) {
case StringMethodKind.Full:
if (ctx.Method.Args.Count != 3)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, register);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[1]);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[2]);
break;
case StringMethodKind.Rep:
if (ctx.Method.Args.Count != 1)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, register);
WriteComma(ctx.Writer);
Write(ctx.Writer, genTypes[TypeIds.Register][nameof(Register.None)]);
WriteComma(ctx.Writer);
Write(ctx.Writer, genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repe)]);
break;
case StringMethodKind.Repe:
case StringMethodKind.Repne:
default:
throw new InvalidOperationException();
}
ctx.Writer.WriteLine(")");
}
protected override void GenCreateString_Reg_ESRDI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register) {
var methodName = idConverter.Method("With" + methodBaseName);
Action<TryMethodKind> writeError = kind => WriteAddrSizeOrBitnessPanic(writer, method, kind);
GenerateTryMethods(writer, method, 1, GenTryFlags.CanFail | GenTryFlags.NoFooter, (ctx, _) => GenCreateString_Reg_ESRDI(ctx, kind, code, register), writeError, methodName);
}
void GenCreateString_Reg_ESRDI(GenerateTryMethodContext ctx, StringMethodKind kind, EnumValue code, EnumValue register) {
ctx.Writer.Write("super::instruction_internal::with_string_reg_esrdi(");
switch (kind) {
case StringMethodKind.Full:
if (ctx.Method.Args.Count != 2)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, register);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[1]);
break;
case StringMethodKind.Repe:
case StringMethodKind.Repne:
if (ctx.Method.Args.Count != 1)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, register);
WriteComma(ctx.Writer);
Write(ctx.Writer, kind == StringMethodKind.Repe ? genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repe)] : genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repne)]);
break;
case StringMethodKind.Rep:
default:
throw new InvalidOperationException();
}
ctx.Writer.WriteLine(")");
}
protected override void GenCreateString_ESRDI_Reg(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register) {
var methodName = idConverter.Method("With" + methodBaseName);
Action<TryMethodKind> writeError = kind => WriteAddrSizeOrBitnessPanic(writer, method, kind);
GenerateTryMethods(writer, method, 1, GenTryFlags.CanFail | GenTryFlags.NoFooter, (ctx, _) => GenCreateString_ESRDI_Reg(ctx, kind, code, register), writeError, methodName);
}
void GenCreateString_ESRDI_Reg(GenerateTryMethodContext ctx, StringMethodKind kind, EnumValue code, EnumValue register) {
ctx.Writer.Write("super::instruction_internal::with_string_esrdi_reg(");
switch (kind) {
case StringMethodKind.Full:
if (ctx.Method.Args.Count != 2)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, register);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[1]);
break;
case StringMethodKind.Rep:
if (ctx.Method.Args.Count != 1)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, register);
WriteComma(ctx.Writer);
Write(ctx.Writer, genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repe)]);
break;
case StringMethodKind.Repe:
case StringMethodKind.Repne:
default:
throw new InvalidOperationException();
}
ctx.Writer.WriteLine(")");
}
protected override void GenCreateString_SegRSI_ESRDI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code) {
var methodName = idConverter.Method("With" + methodBaseName);
Action<TryMethodKind> writeError = kind => WriteAddrSizeOrBitnessPanic(writer, method, kind);
GenerateTryMethods(writer, method, 1, GenTryFlags.CanFail | GenTryFlags.NoFooter, (ctx, _) => GenCreateString_SegRSI_ESRDI(ctx, kind, code), writeError, methodName);
}
void GenCreateString_SegRSI_ESRDI(GenerateTryMethodContext ctx, StringMethodKind kind, EnumValue code) {
ctx.Writer.Write("super::instruction_internal::with_string_segrsi_esrdi(");
switch (kind) {
case StringMethodKind.Full:
if (ctx.Method.Args.Count != 3)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[1]);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[2]);
break;
case StringMethodKind.Repe:
case StringMethodKind.Repne:
if (ctx.Method.Args.Count != 1)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, genTypes[TypeIds.Register][nameof(Register.None)]);
WriteComma(ctx.Writer);
Write(ctx.Writer, kind == StringMethodKind.Repe ? genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repe)] : genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repne)]);
break;
case StringMethodKind.Rep:
default:
throw new InvalidOperationException();
}
ctx.Writer.WriteLine(")");
}
protected override void GenCreateString_ESRDI_SegRSI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code) {
var methodName = idConverter.Method("With" + methodBaseName);
Action<TryMethodKind> writeError = kind => WriteAddrSizeOrBitnessPanic(writer, method, kind);
GenerateTryMethods(writer, method, 1, GenTryFlags.CanFail | GenTryFlags.NoFooter, (ctx, _) => GenCreateString_ESRDI_SegRSI(ctx, kind, code), writeError, methodName);
}
void GenCreateString_ESRDI_SegRSI(GenerateTryMethodContext ctx, StringMethodKind kind, EnumValue code) {
ctx.Writer.Write("super::instruction_internal::with_string_esrdi_segrsi(");
switch (kind) {
case StringMethodKind.Full:
if (ctx.Method.Args.Count != 3)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[1]);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[2]);
break;
case StringMethodKind.Rep:
if (ctx.Method.Args.Count != 1)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, genTypes[TypeIds.Register][nameof(Register.None)]);
WriteComma(ctx.Writer);
Write(ctx.Writer, genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.Repe)]);
break;
case StringMethodKind.Repe:
case StringMethodKind.Repne:
default:
throw new InvalidOperationException();
}
ctx.Writer.WriteLine(")");
}
protected override void GenCreateMaskmov(FileWriter writer, CreateMethod method, string methodBaseName, EnumValue code) {
var methodName = idConverter.Method("With" + methodBaseName);
Action<TryMethodKind> writeError = kind => WriteAddrSizeOrBitnessPanic(writer, method, kind);
GenerateTryMethods(writer, method, 1, GenTryFlags.CanFail | GenTryFlags.NoFooter, (ctx, _) => GenCreateMaskmov(ctx, code), writeError, methodName);
}
void GenCreateMaskmov(GenerateTryMethodContext ctx, EnumValue code) {
ctx.Writer.Write("super::instruction_internal::with_maskmov(");
if (ctx.Method.Args.Count != 4)
throw new InvalidOperationException();
Write(ctx.Writer, code);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[0]);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[1]);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[2]);
WriteComma(ctx.Writer);
Write(ctx.Writer, ctx.Method.Args[3]);
ctx.Writer.WriteLine(")");
}
protected override void GenCreateDeclareData(FileWriter writer, CreateMethod method, DeclareDataKind kind) {
EnumValue code;
string setValueName;
string methodName;
switch (kind) {
case DeclareDataKind.Byte:
code = codeType[nameof(Code.DeclareByte)];
setValueName = "set_declare_byte_value";
methodName = RustInstrCreateGenNames.with_declare_byte;
break;
case DeclareDataKind.Word:
code = codeType[nameof(Code.DeclareWord)];
setValueName = "set_declare_word_value";
methodName = RustInstrCreateGenNames.with_declare_word;
break;
case DeclareDataKind.Dword:
code = codeType[nameof(Code.DeclareDword)];
setValueName = "set_declare_dword_value";
methodName = RustInstrCreateGenNames.with_declare_dword;
break;
case DeclareDataKind.Qword:
code = codeType[nameof(Code.DeclareQword)];
setValueName = "set_declare_qword_value";
methodName = RustInstrCreateGenNames.with_declare_qword;
break;
default:
throw new InvalidOperationException();
}
methodName = RustInstrCreateGenNames.AppendArgCount(methodName, method.Args.Count);
writer.WriteLine();
Action<TryMethodKind> writeError = kind => WriteDeclareDataError(writer, kind);
GenerateTryMethods(writer, method, 0, GenTryFlags.CanFail, (ctx, _) => GenCreateDeclareData(ctx, code, setValueName), writeError, methodName);
}
void GenCreateDeclareData(GenerateTryMethodContext ctx, EnumValue code, string setValueName) {
WriteInitializeInstruction(ctx.Writer, code);
ctx.Writer.WriteLine($"super::instruction_internal::internal_set_declare_data_len(&mut instruction, {ctx.Method.Args.Count});");
ctx.Writer.WriteLine();
for (int i = 0; i < ctx.Method.Args.Count; i++)
ctx.Writer.WriteLine($"instruction.try_{setValueName}({i}, {idConverter.Argument(ctx.Method.Args[i].Name)})?;");
}
static string GetDbErrorMsg(TryMethodKind kind) => GetErrorString(kind, "if `db` feature wasn't enabled");
void WriteDeclareDataError(FileWriter writer, TryMethodKind kind) =>
docWriter.WriteLine(writer, GetDbErrorMsg(kind));
void WriteDataError(FileWriter writer, TryMethodKind kind, CreateMethod method, string extra) {
var msg1 = GetErrorString(kind, $"if `{idConverter.Argument(method.Args[0].Name)}.len()` {extra}");
docWriter.WriteLine(writer, $"- {msg1}");
docWriter.WriteLine(writer, $"- {GetDbErrorMsg(kind)}");
}
void GenCreateDeclareDataSlice(FileWriter writer, CreateMethod method, int elemSize, EnumValue code, string methodName, string setDeclValueName) {
writer.WriteLine();
Action<TryMethodKind> writeError = kind => WriteDataError(writer, kind, method, $"is not 1-{16 / elemSize}");
GenerateTryMethods(writer, method, 0, GenTryFlags.CanFail, (ctx, _) => GenCreateDeclareDataSlice(ctx, elemSize, code, setDeclValueName), writeError, methodName);
}
void GenCreateDeclareDataSlice(GenerateTryMethodContext ctx, int elemSize, EnumValue code, string setDeclValueName) {
var dataName = idConverter.Argument(ctx.Method.Args[0].Name);
ctx.Writer.WriteLine($"if {dataName}.len().wrapping_sub(1) > {16 / elemSize} - 1 {{");
using (ctx.Writer.Indent())
ctx.Writer.WriteLine("return Err(IcedError::new(\"Invalid slice length\"));");
ctx.Writer.WriteLine("}");
ctx.Writer.WriteLine();
WriteInitializeInstruction(ctx.Writer, code);
ctx.Writer.WriteLine($"super::instruction_internal::internal_set_declare_data_len(&mut instruction, {dataName}.len() as u32);");
ctx.Writer.WriteLine();
ctx.Writer.WriteLine($"for i in {dataName}.iter().enumerate() {{");
using (ctx.Writer.Indent())
ctx.Writer.WriteLine($"instruction.try_{setDeclValueName}(i.0, *i.1)?;");
ctx.Writer.WriteLine("}");
}
protected override void GenCreateDeclareDataArray(FileWriter writer, CreateMethod method, DeclareDataKind kind, ArrayType arrayType) {
switch (kind) {
case DeclareDataKind.Byte:
switch (arrayType) {
case ArrayType.BytePtr:
case ArrayType.ByteArray:
break;
case ArrayType.ByteSlice:
GenCreateDeclareDataSlice(writer, method, 1, codeType[nameof(Code.DeclareByte)], RustInstrCreateGenNames.with_declare_byte, "set_declare_byte_value");
break;
default:
throw new InvalidOperationException();
}
break;
case DeclareDataKind.Word:
switch (arrayType) {
case ArrayType.BytePtr:
case ArrayType.WordPtr:
case ArrayType.ByteArray:
case ArrayType.WordArray:
break;
case ArrayType.ByteSlice:
writer.WriteLine();
Action<TryMethodKind> writeError = kind => WriteDataError(writer, kind, method, $"is not 2-16 or not a multiple of 2");
const GenTryFlags flags = GenTryFlags.CanFail | GenTryFlags.TrivialCasts;
GenerateTryMethods(writer, method, 0, flags, (ctx, _) => GenerateDeclWordByteSlice(ctx), writeError, RustInstrCreateGenNames.with_declare_word_slice_u8);
break;
void GenerateDeclWordByteSlice(GenerateTryMethodContext ctx) {
var dataName = idConverter.Argument(method.Args[0].Name);
writer.WriteLine($"if {dataName}.len().wrapping_sub(1) > 16 - 1 || ({dataName}.len() & 1) != 0 {{");
using (writer.Indent())
ctx.Writer.WriteLine("return Err(IcedError::new(\"Invalid slice length\"));");
writer.WriteLine("}");
writer.WriteLine();
WriteInitializeInstruction(writer, codeType[nameof(Code.DeclareWord)]);
writer.WriteLine($"super::instruction_internal::internal_set_declare_data_len(&mut instruction, {dataName}.len() as u32 / 2);");
writer.WriteLine();
writer.WriteLine($"for i in 0..{dataName}.len() / 2 {{");
using (writer.Indent()) {
writer.WriteLine($"let v = unsafe {{ u16::from_le(ptr::read_unaligned({dataName}.get_unchecked(i * 2) as *const _ as *const u16)) }};");
writer.WriteLine("instruction.try_set_declare_word_value(i, v)?;");
}
writer.WriteLine("}");
}
case ArrayType.WordSlice:
GenCreateDeclareDataSlice(writer, method, 2, codeType[nameof(Code.DeclareWord)], RustInstrCreateGenNames.with_declare_word, "set_declare_word_value");
break;
default:
throw new InvalidOperationException();
}
break;
case DeclareDataKind.Dword:
switch (arrayType) {
case ArrayType.BytePtr:
case ArrayType.DwordPtr:
case ArrayType.ByteArray:
case ArrayType.DwordArray:
break;
case ArrayType.ByteSlice:
writer.WriteLine();
Action<TryMethodKind> writeError = kind => WriteDataError(writer, kind, method, $"is not 4-16 or not a multiple of 4");
const GenTryFlags flags = GenTryFlags.CanFail | GenTryFlags.TrivialCasts;
GenerateTryMethods(writer, method, 0, flags, (ctx, _) => GenerateDeclDwordByteSlice(ctx), writeError, RustInstrCreateGenNames.with_declare_dword_slice_u8);
break;
void GenerateDeclDwordByteSlice(GenerateTryMethodContext ctx) {
var dataName = idConverter.Argument(method.Args[0].Name);
writer.WriteLine($"if {dataName}.len().wrapping_sub(1) > 16 - 1 || ({dataName}.len() & 3) != 0 {{");
using (writer.Indent())
ctx.Writer.WriteLine("return Err(IcedError::new(\"Invalid slice length\"));");
writer.WriteLine("}");
writer.WriteLine();
WriteInitializeInstruction(writer, codeType[nameof(Code.DeclareDword)]);
writer.WriteLine($"super::instruction_internal::internal_set_declare_data_len(&mut instruction, {dataName}.len() as u32 / 4);");
writer.WriteLine();
writer.WriteLine($"for i in 0..{dataName}.len() / 4 {{");
using (writer.Indent()) {
writer.WriteLine($"let v = unsafe {{ u32::from_le(ptr::read_unaligned({dataName}.get_unchecked(i * 4) as *const _ as *const u32)) }};");
writer.WriteLine("instruction.try_set_declare_dword_value(i, v)?;");
}
writer.WriteLine("}");
}
case ArrayType.DwordSlice:
GenCreateDeclareDataSlice(writer, method, 4, codeType[nameof(Code.DeclareDword)], RustInstrCreateGenNames.with_declare_dword, "set_declare_dword_value");
break;
default:
throw new InvalidOperationException();
}
break;
case DeclareDataKind.Qword:
switch (arrayType) {
case ArrayType.BytePtr:
case ArrayType.QwordPtr:
case ArrayType.ByteArray:
case ArrayType.QwordArray:
break;
case ArrayType.ByteSlice:
writer.WriteLine();
Action<TryMethodKind> writeError = kind => WriteDataError(writer, kind, method, $"is not 8-16 or not a multiple of 8");
const GenTryFlags flags = GenTryFlags.CanFail | GenTryFlags.TrivialCasts;
GenerateTryMethods(writer, method, 0, flags, (ctx, _) => GenerateDeclQwordByteSlice(ctx), writeError, RustInstrCreateGenNames.with_declare_qword_slice_u8);
break;
void GenerateDeclQwordByteSlice(GenerateTryMethodContext ctx) {
var dataName = idConverter.Argument(method.Args[0].Name);
writer.WriteLine($"if {dataName}.len().wrapping_sub(1) > 16 - 1 || ({dataName}.len() & 7) != 0 {{");
using (writer.Indent())
ctx.Writer.WriteLine("return Err(IcedError::new(\"Invalid slice length\"));");
writer.WriteLine("}");
writer.WriteLine();
WriteInitializeInstruction(writer, codeType[nameof(Code.DeclareQword)]);
writer.WriteLine($"super::instruction_internal::internal_set_declare_data_len(&mut instruction, {dataName}.len() as u32 / 8);");
writer.WriteLine();
writer.WriteLine($"for i in 0..{dataName}.len() / 8 {{");
using (writer.Indent()) {
writer.WriteLine($"let v = unsafe {{ u64::from_le(ptr::read_unaligned({dataName}.get_unchecked(i * 8) as *const _ as *const u64)) }};");
writer.WriteLine("instruction.try_set_declare_qword_value(i, v)?;");
}
writer.WriteLine("}");
}
case ArrayType.QwordSlice:
GenCreateDeclareDataSlice(writer, method, 8, codeType[nameof(Code.DeclareQword)], RustInstrCreateGenNames.with_declare_qword, "set_declare_qword_value");
break;
default:
throw new InvalidOperationException();
}
break;
default:
throw new InvalidOperationException();
}
}
protected override void GenCreateDeclareDataArrayLength(FileWriter writer, CreateMethod method, DeclareDataKind kind, ArrayType arrayType) {
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.IO;
namespace System.Management.Automation
{
/// <summary>
/// These are platform abstractions and platform specific implementations
/// </summary>
public static class Platform
{
/// <summary>
/// True if the current platform is Linux.
/// </summary>
public static bool IsLinux
{
get
{
#if CORECLR
return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
#else
return false;
#endif
}
}
/// <summary>
/// True if the current platform is OS X.
/// </summary>
public static bool IsOSX
{
get
{
#if CORECLR
return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
#else
return false;
#endif
}
}
/// <summary>
/// True if the current platform is Windows.
/// </summary>
public static bool IsWindows
{
get
{
#if CORECLR
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#else
return true;
#endif
}
}
/// <summary>
/// True if PowerShell was built targeting .NET Core.
/// </summary>
public static bool IsCoreCLR
{
get
{
#if CORECLR
return true;
#else
return false;
#endif
}
}
/// <summary>
/// True if the underlying system is NanoServer.
/// </summary>
public static bool IsNanoServer
{
get
{
#if !CORECLR
return false;
#elif UNIX
return false;
#else
if (_isNanoServer.HasValue) { return _isNanoServer.Value; }
_isNanoServer = false;
using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels"))
{
if (regKey != null)
{
object value = regKey.GetValue("NanoServer");
if (value != null && regKey.GetValueKind("NanoServer") == RegistryValueKind.DWord)
{
_isNanoServer = (int)value == 1;
}
}
}
return _isNanoServer.Value;
#endif
}
}
/// <summary>
/// True if the underlying system is IoT.
/// </summary>
public static bool IsIoT
{
get
{
#if !CORECLR
return false;
#elif UNIX
return false;
#else
if (_isIoT.HasValue) { return _isIoT.Value; }
_isIoT = false;
using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
{
if (regKey != null)
{
object value = regKey.GetValue("ProductName");
if (value != null && regKey.GetValueKind("ProductName") == RegistryValueKind.String)
{
_isIoT = string.Equals("IoTUAP", (string)value, StringComparison.OrdinalIgnoreCase);
}
}
}
return _isIoT.Value;
#endif
}
}
#if CORECLR
/// <summary>
/// True if it is the inbox powershell for NanoServer or IoT.
/// </summary>
internal static bool IsInbox
{
get
{
#if UNIX
return false;
#else
if (_isInbox.HasValue) { return _isInbox.Value; }
_isInbox = false;
if (IsNanoServer || IsIoT)
{
_isInbox = string.Equals(
Utils.GetApplicationBase(Utils.DefaultPowerShellShellID),
Utils.GetApplicationBaseFromRegistry(Utils.DefaultPowerShellShellID),
StringComparison.OrdinalIgnoreCase);
}
return _isInbox.Value;
#endif
}
}
#if !UNIX
private static bool? _isNanoServer = null;
private static bool? _isIoT = null;
private static bool? _isInbox = null;
#endif
#endif
// format files
internal static List<string> FormatFileNames = new List<string>
{
"Certificate.format.ps1xml",
"Diagnostics.format.ps1xml",
"DotNetTypes.format.ps1xml",
"Event.format.ps1xml",
"FileSystem.format.ps1xml",
"Help.format.ps1xml",
"HelpV3.format.ps1xml",
"PowerShellCore.format.ps1xml",
"PowerShellTrace.format.ps1xml",
"Registry.format.ps1xml",
"WSMan.format.ps1xml"
};
/// <summary>
/// Some common environment variables used in PS have different
/// names in different OS platforms
/// </summary>
internal static class CommonEnvVariableNames
{
#if UNIX
internal const string Home = "HOME";
#else
internal const string Home = "USERPROFILE";
#endif
}
#if UNIX
/// <summary>
/// X Desktop Group configuration type enum.
/// </summary>
public enum XDG_Type
{
/// <summary> XDG_CONFIG_HOME/powershell </summary>
CONFIG,
/// <summary> XDG_CACHE_HOME/powershell </summary>
CACHE,
/// <summary> XDG_DATA_HOME/powershell </summary>
DATA,
/// <summary> XDG_DATA_HOME/powershell/Modules </summary>
USER_MODULES,
/// <summary> /usr/local/share/powershell/Modules </summary>
SHARED_MODULES,
/// <summary> XDG_CONFIG_HOME/powershell </summary>
DEFAULT
}
/// <summary>
/// function for choosing directory location of PowerShell for profile loading
/// </summary>
public static string SelectProductNameForDirectory(Platform.XDG_Type dirpath)
{
//TODO: XDG_DATA_DIRS implementation as per GitHub issue #1060
string xdgconfighome = System.Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
string xdgdatahome = System.Environment.GetEnvironmentVariable("XDG_DATA_HOME");
string xdgcachehome = System.Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
string xdgConfigHomeDefault = Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), ".config", "powershell");
string xdgDataHomeDefault = Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), ".local", "share", "powershell");
string xdgModuleDefault = Path.Combine(xdgDataHomeDefault, "Modules");
string xdgCacheDefault = Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), ".cache", "powershell");
switch (dirpath)
{
case Platform.XDG_Type.CONFIG:
//the user has set XDG_CONFIG_HOME corrresponding to profile path
if (String.IsNullOrEmpty(xdgconfighome))
{
//xdg values have not been set
return xdgConfigHomeDefault;
}
else
{
return Path.Combine(xdgconfighome, "powershell");
}
case Platform.XDG_Type.DATA:
//the user has set XDG_DATA_HOME corresponding to module path
if (String.IsNullOrEmpty(xdgdatahome))
{
// create the xdg folder if needed
if (!Directory.Exists(xdgDataHomeDefault))
{
Directory.CreateDirectory(xdgDataHomeDefault);
}
return xdgDataHomeDefault;
}
else
{
return Path.Combine(xdgdatahome, "powershell");
}
case Platform.XDG_Type.USER_MODULES:
//the user has set XDG_DATA_HOME corresponding to module path
if (String.IsNullOrEmpty(xdgdatahome))
{
//xdg values have not been set
if (!Directory.Exists(xdgModuleDefault)) //module folder not always guaranteed to exist
{
Directory.CreateDirectory(xdgModuleDefault);
}
return xdgModuleDefault;
}
else
{
return Path.Combine(xdgdatahome, "powershell", "Modules");
}
case Platform.XDG_Type.SHARED_MODULES:
return "/usr/local/share/powershell/Modules";
case Platform.XDG_Type.CACHE:
//the user has set XDG_CACHE_HOME
if (String.IsNullOrEmpty(xdgcachehome))
{
//xdg values have not been set
if (!Directory.Exists(xdgCacheDefault)) //module folder not always guaranteed to exist
{
Directory.CreateDirectory(xdgCacheDefault);
}
return xdgCacheDefault;
}
else
{
if (!Directory.Exists(Path.Combine(xdgcachehome, "powershell")))
{
Directory.CreateDirectory(Path.Combine(xdgcachehome, "powershell"));
}
return Path.Combine(xdgcachehome, "powershell");
}
case Platform.XDG_Type.DEFAULT:
//default for profile location
return xdgConfigHomeDefault;
default:
//xdgConfigHomeDefault needs to be created in the edge case that we do not have the folder or it was deleted
//This folder is the default in the event of all other failures for data storage
if (!Directory.Exists(xdgConfigHomeDefault))
{
try
{
Directory.CreateDirectory(xdgConfigHomeDefault);
}
catch
{
Console.Error.WriteLine("Failed to create default data directory: " + xdgConfigHomeDefault);
}
}
return xdgConfigHomeDefault;
}
}
#endif
// Platform methods prefixed NonWindows are:
// - non-windows by the definition of the IsWindows method above
// - here, because porting to Linux and other operating systems
// should not move the original Windows code out of the module
// it belongs to, so this way the windows code can remain in it's
// original source file and only the non-windows code has been moved
// out here
// - only to be used with the IsWindows feature query, and only if
// no other more specific feature query makes sense
internal static bool NonWindowsIsHardLink(ref IntPtr handle)
{
return Unix.IsHardLink(ref handle);
}
internal static bool NonWindowsIsHardLink(FileSystemInfo fileInfo)
{
return Unix.IsHardLink(fileInfo);
}
internal static bool NonWindowsIsSymLink(FileSystemInfo fileInfo)
{
return Unix.NativeMethods.IsSymLink(fileInfo.FullName);
}
internal static string NonWindowsInternalGetTarget(SafeFileHandle handle)
{
// SafeHandle is a Windows concept. Use the string version instead.
throw new PlatformNotSupportedException();
}
internal static string NonWindowsInternalGetTarget(string path)
{
return Unix.NativeMethods.FollowSymLink(path);
}
internal static string NonWindowsGetUserFromPid(int path)
{
return Unix.NativeMethods.GetUserFromPid(path);
}
internal static string NonWindowsInternalGetLinkType(FileSystemInfo fileInfo)
{
if (NonWindowsIsSymLink(fileInfo))
{
return "SymbolicLink";
}
if (NonWindowsIsHardLink(fileInfo))
{
return "HardLink";
}
return null;
}
internal static bool NonWindowsCreateSymbolicLink(string path, string target)
{
// Linux doesn't care if target is a directory or not
return Unix.NativeMethods.CreateSymLink(path, target);
}
internal static bool NonWindowsCreateHardLink(string path, string strTargetPath)
{
return Unix.CreateHardLink(path, strTargetPath);
}
internal static void NonWindowsSetDate(DateTime dateToUse)
{
Unix.SetDateInfoInternal date = new Unix.SetDateInfoInternal(dateToUse);
Unix.SetDate(date);
}
internal static string NonWindowsGetDomainName()
{
string name = Unix.NativeMethods.GetFullyQualifiedName();
if (!string.IsNullOrEmpty(name))
{
// name is hostname.domainname, so extract domainname
int index = name.IndexOf('.');
if (index >= 0)
{
return name.Substring(index + 1);
}
}
// if the domain name could not be found, do not throw, just return empty
return string.Empty;
}
// Hostname in this context seems to be the FQDN
internal static string NonWindowsGetHostName()
{
return Unix.NativeMethods.GetFullyQualifiedName() ?? string.Empty;
}
internal static bool NonWindowsIsFile(string path)
{
return Unix.NativeMethods.IsFile(path);
}
internal static bool NonWindowsIsDirectory(string path)
{
return Unix.NativeMethods.IsDirectory(path);
}
internal static bool NonWindowsIsExecutable(string path)
{
return Unix.NativeMethods.IsExecutable(path);
}
internal static uint NonWindowsGetThreadId()
{
// TODO:PSL clean this up
return 0;
}
internal static class Unix
{
private static string s_userName;
public static string UserName
{
get
{
if (string.IsNullOrEmpty(s_userName))
{
s_userName = NativeMethods.GetUserName();
}
return s_userName ?? string.Empty;
}
}
public static string TemporaryDirectory
{
get
{
// POSIX temporary directory environment variables
string[] environmentVariables = { "TMPDIR", "TMP", "TEMP", "TEMPDIR" };
string dir = string.Empty;
foreach (string s in environmentVariables)
{
dir = System.Environment.GetEnvironmentVariable(s);
if (!string.IsNullOrEmpty(dir))
{
return dir;
}
}
return "/tmp";
}
}
public static bool IsHardLink(ref IntPtr handle)
{
// TODO:PSL implement using fstat to query inode refcount to see if it is a hard link
return false;
}
public static bool IsHardLink(FileSystemInfo fs)
{
if (!fs.Exists || (fs.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
return false;
}
int count;
string filePath = fs.FullName;
int ret = NativeMethods.GetLinkCount(filePath, out count);
if (ret == 1)
{
return count > 1;
}
else
{
int lastError = Marshal.GetLastWin32Error();
throw new InvalidOperationException("Unix.IsHardLink error: " + lastError);
}
}
public static void SetDate(SetDateInfoInternal info)
{
int ret = NativeMethods.SetDate(info);
if (ret == -1)
{
int lastError = Marshal.GetLastWin32Error();
throw new InvalidOperationException("Unix.NonWindowsSetDate error: " + lastError);
}
}
public static bool CreateHardLink(string path, string strTargetPath)
{
int ret = NativeMethods.CreateHardLink(path, strTargetPath);
return ret == 1 ? true : false;
}
[StructLayout(LayoutKind.Sequential)]
internal class SetDateInfoInternal
{
public int Year;
public int Month;
public int Day;
public int Hour;
public int Minute;
public int Second;
public int Millisecond;
public int DST;
public SetDateInfoInternal(DateTime d)
{
Year = d.Year;
Month = d.Month;
Day = d.Day;
Hour = d.Hour;
Minute = d.Minute;
Second = d.Second;
Millisecond = d.Millisecond;
DST = d.IsDaylightSavingTime() ? 1 : 0;
}
public override string ToString()
{
string ret = String.Format("Year = {0}; Month = {1}; Day = {2}; Hour = {3}; Minute = {4}; Second = {5}; Millisec = {6}; DST = {7}", Year, Month, Day, Hour, Minute, Second, Millisecond, DST);
return ret;
}
}
internal static class NativeMethods
{
private const string psLib = "libpsl-native";
// Ansi is a misnomer, it is hardcoded to UTF-8 on Linux and OS X
// C bools are 1 byte and so must be marshaled as I1
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.LPStr)]
internal static extern string GetUserName();
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int GetLinkCount([MarshalAs(UnmanagedType.LPStr)]string filePath, out int linkCount);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.I1)]
internal static extern bool IsSymLink([MarshalAs(UnmanagedType.LPStr)]string filePath);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.I1)]
internal static extern bool IsExecutable([MarshalAs(UnmanagedType.LPStr)]string filePath);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.LPStr)]
internal static extern string GetFullyQualifiedName();
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int SetDate(SetDateInfoInternal info);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.I1)]
internal static extern bool CreateSymLink([MarshalAs(UnmanagedType.LPStr)]string filePath,
[MarshalAs(UnmanagedType.LPStr)]string target);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int CreateHardLink([MarshalAs(UnmanagedType.LPStr)]string filePath,
[MarshalAs(UnmanagedType.LPStr)]string target);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.LPStr)]
internal static extern string FollowSymLink([MarshalAs(UnmanagedType.LPStr)]string filePath);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.LPStr)]
internal static extern string GetUserFromPid(int pid);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.I1)]
internal static extern bool IsFile([MarshalAs(UnmanagedType.LPStr)]string filePath);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.I1)]
internal static extern bool IsDirectory([MarshalAs(UnmanagedType.LPStr)]string filePath);
}
}
}
} // namespace System.Management.Automation
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using JsonLD.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JsonLD.Core
{
/// <summary>
/// Starting to migrate away from using plain java Maps as the internal RDF
/// dataset store.
/// </summary>
/// <remarks>
/// Starting to migrate away from using plain java Maps as the internal RDF
/// dataset store. Currently each item just wraps a Map based on the old format
/// so everything doesn't break. Will phase this out once everything is using the
/// new format.
/// </remarks>
/// <author>Tristan</author>
//[System.Serializable]
public class RDFDataset : Dictionary<string,object>
{
//[System.Serializable]
public class Quad : Dictionary<string,object>, IComparable<RDFDataset.Quad>
{
public Quad(string subject, string predicate, string @object, string graph) : this
(subject, predicate, @object.StartsWith("_:") ? (Node)new RDFDataset.BlankNode(@object
) : (Node)new RDFDataset.IRI(@object), graph)
{
}
public Quad(string subject, string predicate, string value, string datatype, string
language, string graph) : this(subject, predicate, new RDFDataset.Literal(value
, datatype, language), graph)
{
}
private Quad(string subject, string predicate, RDFDataset.Node @object, string graph
) : this(subject.StartsWith("_:") ? (Node)new RDFDataset.BlankNode(subject) : (Node)new RDFDataset.IRI
(subject), new RDFDataset.IRI(predicate), @object, graph)
{
}
public Quad(RDFDataset.Node subject, RDFDataset.Node predicate, RDFDataset.Node @object
, string graph) : base()
{
this["subject"] = subject;
this["predicate"] = predicate;
this["object"] = @object;
if (graph != null && !"@default".Equals(graph))
{
// TODO: i'm not yet sure if this should be added or if the
// graph should only be represented by the keys in the dataset
this["name"] = graph.StartsWith("_:") ? (Node)new RDFDataset.BlankNode(graph) : (Node)new RDFDataset.IRI
(graph);
}
}
public virtual RDFDataset.Node GetSubject()
{
return (RDFDataset.Node)this["subject"];
}
public virtual RDFDataset.Node GetPredicate()
{
return (RDFDataset.Node)this["predicate"];
}
public virtual RDFDataset.Node GetObject()
{
return (RDFDataset.Node)this["object"];
}
public virtual RDFDataset.Node GetGraph()
{
return (RDFDataset.Node)this["name"];
}
public virtual int CompareTo(RDFDataset.Quad o)
{
if (o == null)
{
return 1;
}
int rval = GetGraph().CompareTo(o.GetGraph());
if (rval != 0)
{
return rval;
}
rval = GetSubject().CompareTo(o.GetSubject());
if (rval != 0)
{
return rval;
}
rval = GetPredicate().CompareTo(o.GetPredicate());
if (rval != 0)
{
return rval;
}
return GetObject().CompareTo(o.GetObject());
}
}
//[System.Serializable]
public abstract class Node : Dictionary<string,object>, IComparable<RDFDataset.Node
>
{
public abstract bool IsLiteral();
public abstract bool IsIRI();
public abstract bool IsBlankNode();
public virtual string GetValue()
{
object value;
return this.TryGetValue("value", out value) ? (string)value : null;
}
public virtual string GetDatatype()
{
object value;
return this.TryGetValue("datatype", out value) ? (string)value : null;
}
public virtual string GetLanguage()
{
object value;
return this.TryGetValue("language", out value) ? (string)value : null;
}
public virtual int CompareTo(RDFDataset.Node o)
{
if (this.IsIRI())
{
if (!o.IsIRI())
{
// IRIs > everything
return 1;
}
}
else
{
if (this.IsBlankNode())
{
if (o.IsIRI())
{
// IRI > blank node
return -1;
}
else
{
if (o.IsLiteral())
{
// blank node > literal
return 1;
}
}
}
}
return string.CompareOrdinal(this.GetValue(), o.GetValue());
}
/// <summary>Converts an RDF triple object to a JSON-LD object.</summary>
/// <remarks>Converts an RDF triple object to a JSON-LD object.</remarks>
/// <param name="o">the RDF triple object to convert.</param>
/// <param name="useNativeTypes">true to output native types, false not to.</param>
/// <returns>the JSON-LD object.</returns>
/// <exception cref="JsonLdError">JsonLdError</exception>
/// <exception cref="JsonLD.Core.JsonLdError"></exception>
internal virtual JObject ToObject(bool useNativeTypes)
{
// If value is an an IRI or a blank node identifier, return a new
// JSON object consisting
// of a single member @id whose value is set to value.
if (IsIRI() || IsBlankNode())
{
JObject obj = new JObject();
obj["@id"] = GetValue();
return obj;
}
// convert literal object to JSON-LD
JObject rval = new JObject();
rval["@value"] = GetValue();
// add language
if (GetLanguage() != null)
{
rval["@language"] = GetLanguage();
}
else
{
// add datatype
string type = GetDatatype();
string value = GetValue();
if (useNativeTypes)
{
// use native datatypes for certain xsd types
if (JSONLDConsts.XsdString.Equals(type))
{
}
else
{
// don't add xsd:string
if (JSONLDConsts.XsdBoolean.Equals(type))
{
if ("true".Equals(value))
{
rval["@value"] = true;
}
else
{
if ("false".Equals(value))
{
rval["@value"] = false;
}
}
}
else
{
if (Pattern.Matches(value, "^[+-]?[0-9]+((?:\\.?[0-9]+((?:E?[+-]?[0-9]+)|)|))$"))
{
try
{
double d = double.Parse(value, CultureInfo.InvariantCulture);
if (!double.IsNaN(d) && !double.IsInfinity(d))
{
if (JSONLDConsts.XsdInteger.Equals(type))
{
int i = (int)d;
if (i.ToString().Equals(value))
{
rval["@value"] = i;
}
}
else
{
if (JSONLDConsts.XsdDouble.Equals(type))
{
rval["@value"] = d;
}
else
{
// we don't know the type, so we should add
// it to the JSON-LD
rval["@type"] = type;
}
}
}
}
catch
{
// TODO: This should never happen since we match the
// value with regex!
throw;
}
}
else
{
// do not add xsd:string type
rval["@type"] = type;
}
}
}
}
else
{
if (!JSONLDConsts.XsdString.Equals(type))
{
rval["@type"] = type;
}
}
}
return rval;
}
}
//[System.Serializable]
public class Literal : RDFDataset.Node
{
public Literal(string value, string datatype, string language) : base()
{
this["type"] = "literal";
this["value"] = value;
this["datatype"] = datatype != null ? datatype : JSONLDConsts.XsdString;
if (language != null)
{
this["language"] = language;
}
}
public override bool IsLiteral()
{
return true;
}
public override bool IsIRI()
{
return false;
}
public override bool IsBlankNode()
{
return false;
}
public override int CompareTo(RDFDataset.Node o)
{
if (o == null)
{
// valid nodes are > null nodes
return 1;
}
if (o.IsIRI())
{
// literals < iri
return -1;
}
if (o.IsBlankNode())
{
// blank node < iri
return -1;
}
if (this.GetLanguage() == null && ((RDFDataset.Literal)o).GetLanguage() != null)
{
return -1;
}
else
{
if (this.GetLanguage() != null && ((RDFDataset.Literal)o).GetLanguage() == null)
{
return 1;
}
}
if (this.GetDatatype() != null)
{
return string.CompareOrdinal(this.GetDatatype(), ((RDFDataset.Literal)o).GetDatatype
());
}
else
{
if (((RDFDataset.Literal)o).GetDatatype() != null)
{
return -1;
}
}
return 0;
}
}
//[System.Serializable]
public class IRI : RDFDataset.Node
{
public IRI(string iri) : base()
{
this["type"] = "IRI";
this["value"] = iri;
}
public override bool IsLiteral()
{
return false;
}
public override bool IsIRI()
{
return true;
}
public override bool IsBlankNode()
{
return false;
}
}
//[System.Serializable]
public class BlankNode : RDFDataset.Node
{
public BlankNode(string attribute) : base()
{
this["type"] = "blank node";
this["value"] = attribute;
}
public override bool IsLiteral()
{
return false;
}
public override bool IsIRI()
{
return false;
}
public override bool IsBlankNode()
{
return true;
}
}
private static readonly RDFDataset.Node first = new RDFDataset.IRI(JSONLDConsts.RdfFirst
);
private static readonly RDFDataset.Node rest = new RDFDataset.IRI(JSONLDConsts.RdfRest
);
private static readonly RDFDataset.Node nil = new RDFDataset.IRI(JSONLDConsts.RdfNil
);
private readonly IDictionary<string, string> context;
private JsonLdApi api;
public RDFDataset() : base()
{
// private UniqueNamer namer;
this["@default"] = new List<Quad>();
context = new Dictionary<string, string>();
}
public RDFDataset(JsonLdApi jsonLdApi) : this()
{
// put("@context", context);
this.api = jsonLdApi;
}
public virtual void SetNamespace(string ns, string prefix)
{
context[ns] = prefix;
}
public virtual string GetNamespace(string ns)
{
return context[ns];
}
/// <summary>clears all the namespaces in this dataset</summary>
public virtual void ClearNamespaces()
{
context.Clear();
}
public virtual IDictionary<string, string> GetNamespaces()
{
return context;
}
/// <summary>Returns a valid @context containing any namespaces set</summary>
/// <returns></returns>
public virtual JObject GetContext()
{
JObject rval = new JObject();
rval.PutAll(context);
// replace "" with "@vocab"
if (rval.ContainsKey(string.Empty))
{
rval["@vocab"] = JsonLD.Collections.Remove(rval, string.Empty);
}
return rval;
}
/// <summary>parses a @context object and sets any namespaces found within it</summary>
/// <param name="context"></param>
public virtual void ParseContext(JObject context)
{
foreach (string key in context.GetKeys())
{
JToken val = context[key];
if ("@vocab".Equals(key))
{
if (val.IsNull() || JsonLdUtils.IsString(val))
{
SetNamespace(string.Empty, (string)val);
}
}
else
{
// TODO: the context is actually invalid, should we throw an
// exception?
if ("@context".Equals(key))
{
// go deeper!
ParseContext((JObject)context["@context"]);
}
else
{
if (!JsonLdUtils.IsKeyword(key))
{
// TODO: should we make sure val is a valid URI prefix (i.e. it
// ends with /# or ?)
// or is it ok that full URIs for terms are used?
if (val.Type == JTokenType.String)
{
SetNamespace(key, (string)context[key]);
}
else
{
if (JsonLdUtils.IsObject(val) && ((JObject)val).ContainsKey("@id"
))
{
SetNamespace(key, (string)((JObject)val)["@id"]);
}
}
}
}
}
}
}
/// <summary>Adds a triple to the @default graph of this dataset</summary>
/// <param name="s">the subject for the triple</param>
/// <param name="p">the predicate for the triple</param>
/// <param name="value">the value of the literal object for the triple</param>
/// <param name="datatype">
/// the datatype of the literal object for the triple (null values
/// will default to xsd:string)
/// </param>
/// <param name="language">the language of the literal object for the triple (or null)
/// </param>
public virtual void AddTriple(string s, string p, string value, string datatype,
string language)
{
AddQuad(s, p, value, datatype, language, "@default");
}
/// <summary>Adds a triple to the specified graph of this dataset</summary>
/// <param name="s">the subject for the triple</param>
/// <param name="p">the predicate for the triple</param>
/// <param name="value">the value of the literal object for the triple</param>
/// <param name="datatype">
/// the datatype of the literal object for the triple (null values
/// will default to xsd:string)
/// </param>
/// <param name="graph">the graph to add this triple to</param>
/// <param name="language">the language of the literal object for the triple (or null)
/// </param>
public virtual void AddQuad(string s, string p, string value, string datatype, string
language, string graph)
{
if (graph == null)
{
graph = "@default";
}
if (!this.ContainsKey(graph))
{
this[graph] = new List<Quad>();
}
((IList<Quad>)this[graph]).Add(new RDFDataset.Quad(s, p, value, datatype
, language, graph));
}
/// <summary>Adds a triple to the @default graph of this dataset</summary>
/// <param name="s">the subject for the triple</param>
/// <param name="p">the predicate for the triple</param>
/// <param name="o">the object for the triple</param>
/// <param name="datatype">
/// the datatype of the literal object for the triple (null values
/// will default to xsd:string)
/// </param>
/// <param name="language">the language of the literal object for the triple (or null)
/// </param>
public virtual void AddTriple(string s, string p, string o)
{
AddQuad(s, p, o, "@default");
}
/// <summary>Adds a triple to thespecified graph of this dataset</summary>
/// <param name="s">the subject for the triple</param>
/// <param name="p">the predicate for the triple</param>
/// <param name="o">the object for the triple</param>
/// <param name="datatype">
/// the datatype of the literal object for the triple (null values
/// will default to xsd:string)
/// </param>
/// <param name="graph">the graph to add this triple to</param>
/// <param name="language">the language of the literal object for the triple (or null)
/// </param>
public virtual void AddQuad(string s, string p, string o, string graph)
{
if (graph == null)
{
graph = "@default";
}
if (!this.ContainsKey(graph))
{
this[graph] = new List<Quad>();
}
((IList<Quad>)this[graph]).Add(new RDFDataset.Quad(s, p, o, graph));
}
/// <summary>Creates an array of RDF triples for the given graph.</summary>
/// <remarks>Creates an array of RDF triples for the given graph.</remarks>
/// <param name="graph">the graph to create RDF triples for.</param>
internal virtual void GraphToRDF(string graphName, JObject graph
)
{
// 4.2)
IList<RDFDataset.Quad> triples = new List<RDFDataset.Quad>();
// 4.3)
IEnumerable<string> subjects = graph.GetKeys();
// Collections.sort(subjects);
foreach (string id in subjects)
{
if (JsonLdUtils.IsRelativeIri(id))
{
continue;
}
JObject node = (JObject)graph[id];
JArray properties = new JArray(node.GetKeys());
properties.SortInPlace();
foreach (string property in properties)
{
var localProperty = property;
JArray values;
// 4.3.2.1)
if ("@type".Equals(localProperty))
{
values = (JArray)node["@type"];
localProperty = JSONLDConsts.RdfType;
}
else
{
// 4.3.2.2)
if (JsonLdUtils.IsKeyword(localProperty))
{
continue;
}
else
{
// 4.3.2.3)
if (localProperty.StartsWith("_:") && !api.opts.GetProduceGeneralizedRdf())
{
continue;
}
else
{
// 4.3.2.4)
if (JsonLdUtils.IsRelativeIri(localProperty))
{
continue;
}
else
{
values = (JArray)node[localProperty];
}
}
}
}
RDFDataset.Node subject;
if (id.IndexOf("_:") == 0)
{
// NOTE: don't rename, just set it as a blank node
subject = new RDFDataset.BlankNode(id);
}
else
{
subject = new RDFDataset.IRI(id);
}
// RDF predicates
RDFDataset.Node predicate;
if (localProperty.StartsWith("_:"))
{
predicate = new RDFDataset.BlankNode(localProperty);
}
else
{
predicate = new RDFDataset.IRI(localProperty);
}
foreach (JToken item in values)
{
// convert @list to triples
if (JsonLdUtils.IsList(item))
{
JArray list = (JArray)((JObject)item)["@list"];
RDFDataset.Node last = null;
RDFDataset.Node firstBNode = nil;
if (!list.IsEmpty())
{
last = ObjectToRDF(list[list.Count - 1]);
firstBNode = new RDFDataset.BlankNode(api.GenerateBlankNodeIdentifier());
}
triples.Add(new RDFDataset.Quad(subject, predicate, firstBNode, graphName));
for (int i = 0; i < list.Count - 1; i++)
{
RDFDataset.Node @object = ObjectToRDF(list[i]);
triples.Add(new RDFDataset.Quad(firstBNode, first, @object, graphName));
RDFDataset.Node restBNode = new RDFDataset.BlankNode(api.GenerateBlankNodeIdentifier
());
triples.Add(new RDFDataset.Quad(firstBNode, rest, restBNode, graphName));
firstBNode = restBNode;
}
if (last != null)
{
triples.Add(new RDFDataset.Quad(firstBNode, first, last, graphName));
triples.Add(new RDFDataset.Quad(firstBNode, rest, nil, graphName));
}
}
else
{
// convert value or node object to triple
RDFDataset.Node @object = ObjectToRDF(item);
if (@object != null)
{
triples.Add(new RDFDataset.Quad(subject, predicate, @object, graphName));
}
}
}
}
}
this[graphName] = triples;
}
/// <summary>
/// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
/// node object to an RDF resource.
/// </summary>
/// <remarks>
/// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
/// node object to an RDF resource.
/// </remarks>
/// <param name="item">the JSON-LD value or node object.</param>
/// <param name="namer">the UniqueNamer to use to assign blank node names.</param>
/// <returns>the RDF literal or RDF resource.</returns>
private RDFDataset.Node ObjectToRDF(JToken item)
{
// convert value object to RDF
if (JsonLdUtils.IsValue(item))
{
JToken value = ((JObject)item)["@value"];
JToken datatype = ((JObject)item)["@type"];
// convert to XSD datatypes as appropriate
if (value.Type == JTokenType.Boolean || value.Type == JTokenType.Float || value.Type == JTokenType.Integer)
{
// convert to XSD datatype
if (value.Type == JTokenType.Boolean)
{
var serializeObject = JsonConvert.SerializeObject(value, Formatting.None).Trim('"');
return new RDFDataset.Literal(serializeObject, datatype.IsNull() ? JSONLDConsts.XsdBoolean
: (string)datatype, null);
}
else
{
if (value.Type == JTokenType.Float || datatype.SafeCompare(JSONLDConsts.XsdDouble))
{
// Workaround for Newtonsoft.Json's refusal to cast a JTokenType.Integer to a double.
if (value.Type == JTokenType.Integer)
{
int number = (int)value;
value = new JValue((double)number);
}
// canonical double representation
return new RDFDataset.Literal(string.Format(CultureInfo.InvariantCulture, "{0:0.0###############E0}", (double)value), datatype.IsNull() ? JSONLDConsts.XsdDouble
: (string)datatype, null);
}
else
{
return new RDFDataset.Literal(string.Format("{0:0}",value), datatype.IsNull() ? JSONLDConsts.XsdInteger
: (string)datatype, null);
}
}
}
else
{
if (((JObject)item).ContainsKey("@language"))
{
return new RDFDataset.Literal((string)value, datatype.IsNull() ? JSONLDConsts.RdfLangstring
: (string)datatype, (string)((JObject)item)["@language"]);
}
else
{
var serializeObject = JsonConvert.SerializeObject(value, Formatting.None).Trim('"');
return new RDFDataset.Literal(serializeObject, datatype.IsNull() ? JSONLDConsts.XsdString
: (string)datatype, null);
}
}
}
else
{
// convert string/node object to RDF
string id;
if (JsonLdUtils.IsObject(item))
{
id = (string)((JObject)item)["@id"];
if (JsonLdUtils.IsRelativeIri(id))
{
return null;
}
}
else
{
id = (string)item;
}
if (id.IndexOf("_:") == 0)
{
// NOTE: once again no need to rename existing blank nodes
return new RDFDataset.BlankNode(id);
}
else
{
return new RDFDataset.IRI(id);
}
}
}
public virtual IList<string> GraphNames()
{
return new List<string>(Keys);
}
public virtual IList<Quad> GetQuads(string graphName)
{
return (IList<Quad>)this[graphName];
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Xml;
using Microsoft.Win32;
using System.Collections.Generic;
using System.Management.Automation.Language;
namespace System.Management.Automation
{
/// <summary>
/// Defines generic utilities and helper methods for PowerShell.
/// </summary>
internal static class PsUtils
{
internal static string ArmArchitecture = "ARM";
/// <summary>
/// Safely retrieves the MainModule property of a
/// process. Version 2.0 and below of the .NET Framework are
/// impacted by a Win32 API usability knot that throws an
/// exception if API tries to enumerate the process' modules
/// while it is still loading them. This generates the error
/// message: Only part of a ReadProcessMemory or
/// WriteProcessMemory request was completed.
/// The BCL fix in V3 was to just try more, so we do the same
/// thing.
///
/// Note: If you attempt to retrieve the MainModule of a 64-bit
/// process from a WOW64 (32-bit) process, the Win32 API has a fatal
/// flaw that causes this to return the same error.
///
/// If you need the MainModule of a 64-bit process from a WOW64
/// process, you will need to write the P/Invoke yourself.
/// </summary>
/// <param name="targetProcess">The process from which to
/// retrieve the MainModule</param>
/// <exception cref="NotSupportedException">
/// You are trying to access the MainModule property for a process that is running
/// on a remote computer. This property is available only for processes that are
/// running on the local computer.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The process Id is not available (or) The process has exited.
/// </exception>
/// <exception cref="System.ComponentModel.Win32Exception">
/// </exception>
internal static ProcessModule GetMainModule(Process targetProcess)
{
int caughtCount = 0;
while (true)
{
try
{
return targetProcess.MainModule;
}
catch (System.ComponentModel.Win32Exception e)
{
// If this is an Access Denied error (which can happen with thread impersonation)
// then re-throw immediately.
if (e.NativeErrorCode == 5)
throw;
// Otherwise retry to ensure module is loaded.
caughtCount++;
System.Threading.Thread.Sleep(100);
if (caughtCount == 5)
throw;
}
}
}
// Cache of the current process' parentId
private static int? s_currentParentProcessId;
private static readonly int s_currentProcessId = Process.GetCurrentProcess().Id;
/// <summary>
/// Retrieve the parent process of a process.
///
/// Previously this code used WMI, but WMI is causing a CPU spike whenever the query gets called as it results in
/// tzres.dll and tzres.mui.dll being loaded into every process to convert the time information to local format.
/// For perf reasons, we resort to P/Invoke.
/// </summary>
/// <param name="current">The process we want to find the
/// parent of</param>
internal static Process GetParentProcess(Process current)
{
var processId = current.Id;
// This is a common query (parent id for the current process)
// Use cached value if available
var parentProcessId = processId == s_currentProcessId && s_currentParentProcessId.HasValue ?
s_currentParentProcessId.Value :
Microsoft.PowerShell.ProcessCodeMethods.GetParentPid(current);
// cache the current process parent pid if it hasn't been done yet
if (processId == s_currentProcessId && !s_currentParentProcessId.HasValue)
{
s_currentParentProcessId = parentProcessId;
}
if (parentProcessId == 0)
return null;
try
{
Process returnProcess = Process.GetProcessById(parentProcessId);
// Ensure the process started before the current
// process, as it could have gone away and had the
// PID recycled.
if (returnProcess.StartTime <= current.StartTime)
return returnProcess;
else
return null;
}
catch (ArgumentException)
{
// GetProcessById throws an ArgumentException when
// you reach the top of the chain -- Explorer.exe
// has a parent process, but you cannot retrieve it.
return null;
}
}
/// <summary>
/// Returns processor architecture for the current process.
/// If powershell is running inside Wow64, then <see cref="ProcessorArchitecture.X86"/> is returned.
/// </summary>
/// <returns>Processor architecture for the current process.</returns>
internal static ProcessorArchitecture GetProcessorArchitecture(out bool isRunningOnArm)
{
var sysInfo = new NativeMethods.SYSTEM_INFO();
NativeMethods.GetSystemInfo(ref sysInfo);
ProcessorArchitecture result;
isRunningOnArm = false;
switch (sysInfo.wProcessorArchitecture)
{
case NativeMethods.PROCESSOR_ARCHITECTURE_IA64:
result = ProcessorArchitecture.IA64;
break;
case NativeMethods.PROCESSOR_ARCHITECTURE_AMD64:
result = ProcessorArchitecture.Amd64;
break;
case NativeMethods.PROCESSOR_ARCHITECTURE_INTEL:
result = ProcessorArchitecture.X86;
break;
case NativeMethods.PROCESSOR_ARCHITECTURE_ARM:
result = ProcessorArchitecture.None;
isRunningOnArm = true;
break;
default:
result = ProcessorArchitecture.None;
break;
}
return result;
}
/// <summary>
/// Return true/false to indicate whether the processor architecture is ARM.
/// </summary>
/// <returns></returns>
internal static bool IsRunningOnProcessorArchitectureARM()
{
Architecture arch = RuntimeInformation.OSArchitecture;
return arch == Architecture.Arm || arch == Architecture.Arm64;
}
/// <summary>
/// Get a temporary directory to use, needs to be unique to avoid collision.
/// </summary>
internal static string GetTemporaryDirectory()
{
string tempDir = string.Empty;
string tempPath = Path.GetTempPath();
do
{
tempDir = Path.Combine(tempPath,System.Guid.NewGuid().ToString());
}
while (Directory.Exists(tempDir));
try
{
Directory.CreateDirectory(tempDir);
}
catch (UnauthorizedAccessException)
{
tempDir = string.Empty; // will become current working directory
}
return tempDir;
}
internal static string GetHostName()
{
// Note: non-windows CoreCLR does not support System.Net yet
if (Platform.IsWindows)
{
return WinGetHostName();
}
else
{
return Platform.NonWindowsGetHostName();
}
}
internal static string WinGetHostName()
{
System.Net.NetworkInformation.IPGlobalProperties ipProperties =
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
string hostname = ipProperties.HostName;
if (!string.IsNullOrEmpty(ipProperties.DomainName))
{
hostname = hostname + "." + ipProperties.DomainName;
}
return hostname;
}
internal static uint GetNativeThreadId()
{
#if UNIX
return Platform.NonWindowsGetThreadId();
#else
return NativeMethods.GetCurrentThreadId();
#endif
}
private static class NativeMethods
{
internal const ushort PROCESSOR_ARCHITECTURE_INTEL = 0;
internal const ushort PROCESSOR_ARCHITECTURE_ARM = 5;
internal const ushort PROCESSOR_ARCHITECTURE_IA64 = 6;
internal const ushort PROCESSOR_ARCHITECTURE_AMD64 = 9;
internal const ushort PROCESSOR_ARCHITECTURE_UNKNOWN = 0xFFFF;
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEM_INFO
{
public ushort wProcessorArchitecture;
public ushort wReserved;
public uint dwPageSize;
public IntPtr lpMinimumApplicationAddress;
public IntPtr lpMaximumApplicationAddress;
public UIntPtr dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public ushort wProcessorLevel;
public ushort wProcessorRevision;
};
[DllImport(PinvokeDllNames.GetSystemInfoDllName)]
internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
[DllImport(PinvokeDllNames.GetCurrentThreadIdDllName)]
internal static extern uint GetCurrentThreadId();
}
#region ASTUtils
/// <summary>
/// This method is to get the unique key for a UsingExpressionAst. The key is a base64
/// encoded string based on the text of the UsingExpressionAst.
///
/// This method is used when handling a script block that contains $using for Invoke-Command.
///
/// When run Invoke-Command targeting a machine that runs PSv3 or above, we pass a dictionary
/// to the remote end that contains the key of each UsingExpressionAst and its value. This method
/// is used to generate the key.
/// </summary>
/// <param name="usingAst">A using expression.</param>
/// <returns>Base64 encoded string as the key of the UsingExpressionAst.</returns>
internal static string GetUsingExpressionKey(Language.UsingExpressionAst usingAst)
{
Diagnostics.Assert(usingAst != null, "Caller makes sure the parameter is not null");
// We cannot call ToLowerInvariant unconditionally, because usingAst might
// contain IndexExpressionAst in its SubExpression, such as
// $using:bar["AAAA"]
// and the index "AAAA" might not get us the same value as "aaaa".
//
// But we do want a unique key to represent the same UsingExpressionAst's as much
// as possible, so as to avoid sending redundant key-value's to remote machine.
// As a workaround, we call ToLowerInvariant when the SubExpression of usingAst
// is a VariableExpressionAst, because:
// (1) Variable name is case insensitive;
// (2) People use $using to refer to a variable most of the time.
string usingAstText = usingAst.ToString();
if (usingAst.SubExpression is Language.VariableExpressionAst)
{
usingAstText = usingAstText.ToLowerInvariant();
}
return StringToBase64Converter.StringToBase64String(usingAstText);
}
#endregion ASTUtils
#region EvaluatePowerShellDataFile
/// <summary>
/// Evaluate a powershell data file as if it's a module manifest.
/// </summary>
/// <param name="parameterName"></param>
/// <param name="psDataFilePath"></param>
/// <param name="context"></param>
/// <param name="skipPathValidation"></param>
/// <returns></returns>
internal static Hashtable EvaluatePowerShellDataFileAsModuleManifest(
string parameterName,
string psDataFilePath,
ExecutionContext context,
bool skipPathValidation)
{
// Use the same capabilities as the module manifest
// e.g. allow 'PSScriptRoot' variable
return EvaluatePowerShellDataFile(
parameterName,
psDataFilePath,
context,
Microsoft.PowerShell.Commands.ModuleCmdletBase.PermittedCmdlets,
new[] { "PSScriptRoot" },
allowEnvironmentVariables: true,
skipPathValidation: skipPathValidation);
}
/// <summary>
/// Get a Hashtable object out of a PowerShell data file (.psd1)
/// </summary>
/// <param name="parameterName">
/// Name of the parameter that takes the specified .psd1 file as a value
/// </param>
/// <param name="psDataFilePath">
/// Path to the powershell data file
/// </param>
/// <param name="context">
/// ExecutionContext to use
/// </param>
/// <param name="allowedCommands">
/// Set of command names that are allowed to use in the .psd1 file
/// </param>
/// <param name="allowedVariables">
/// Set of variable names that are allowed to use in the .psd1 file
/// </param>
/// <param name="allowEnvironmentVariables">
/// If true, allow to use environment variables in the .psd1 file
/// </param>
/// <param name="skipPathValidation">
/// If true, caller guarantees the path is valid
/// </param>
/// <returns></returns>
internal static Hashtable EvaluatePowerShellDataFile(
string parameterName,
string psDataFilePath,
ExecutionContext context,
IEnumerable<string> allowedCommands,
IEnumerable<string> allowedVariables,
bool allowEnvironmentVariables,
bool skipPathValidation)
{
if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException("parameterName"); }
if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException("psDataFilePath"); }
if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); }
string resolvedPath;
if (skipPathValidation)
{
resolvedPath = psDataFilePath;
}
else
{
#region "ValidatePowerShellDataFilePath"
bool isPathValid = true;
// File extension needs to be .psd1
string pathExt = Path.GetExtension(psDataFilePath);
if (string.IsNullOrEmpty(pathExt) ||
!StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase))
{
isPathValid = false;
}
ProviderInfo provider;
var resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider);
// ConfigPath should be resolved as FileSystem provider
if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase))
{
isPathValid = false;
}
// ConfigPath should be resolved to a single path
if (resolvedPaths.Count != 1)
{
isPathValid = false;
}
if (!isPathValid)
{
throw PSTraceSource.NewArgumentException(
parameterName,
ParserStrings.CannotResolvePowerShellDataFilePath,
psDataFilePath);
}
resolvedPath = resolvedPaths[0];
#endregion "ValidatePowerShellDataFilePath"
}
#region "LoadAndEvaluatePowerShellDataFile"
object evaluationResult;
try
{
// Create the scriptInfo for the .psd1 file
string dataFileName = Path.GetFileName(resolvedPath);
var dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context);
ScriptBlock scriptBlock = dataFileScriptInfo.ScriptBlock;
// Validate the scriptblock
scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables);
// Evaluate the scriptblock
object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath);
try
{
// Set the $PSScriptRoot before the evaluation
context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath));
evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs());
}
finally
{
context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot);
}
}
catch (RuntimeException ex)
{
throw PSTraceSource.NewInvalidOperationException(
ex,
ParserStrings.CannotLoadPowerShellDataFile,
psDataFilePath,
ex.Message);
}
var retResult = evaluationResult as Hashtable;
if (retResult == null)
{
throw PSTraceSource.NewInvalidOperationException(
ParserStrings.InvalidPowerShellDataFile,
psDataFilePath);
}
#endregion "LoadAndEvaluatePowerShellDataFile"
return retResult;
}
#endregion EvaluatePowerShellDataFile
internal static readonly string[] ManifestModuleVersionPropertyName = new[] { "ModuleVersion" };
internal static readonly string[] ManifestGuidPropertyName = new[] { "GUID" };
internal static readonly string[] ManifestPrivateDataPropertyName = new[] { "PrivateData" };
internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[]
{
"AliasesToExport",
"CmdletsToExport",
"CompatiblePSEditions",
"FunctionsToExport",
"NestedModules",
"RootModule",
"ModuleToProcess",
"ModuleVersion"
};
internal static Hashtable GetModuleManifestProperties(string psDataFilePath, string[] keys)
{
string dataFileContents = ScriptAnalysis.ReadScript(psDataFilePath);
ParseError[] parseErrors;
var ast = (new Parser()).Parse(psDataFilePath, dataFileContents, null, out parseErrors, ParseMode.ModuleAnalysis);
if (parseErrors.Length > 0)
{
var pe = new ParseException(parseErrors);
throw PSTraceSource.NewInvalidOperationException(
pe,
ParserStrings.CannotLoadPowerShellDataFile,
psDataFilePath,
pe.Message);
}
string unused1;
string unused2;
var pipeline = ast.GetSimplePipeline(false, out unused1, out unused2);
if (pipeline != null)
{
var hashtableAst = pipeline.GetPureExpression() as HashtableAst;
if (hashtableAst != null)
{
var result = new Hashtable(StringComparer.OrdinalIgnoreCase);
foreach (var pair in hashtableAst.KeyValuePairs)
{
var key = pair.Item1 as StringConstantExpressionAst;
if (key != null && keys.Contains(key.Value, StringComparer.OrdinalIgnoreCase))
{
try
{
var val = pair.Item2.SafeGetValue();
result[key.Value] = val;
}
catch
{
throw PSTraceSource.NewInvalidOperationException(
ParserStrings.InvalidPowerShellDataFile,
psDataFilePath);
}
}
}
return result;
}
}
throw PSTraceSource.NewInvalidOperationException(
ParserStrings.InvalidPowerShellDataFile,
psDataFilePath);
}
}
/// <summary>
/// This class provides helper methods for converting to/fro from
/// string to base64string.
/// </summary>
internal static class StringToBase64Converter
{
/// <summary>
/// Converts string to base64 encoded string.
/// </summary>
/// <param name="input">String to encode.</param>
/// <returns>Base64 encoded string.</returns>
internal static string StringToBase64String(string input)
{
// NTRAID#Windows Out Of Band Releases-926471-2005/12/27-JonN
// shell crashes if you pass an empty script block to a native command
if (input == null)
{
throw PSTraceSource.NewArgumentNullException("input");
}
string base64 = Convert.ToBase64String
(
Encoding.Unicode.GetBytes(input.ToCharArray())
);
return base64;
}
/// <summary>
/// Decodes base64 encoded string.
/// </summary>
/// <param name="base64">Base64 string to decode.</param>
/// <returns>Decoded string.</returns>
internal static string Base64ToString(string base64)
{
if (string.IsNullOrEmpty(base64))
{
throw PSTraceSource.NewArgumentNullException("base64");
}
string output = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64)));
return output;
}
/// <summary>
/// Decodes base64 encoded string in to args array.
/// </summary>
/// <param name="base64"></param>
/// <returns></returns>
internal static object[] Base64ToArgsConverter(string base64)
{
if (string.IsNullOrEmpty(base64))
{
throw PSTraceSource.NewArgumentNullException("base64");
}
string decoded = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64)));
// Deserialize string
XmlReader reader = XmlReader.Create(new StringReader(decoded), InternalDeserializer.XmlReaderSettingsForCliXml);
object dso;
Deserializer deserializer = new Deserializer(reader);
dso = deserializer.Deserialize();
if (deserializer.Done() == false)
{
// This helper function should move to host and it should provide appropriate
// error message there.
throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter);
}
PSObject mo = dso as PSObject;
if (mo == null)
{
// This helper function should move the host. Provide appropriate error message.
// Format of args parameter is not correct.
throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter);
}
var argsList = mo.BaseObject as ArrayList;
if (argsList == null)
{
// This helper function should move the host. Provide appropriate error message.
// Format of args parameter is not correct.
throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter);
}
return argsList.ToArray();
}
}
/// <summary>
/// A simple implementation of CRC32.
/// See "CRC-32 algorithm" in https://en.wikipedia.org/wiki/Cyclic_redundancy_check.
/// </summary>
internal class CRC32Hash
{
// CRC-32C polynomial representations
private const uint polynomial = 0x1EDC6F41;
private static uint[] table;
static CRC32Hash()
{
uint temp = 0;
table = new uint[256];
for (int i = 0; i < table.Length; i++)
{
temp = (uint)i;
for (int j = 0; j < 8; j++)
{
if ((temp & 1) == 1)
{
temp = (temp >> 1) ^ polynomial;
}
else
{
temp >>= 1;
}
}
table[i] = temp;
}
}
private static uint Compute(byte[] buffer)
{
uint crc = 0xFFFFFFFF;
for (int i = 0; i < buffer.Length; ++i)
{
var index = (byte)(crc ^ buffer[i] & 0xff);
crc = (crc >> 8) ^ table[index];
}
return ~crc;
}
internal static byte[] ComputeHash(byte[] buffer)
{
uint crcResult = Compute(buffer);
return BitConverter.GetBytes(crcResult);
}
internal static string ComputeHash(string input)
{
byte[] hashBytes = ComputeHash(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(hashBytes).Replace("-", string.Empty);
}
}
#region ReferenceEqualityComparer
/// <summary>
/// Equality comparer based on Object Identity.
/// </summary>
internal class ReferenceEqualityComparer : IEqualityComparer
{
bool IEqualityComparer.Equals(object x, object y)
{
return Object.ReferenceEquals(x, y);
}
int IEqualityComparer.GetHashCode(object obj)
{
// The Object.GetHashCode and RuntimeHelpers.GetHashCode methods are used in the following scenarios:
//
// Object.GetHashCode is useful in scenarios where you care about object value. Two strings with identical
// contents will return the same value for Object.GetHashCode.
//
// RuntimeHelpers.GetHashCode is useful in scenarios where you care about object identity. Two strings with
// identical contents will return different values for RuntimeHelpers.GetHashCode, because they are different
// string objects, although their contents are the same.
return RuntimeHelpers.GetHashCode(obj);
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.Build.Framework;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.Build.Construction;
using System.Net.Http;
using System.Xml;
using System.Globalization;
using System.Threading.Tasks;
using System.Linq;
using System.Diagnostics;
using System.Threading;
namespace Microsoft.DotNet.Build.Tasks
{
public partial class FinalizeBuild : Utility.AzureConnectionStringBuildTask
{
[Required]
public string SemaphoreBlob { get; set; }
[Required]
public string FinalizeContainer { get; set; }
public string MaxWait { get; set; }
public string Delay { get; set; }
[Required]
public string ContainerName { get; set; }
[Required]
public string Channel { get; set; }
[Required]
public string SharedFrameworkNugetVersion { get; set; }
[Required]
public string SharedHostNugetVersion { get; set; }
[Required]
public string Version { get; set; }
[Required]
public ITaskItem [] PublishRids { get; set; }
[Required]
public string CommitHash { get; set; }
public bool ForcePublish { get; set; }
private Regex _versionRegex = new Regex(@"(?<version>\d+\.\d+\.\d+)(-(?<prerelease>[^-]+-)?(?<major>\d+)-(?<minor>\d+))?");
public override bool Execute()
{
ParseConnectionString();
if (Log.HasLoggedErrors)
{
return false;
}
if (!FinalizeContainer.EndsWith("/"))
{
FinalizeContainer = $"{FinalizeContainer}/";
}
string targetVersionFile = $"{FinalizeContainer}{Version}";
CreateBlobIfNotExists(SemaphoreBlob);
AzureBlobLease blobLease = new AzureBlobLease(AccountName, AccountKey, ConnectionString, ContainerName, SemaphoreBlob, Log);
Log.LogMessage($"Acquiring lease on semaphore blob '{SemaphoreBlob}'");
blobLease.Acquire();
// Prevent race conditions by dropping a version hint of what version this is. If we see this file
// and it is the same as our version then we know that a race happened where two+ builds finished
// at the same time and someone already took care of publishing and we have no work to do.
if (IsLatestSpecifiedVersion(targetVersionFile) && !ForcePublish)
{
Log.LogMessage(MessageImportance.Low, $"version hint file for publishing finalization is {targetVersionFile}");
Log.LogMessage(MessageImportance.High, $"Version '{Version}' is already published, skipping finalization.");
Log.LogMessage($"Releasing lease on semaphore blob '{SemaphoreBlob}'");
blobLease.Release();
return true;
}
else
{
// Delete old version files
GetBlobList(FinalizeContainer)
.Select(s => s.Replace("/dotnet/", ""))
.Where(w => _versionRegex.Replace(Path.GetFileName(w), "") == "")
.ToList()
.ForEach(f => TryDeleteBlob(f));
// Drop the version file signaling such for any race-condition builds (see above comment).
CreateBlobIfNotExists(targetVersionFile);
try
{
CopyBlobs($"{Channel}/Binaries/{SharedFrameworkNugetVersion}", $"{Channel}/Binaries/Latest/");
CopyBlobs($"{Channel}/Installers/{SharedFrameworkNugetVersion}", $"{Channel}/Installers/Latest/");
CopyBlobs($"{Channel}/Installers/{SharedHostNugetVersion}", $"{Channel}/Installers/Latest/");
// Generate the Sharedfx Version text files
List<string> versionFiles = PublishRids.Select(p => $"{p.GetMetadata("VersionFileName")}.version").ToList();
string sfxVersion = GetSharedFrameworkVersionFileContent();
foreach(string version in versionFiles)
{
PublishStringToBlob(ContainerName, $"{Channel}/dnvm/latest.sharedfx.{version}", sfxVersion, "text/plain");
}
}
finally
{
blobLease.Release();
}
}
return !Log.HasLoggedErrors;
}
private string GetSharedFrameworkVersionFileContent()
{
string returnString = $"{CommitHash}{Environment.NewLine}";
returnString += $"{SharedFrameworkNugetVersion}{Environment.NewLine}";
return returnString;
}
public bool CopyBlobs(string sourceFolder, string destinationFolder)
{
bool returnStatus = true;
List<Task<bool>> copyTasks = new List<Task<bool>>();
string[] blobs = GetBlobList(sourceFolder);
foreach (string blob in blobs)
{
string targetName = Path.GetFileName(blob)
.Replace(SharedFrameworkNugetVersion, "latest")
.Replace(SharedHostNugetVersion, "latest");
string sourceBlob = blob.Replace($"/{ContainerName}/", "");
string destinationBlob = $"{destinationFolder}{targetName}";
Log.LogMessage($"Copying blob '{sourceBlob}' to '{destinationBlob}'");
copyTasks.Add(CopyBlobAsync(sourceBlob, destinationBlob));
}
Task.WaitAll(copyTasks.ToArray());
copyTasks.ForEach(c => returnStatus &= c.Result);
return returnStatus;
}
public bool TryDeleteBlob(string path)
{
return DeleteBlob(ContainerName, path);
}
public void CreateBlobIfNotExists(string path)
{
var blobList = GetBlobList(path);
if(blobList.Count() == 0)
{
PublishStringToBlob(ContainerName, path, DateTime.Now.ToString());
}
}
public bool IsLatestSpecifiedVersion(string versionFile)
{
var blobList = GetBlobList(versionFile);
return blobList.Count() != 0;
}
public bool DeleteBlob(string container, string blob)
{
return DeleteAzureBlob.Execute(AccountName,
AccountKey,
ConnectionString,
container,
blob,
BuildEngine,
HostObject);
}
public Task<bool> CopyBlobAsync(string sourceBlobName, string destinationBlobName)
{
return CopyAzureBlobToBlob.ExecuteAsync(AccountName,
AccountKey,
ConnectionString,
ContainerName,
sourceBlobName,
destinationBlobName,
BuildEngine,
HostObject);
}
public string[] GetBlobList(string path)
{
return GetAzureBlobList.Execute(AccountName,
AccountKey,
ConnectionString,
ContainerName,
path,
BuildEngine,
HostObject);
}
public bool PublishStringToBlob(string container, string blob, string contents, string contentType = null)
{
return PublishStringToAzureBlob.Execute(AccountName,
AccountKey,
ConnectionString,
container,
blob,
contents,
contentType,
BuildEngine,
HostObject);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization {
using System;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////////
//
// Notes about TaiwanLunisolarCalendar
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1912/02/18 2051/02/10
** TaiwanLunisolar 1912/01/01 2050/13/29
*/
[Serializable]
public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar {
// Since
// Gregorian Year = Era Year + yearOffset
// When Gregorian Year 1912 is year 1, so that
// 1912 = 1 + yearOffset
// So yearOffset = 1911
//m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911);
// Initialize our era info.
static internal EraInfo[] taiwanLunisolarEraInfo = new EraInfo[] {
new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear
};
internal GregorianCalendarHelper helper;
internal const int MIN_LUNISOLAR_YEAR = 1912;
internal const int MAX_LUNISOLAR_YEAR = 2050;
internal const int MIN_GREGORIAN_YEAR = 1912;
internal const int MIN_GREGORIAN_MONTH = 2;
internal const int MIN_GREGORIAN_DAY = 18;
internal const int MAX_GREGORIAN_YEAR = 2051;
internal const int MAX_GREGORIAN_MONTH = 2;
internal const int MAX_GREGORIAN_DAY = 10;
internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY);
internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999);
public override DateTime MinSupportedDateTime {
get
{
return (minDate);
}
}
public override DateTime MaxSupportedDateTime {
get
{
return (maxDate);
}
}
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// 1911 from ChineseLunisolarCalendar
return 384;
}
}
static readonly int [,] yinfo =
{
/*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days
1912 */{ 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355
1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385
1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384
1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354
1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354
1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383
1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355
1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353
1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355
1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384
1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384
1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354
1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384
1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354
2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354
2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384
2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384
2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355
2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384
2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384
2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384
2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355
2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354
2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
*/};
internal override int MinCalendarYear {
get
{
return (MIN_LUNISOLAR_YEAR);
}
}
internal override int MaxCalendarYear {
get
{
return (MAX_LUNISOLAR_YEAR);
}
}
internal override DateTime MinDate {
get
{
return (minDate);
}
}
internal override DateTime MaxDate {
get
{
return (maxDate);
}
}
internal override EraInfo[] CalEraInfo {
get
{
return (taiwanLunisolarEraInfo);
}
}
internal override int GetYearInfo(int LunarYear, int Index) {
if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
MIN_LUNISOLAR_YEAR,
MAX_LUNISOLAR_YEAR ));
}
Contract.EndContractBlock();
return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
}
internal override int GetYear(int year, DateTime time) {
return helper.GetYear(year, time);
}
internal override int GetGregorianYear(int year, int era) {
return helper.GetGregorianYear(year, era);
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of TaiwanLunisolarCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance()
{
if (m_defaultInstance == null) {
m_defaultInstance = new TaiwanLunisolarCalendar();
}
return (m_defaultInstance);
}
*/
// Construct an instance of TaiwanLunisolar calendar.
public TaiwanLunisolarCalendar() {
helper = new GregorianCalendarHelper(this, taiwanLunisolarEraInfo);
}
public override int GetEra(DateTime time) {
return (helper.GetEra(time));
}
internal override int BaseCalendarID {
get {
return (CAL_TAIWAN);
}
}
internal override int ID {
get {
return (CAL_TAIWANLUNISOLAR);
}
}
public override int[] Eras {
get {
return (helper.Eras);
}
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using Hydra.Framework.ImageProcessing.Analysis.Maths;
namespace Hydra.Framework.ImageProcessing.Analysis.Filters
{
//
//**********************************************************************
/// <summary>
/// HSLFiltering - filters pixels inside or outside specified HSL range
/// </summary>
//**********************************************************************
//
public class HSLFiltering
: IFilter
{
#region Private Constants
//
//**********************************************************************
/// <summary>
/// Default Fill Hue
/// </summary>
//**********************************************************************
//
private const int FillHue_sc = 0;
//
//**********************************************************************
/// <summary>
/// Default Fill Saturation
/// </summary>
//**********************************************************************
//
private const double FillSaturation_sc = 0.0;
//
//**********************************************************************
/// <summary>
/// Default Fill Luminance
/// </summary>
//**********************************************************************
//
private const double FillLuminance_sc = 0.0;
//
//**********************************************************************
/// <summary>
/// Default Fill Outside Range
/// </summary>
//**********************************************************************
//
private const bool FillOutsideRange_sc = true;
#endregion
#region Private Member Variables
//
//**********************************************************************
/// <summary>
/// Adjust Hue
/// </summary>
//**********************************************************************
//
private Range hue_m;
//
//**********************************************************************
/// <summary>
/// Adjust Saturation
/// </summary>
//**********************************************************************
//
private RangeD saturation_m;
//
//**********************************************************************
/// <summary>
/// Adjust Luminance
/// </summary>
//**********************************************************************
//
private RangeD luminance_m;
//
//**********************************************************************
/// <summary>
/// Adjust Fill Hue
/// </summary>
//**********************************************************************
//
private int fillH_m;
//
//**********************************************************************
/// <summary>
/// Adjust Fill Saturation
/// </summary>
//**********************************************************************
//
private double fillS_m;
//
//**********************************************************************
/// <summary>
/// Adjust Fill Luminance
/// </summary>
//**********************************************************************
//
private double fillL_m;
//
//**********************************************************************
/// <summary>
/// Flag to determine if we fill the outside of the image range
/// </summary>
//**********************************************************************
//
private bool fillOutsideRange_m;
//
//**********************************************************************
/// <summary>
/// Flag to check if we need to update the Hue
/// </summary>
//**********************************************************************
//
private bool updateH_m;
//
//**********************************************************************
/// <summary>
/// Flag to check if we need to update the Saturation
/// </summary>
//**********************************************************************
//
private bool updateS_m;
//
//**********************************************************************
/// <summary>
/// Flag to check if we need to update the Luminance
/// </summary>
//**********************************************************************
//
private bool updateL_m;
#endregion
#region Constructors
//
//**********************************************************************
/// <summary>
/// Initialises a new instance of the <see cref="T:HSLFiltering"/> class.
/// </summary>
//**********************************************************************
//
public HSLFiltering()
{
CommonInitialisation();
}
//
//**********************************************************************
/// <summary>
/// Initialises a new instance of the <see cref="T:HSLFiltering"/> class.
/// </summary>
/// <param name="hue">The hue.</param>
/// <param name="saturation">The saturation.</param>
/// <param name="luminance">The luminance.</param>
//**********************************************************************
//
public HSLFiltering(Range hue, RangeD saturation, RangeD luminance)
{
CommonInitialisation();
this.hue_m = hue;
this.saturation_m = saturation;
this.luminance_m = luminance;
}
#endregion
#region Properties
//
//**********************************************************************
/// <summary>
/// Gets or sets the hue property.
/// </summary>
/// <value>The hue.</value>
//**********************************************************************
//
public Range Hue
{
get
{
return hue_m;
}
set
{
hue_m = value;
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the saturation property.
/// </summary>
/// <value>The saturation.</value>
//**********************************************************************
//
public RangeD Saturation
{
get
{
return saturation_m;
}
set
{
saturation_m = value;
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the luminance property
/// </summary>
/// <value>The luminance.</value>
//**********************************************************************
//
public RangeD Luminance
{
get
{
return luminance_m;
}
set
{
luminance_m = value;
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the color of the fill property.
/// </summary>
/// <value>The color of the fill.</value>
//**********************************************************************
//
public HSL FillColor
{
get
{
return new HSL(fillH_m, fillS_m, fillL_m);
}
set
{
fillH_m = value.Hue;
fillS_m = value.Saturation;
fillL_m = value.Luminance;
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets a value indicating whether [fill outside range] property.
/// </summary>
/// <value><c>true</c> if [fill outside range]; otherwise, <c>false</c>.</value>
//**********************************************************************
//
public bool FillOutsideRange
{
get
{
return fillOutsideRange_m;
}
set
{
fillOutsideRange_m = value;
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets a value indicating whether [update hue] property.
/// </summary>
/// <value><c>true</c> if [update hue]; otherwise, <c>false</c>.</value>
//**********************************************************************
//
public bool UpdateHue
{
get
{
return updateH_m;
}
set
{
updateH_m = value;
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets a value indicating whether [update saturation] property.
/// </summary>
/// <value><c>true</c> if [update saturation]; otherwise, <c>false</c>.</value>
//**********************************************************************
//
public bool UpdateSaturation
{
get
{
return updateS_m;
}
set
{
updateS_m = value;
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets a value indicating whether [update luminance] property.
/// </summary>
/// <value><c>true</c> if [update luminance]; otherwise, <c>false</c>.</value>
//**********************************************************************
//
public bool UpdateLuminance
{
get
{
return updateL_m;
}
set
{
updateL_m = value;
}
}
#endregion
#region Private Methods
/// <summary>
/// Common initialisation for this object.
/// </summary>
private void CommonInitialisation ()
{
hue_m = new Range(0, 359);
saturation_m = new RangeD(0.0, 1.0);
luminance_m = new RangeD(0.0, 1.0);
fillH_m = FillHue_sc;
fillS_m = FillSaturation_sc;
fillL_m = FillLuminance_sc;
fillOutsideRange_m = FillOutsideRange_sc;
updateH_m = true;
updateS_m = true;
updateL_m = true;
}
#endregion
#region Public Methods
//
//**********************************************************************
/// <summary>
/// Apply filter
/// </summary>
/// <param name="srcImg">The SRC img.</param>
/// <returns></returns>
//**********************************************************************
//
public Bitmap Apply(Bitmap srcImg)
{
if (srcImg.PixelFormat != PixelFormat.Format24bppRgb)
throw new ArgumentException();
//
// get source image size
//
int width = srcImg.Width;
int height = srcImg.Height;
//
// lock source bitmap data
//
BitmapData srcData = srcImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
//
// create new image
//
Bitmap dstImg = new Bitmap(width, height, PixelFormat.Format24bppRgb);
//
// lock destination bitmap data
//
BitmapData dstData = dstImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
RGB rgb = new RGB();
HSL hsl = new HSL();
int offset = srcData.Stride - width * 3;
//
// do the job
//
unsafe
{
byte * src = (byte *) srcData.Scan0.ToPointer();
byte * dst = (byte *) dstData.Scan0.ToPointer();
//
// for each row
//
for (int y = 0; y < height; y++)
{
//
// for each pixel
//
for (int x = 0; x < width; x++, src += 3, dst += 3)
{
rgb.Red = src[RGB.R];
rgb.Green = src[RGB.G];
rgb.Blue = src[RGB.B];
//
// convert to HSL
//
Hydra.Framework.ImageProcessing.Analysis.ColorConverter.RGB2HSL(rgb, hsl);
//
// check HSL value
//
if ((hsl.Saturation >= saturation_m.Min) && (hsl.Saturation <= saturation_m.Max) &&
(hsl.Luminance >= luminance_m.Min) && (hsl.Luminance <= luminance_m.Max) &&
(
((hue_m.Min < hue_m.Max) && (hsl.Hue >= hue_m.Min) && (hsl.Hue <= hue_m.Max)) ||
((hue_m.Min > hue_m.Max) && ((hsl.Hue >= hue_m.Min) || (hsl.Hue <= hue_m.Max)))
))
{
if (!fillOutsideRange_m)
{
if (updateH_m) hsl.Hue = fillH_m;
if (updateS_m) hsl.Saturation = fillS_m;
if (updateL_m) hsl.Luminance = fillL_m;
}
}
else
{
if (fillOutsideRange_m)
{
if (updateH_m) hsl.Hue = fillH_m;
if (updateS_m) hsl.Saturation = fillS_m;
if (updateL_m) hsl.Luminance = fillL_m;
}
}
//
// convert back to RGB
//
Hydra.Framework.ImageProcessing.Analysis.ColorConverter.HSL2RGB(hsl, rgb);
dst[RGB.R] = rgb.Red;
dst[RGB.G] = rgb.Green;
dst[RGB.B] = rgb.Blue;
}
src += offset;
dst += offset;
}
}
//
// unlock both images
//
dstImg.UnlockBits(dstData);
srcImg.UnlockBits(srcData);
return dstImg;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 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>
/// PacketCapturesOperations operations.
/// </summary>
internal partial class PacketCapturesOperations : IServiceOperations<NetworkManagementClient>, IPacketCapturesOperations
{
/// <summary>
/// Initializes a new instance of the PacketCapturesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PacketCapturesOperations(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>
/// Create and start a packet capture on the specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='parameters'>
/// Parameters that define the create packet capture 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<PacketCaptureResult>> CreateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<PacketCaptureResult> _response = await BeginCreateWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a packet capture session by name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </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<PacketCaptureResult>> GetWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-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("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
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/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_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<PacketCaptureResult>();
_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<PacketCaptureResult>(_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 packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </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 networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stops a specified packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> StopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginStopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Query the status of a running packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='packetCaptureName'>
/// The name given to the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<PacketCaptureQueryStatusResult>> GetStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse<PacketCaptureQueryStatusResult> _response = await BeginGetStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Lists all packet capture sessions within the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </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<IEnumerable<PacketCaptureResult>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-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("networkWatcherName", networkWatcherName);
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/networkWatchers/{networkWatcherName}/packetCaptures").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_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<IEnumerable<PacketCaptureResult>>();
_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<Page1<PacketCaptureResult>>(_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>
/// Create and start a packet capture on the specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='parameters'>
/// Parameters that define the create packet capture 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<PacketCaptureResult>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-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("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", 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/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_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(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, 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 != 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<PacketCaptureResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureResult>(_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 packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </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 networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-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("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
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/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_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 != 204 && (int)_statusCode != 202)
{
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>
/// Stops a specified packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </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> BeginStopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-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("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginStop", 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/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/stop").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_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("POST");
_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 && (int)_statusCode != 202)
{
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>
/// Query the status of a running packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='packetCaptureName'>
/// The name given to the packet capture session.
/// </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<PacketCaptureQueryStatusResult>> BeginGetStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-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("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginGetStatus", 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/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/queryStatus").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_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("POST");
_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 && (int)_statusCode != 202)
{
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<PacketCaptureQueryStatusResult>();
_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<PacketCaptureQueryStatusResult>(_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 == 202)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureQueryStatusResult>(_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;
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: LineBase.cs
//
// Description: Text line formatter.
//
// History:
// 02/07/2005 : ghermann - Split from Line.cs
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using MS.Internal.Text;
using MS.Internal.Documents;
using MS.Internal.PtsHost.UnsafeNativeMethods;
#pragma warning disable 1634, 1691 // avoid generating warnings about unknown
// message numbers and unknown pragmas for PRESharp contol
namespace MS.Internal.PtsHost
{
internal abstract class LineBase : UnmanagedHandle
{
internal LineBase(BaseParaClient paraClient) : base(paraClient.PtsContext)
{
_paraClient = paraClient;
}
// ------------------------------------------------------------------
//
// TextSource Implementation
//
// ------------------------------------------------------------------
#region TextSource Implementation
/// <summary>
/// Get a text run at specified text source position.
/// </summary>
/// <param name="dcp">
/// dcp of specified position relative to start of line
/// </param>
internal abstract TextRun GetTextRun(int dcp);
/// <summary>
/// Get text immediately before specified text source position.
/// </summary>
/// <param name="dcp">
/// dcp of specified position relative to start of line
/// </param>
internal abstract TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int dcp);
/// <summary>
/// Get Text effect index from text source character index
/// </summary>
/// <param name="dcp">
/// dcp of specified position relative to start of line
/// </param>
internal abstract int GetTextEffectCharacterIndexFromTextSourceCharacterIndex(int dcp);
#endregion TextSource Implementation
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
/// <summary>
/// Fetch the next run at text position.
/// </summary>
/// <param name="position">
/// Current position in text array
/// </param>
/// <returns></returns>
protected TextRun HandleText(StaticTextPointer position)
{
DependencyObject element;
StaticTextPointer endOfRunPosition;
Invariant.Assert(position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text, "TextPointer does not point to characters.");
if (position.Parent != null)
{
element = position.Parent;
}
else
{
element = _paraClient.Paragraph.Element;
}
// Extract the aggregated properties into something that the textrun can use.
//
TextProperties textProps = new TextProperties(element, position, false /* inline objects */, true /* get background */);
// Calculate the end of the run by finding either:
// a) the next intersection of highlight ranges, or
// b) the natural end of this textrun
endOfRunPosition = position.TextContainer.Highlights.GetNextPropertyChangePosition(position, LogicalDirection.Forward);
// Clamp the text run at an arbitrary limit, so we don't make
// an unbounded allocation.
if (position.GetOffsetToPosition(endOfRunPosition) > 4096)
{
endOfRunPosition = position.CreatePointer(4096);
}
// Get character buffer for the text run.
char[] textBuffer = new char[position.GetOffsetToPosition(endOfRunPosition)];
// Copy characters from text run into buffer. Note the actual number of characters copied,
// which may be different than the buffer's length. Buffer length only specifies the maximum
// number of characters
int charactersCopied = position.GetTextInRun(LogicalDirection.Forward, textBuffer, 0, textBuffer.Length);
// Create text run using the actual number of characters copied
return new TextCharacters(textBuffer, 0, charactersCopied, textProps);
}
/// <summary>
/// Return next TextRun at element edge start position
/// </summary>
/// <param name="position">
/// Current position in text array
/// </param>
protected TextRun HandleElementStartEdge(StaticTextPointer position)
{
Invariant.Assert(position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementStart, "TextPointer does not point to element start edge.");
//
TextRun run = null;
TextElement element = (TextElement)position.GetAdjacentElement(LogicalDirection.Forward);
Debug.Assert(element != null, "Cannot use ITextContainer that does not provide TextElement instances.");
Invariant.Assert(!(element is Block), "We do not expect any Blocks inside Paragraphs");
// Treat figure and floaters as special hidden runs.
if (element is Figure || element is Floater)
{
// Get the length of the element
int cch = TextContainerHelper.GetElementLength(_paraClient.Paragraph.StructuralCache.TextContainer, element);
// Create special hidden run.
run = new FloatingRun(cch, element is Figure);
if (element is Figure)
{
_hasFigures = true;
}
else
{
_hasFloaters = true;
}
}
else if (element is LineBreak)
{
int cch = TextContainerHelper.GetElementLength(_paraClient.Paragraph.StructuralCache.TextContainer, element);
run = new LineBreakRun(cch, PTS.FSFLRES.fsflrSoftBreak);
}
else if (element.IsEmpty)
{
// Empty TextElement should affect line metrics.
// TextFormatter does not support this feature right now, so as workaround
// TextRun with ZERO WIDTH SPACE is used.
TextProperties textProps = new TextProperties(element, position, false /* inline objects */, true /* get background */);
char[] textBuffer = new char[_elementEdgeCharacterLength * 2];
// Assert that _elementEdgeCharacterLength is 1 before we use hard-coded indices
Invariant.Assert(_elementEdgeCharacterLength == 1, "Expected value of _elementEdgeCharacterLength is 1");
textBuffer[0] = (char)0x200B;
textBuffer[1] = (char)0x200B;
run = new TextCharacters(textBuffer, 0, textBuffer.Length, textProps);
}
else
{
Inline inline = (Inline) element;
DependencyObject parent = inline.Parent;
FlowDirection inlineFlowDirection = inline.FlowDirection;
FlowDirection parentFlowDirection = inlineFlowDirection;
TextDecorationCollection inlineTextDecorations = DynamicPropertyReader.GetTextDecorations(inline);
if(parent != null)
{
parentFlowDirection = (FlowDirection)parent.GetValue(FrameworkElement.FlowDirectionProperty);
}
if (inlineFlowDirection != parentFlowDirection)
{
// Inline's flow direction is different from its parent. Need to create new TextSpanModifier with flow direction
if (inlineTextDecorations == null || inlineTextDecorations.Count == 0)
{
run = new TextSpanModifier(
_elementEdgeCharacterLength,
null,
null,
inlineFlowDirection
);
}
else
{
run = new TextSpanModifier(
_elementEdgeCharacterLength,
inlineTextDecorations,
inline.Foreground,
inlineFlowDirection
);
}
}
else
{
if (inlineTextDecorations == null || inlineTextDecorations.Count == 0)
{
run = new TextHidden(_elementEdgeCharacterLength);
}
else
{
run = new TextSpanModifier(
_elementEdgeCharacterLength,
inlineTextDecorations,
inline.Foreground
);
}
}
}
return run;
}
/// <summary>
/// Fetch the next run at element end edge position.
/// ElementEndEdge; we can have 2 possibilities:
/// (1) Close edge of element associated with the text paragraph,
/// create synthetic LineBreak run to end the current line.
/// (2) End of inline element, hide CloseEdge character and continue
/// </summary>
/// <param name="position"></param>
/// Position in current text array
protected TextRun HandleElementEndEdge(StaticTextPointer position)
{
Invariant.Assert(position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementEnd, "TextPointer does not point to element end edge.");
TextRun run;
if (position.Parent == _paraClient.Paragraph.Element)
{
// (1) Close edge of element associated with the text paragraph,
// create synthetic LineBreak run to end the current line.
run = new ParagraphBreakRun(_syntheticCharacterLength, PTS.FSFLRES.fsflrEndOfParagraph);
}
else
{
TextElement element = (TextElement)position.GetAdjacentElement(LogicalDirection.Forward);
Debug.Assert(element != null, "Element should be here.");
Inline inline = (Inline) element;
DependencyObject parent = inline.Parent;
FlowDirection parentFlowDirection = inline.FlowDirection;
if(parent != null)
{
parentFlowDirection = (FlowDirection)parent.GetValue(FrameworkElement.FlowDirectionProperty);
}
if (inline.FlowDirection != parentFlowDirection)
{
run = new TextEndOfSegment(_elementEdgeCharacterLength);
}
else
{
TextDecorationCollection textDecorations = DynamicPropertyReader.GetTextDecorations(inline);
if (textDecorations == null || textDecorations.Count == 0)
{
// (2) End of inline element, hide CloseEdge character and continue
run = new TextHidden(_elementEdgeCharacterLength);
}
else
{
run = new TextEndOfSegment(_elementEdgeCharacterLength);
}
}
}
return run;
}
/// <summary>
/// Fetch the next run at embedded object position.
/// </summary>
/// <param name="dcp">
/// Character offset of this run.
/// </param>
/// <param name="position">
/// Current position in the text array.
/// </param>
protected TextRun HandleEmbeddedObject(int dcp, StaticTextPointer position)
{
Invariant.Assert(position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.EmbeddedElement, "TextPointer does not point to embedded object.");
TextRun run = null;
DependencyObject embeddedObject = position.GetAdjacentElement(LogicalDirection.Forward) as DependencyObject;
if (embeddedObject is UIElement)
{
// Extract the aggregated properties into something that the textrun can use.
TextRunProperties textProps = new TextProperties(embeddedObject, position, true /* inline objects */, true /* get background */);
// Create inline object run.
run = new InlineObjectRun(TextContainerHelper.EmbeddedObjectLength, (UIElement)embeddedObject, textProps, _paraClient.Paragraph as TextParagraph);
}
else
{
// If the embedded object is of an unknown type, treat it as hidden content.
run = new TextHidden(TextContainerHelper.EmbeddedObjectLength);
}
return run;
}
#endregion Protected Methods
#region Internal Methods
/// <summary>
/// Synthetic character length.
/// </summary>
internal static int SyntheticCharacterLength
{
get
{
return _syntheticCharacterLength;
}
}
/// <summary>
/// Returns true if any figure runs have been handled by this text source - Only valid after line is formatted.
/// </summary>
internal bool HasFigures
{
get { return _hasFigures; }
}
/// <summary>
/// Returns true if any floater runs have been handled by this text source - Only valid after line is formatted.
/// </summary>
internal bool HasFloaters
{
get { return _hasFloaters; }
}
#endregion Internal Methods
#region Protected Fields
/// <summary>
/// Owner of the line
/// </summary>
protected readonly BaseParaClient _paraClient;
/// <summary>
/// Has any figures?
/// </summary>
protected bool _hasFigures;
/// <summary>
/// Has any floaters?
/// </summary>
protected bool _hasFloaters;
protected static int _syntheticCharacterLength = 1;
/// <summary>
/// Element edge character length.
///
protected static int _elementEdgeCharacterLength = 1;
#endregion Protected Fields
}
}
#pragma warning enable 1634, 1691
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Redis;
using Microsoft.Azure.Management.Redis.Models;
using Microsoft.WindowsAzure;
namespace Microsoft.Azure.Management.Redis
{
/// <summary>
/// .Net client wrapper for the REST API for Azure Redis Cache Management
/// Service
/// </summary>
public static partial class RedisOperationsExtensions
{
/// <summary>
/// Create a redis cache, or replace (overwrite/recreate, with
/// potential downtime) an existing cache
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate redis operation.
/// </param>
/// <returns>
/// The response of CreateOrUpdate redis operation.
/// </returns>
public static RedisCreateOrUpdateResponse CreateOrUpdate(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).CreateOrUpdateAsync(resourceGroupName, name, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a redis cache, or replace (overwrite/recreate, with
/// potential downtime) an existing cache
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate redis operation.
/// </param>
/// <returns>
/// The response of CreateOrUpdate redis operation.
/// </returns>
public static Task<RedisCreateOrUpdateResponse> CreateOrUpdateAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, name, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes a redis cache. This operation takes a while to complete.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Delete(this IRedisOperations operations, string resourceGroupName, string name)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).DeleteAsync(resourceGroupName, name);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a redis cache. This operation takes a while to complete.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> DeleteAsync(this IRedisOperations operations, string resourceGroupName, string name)
{
return operations.DeleteAsync(resourceGroupName, name, CancellationToken.None);
}
/// <summary>
/// Gets a redis cache (resource description).
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// The response of GET redis operation.
/// </returns>
public static RedisGetResponse Get(this IRedisOperations operations, string resourceGroupName, string name)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).GetAsync(resourceGroupName, name);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a redis cache (resource description).
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// The response of GET redis operation.
/// </returns>
public static Task<RedisGetResponse> GetAsync(this IRedisOperations operations, string resourceGroupName, string name)
{
return operations.GetAsync(resourceGroupName, name, CancellationToken.None);
}
/// <summary>
/// Gets all redis caches in a resource group (if provided) otherwise
/// all in subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Optional. The name of the resource group.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public static RedisListResponse List(this IRedisOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).ListAsync(resourceGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all redis caches in a resource group (if provided) otherwise
/// all in subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Optional. The name of the resource group.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public static Task<RedisListResponse> ListAsync(this IRedisOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName, CancellationToken.None);
}
/// <summary>
/// Retrieve a redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// The response of redis list keys operation.
/// </returns>
public static RedisListKeysResponse ListKeys(this IRedisOperations operations, string resourceGroupName, string name)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).ListKeysAsync(resourceGroupName, name);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <returns>
/// The response of redis list keys operation.
/// </returns>
public static Task<RedisListKeysResponse> ListKeysAsync(this IRedisOperations operations, string resourceGroupName, string name)
{
return operations.ListKeysAsync(resourceGroupName, name, CancellationToken.None);
}
/// <summary>
/// Gets all redis caches using next link.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public static RedisListResponse ListNext(this IRedisOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all redis caches using next link.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public static Task<RedisListResponse> ListNextAsync(this IRedisOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Regenerate redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Specifies which key to reset.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse RegenerateKey(this IRedisOperations operations, string resourceGroupName, string name, RedisRegenerateKeyParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRedisOperations)s).RegenerateKeyAsync(resourceGroupName, name, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerate redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='operations'>
/// Reference to the Microsoft.Azure.Management.Redis.IRedisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Specifies which key to reset.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> RegenerateKeyAsync(this IRedisOperations operations, string resourceGroupName, string name, RedisRegenerateKeyParameters parameters)
{
return operations.RegenerateKeyAsync(resourceGroupName, name, parameters, CancellationToken.None);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if PARALLEL
using System;
using System.Collections.Generic;
using System.Threading;
namespace NUnit.Framework.Internal.Execution
{
/// <summary>
/// The dispatcher needs to do different things at different,
/// non-overlapped times. For example, non-parallel tests may
/// not be run at the same time as parallel tests. We model
/// this using the metaphor of a working shift. The WorkShift
/// class associates one or more WorkItemQueues with one or
/// more TestWorkers.
///
/// Work in the queues is processed until all queues are empty
/// and all workers are idle. Both tests are needed because a
/// worker that is busy may end up adding more work to one of
/// the queues. At that point, the shift is over and another
/// shift may begin. This cycle continues until all the tests
/// have been run.
/// </summary>
public class WorkShift
{
private static Logger log = InternalTrace.GetLogger("WorkShift");
private object _syncRoot = new object();
private int _busyCount = 0;
// Shift name - used for logging
private string _name;
/// <summary>
/// Construct a WorkShift
/// </summary>
public WorkShift(string name)
{
_name = name;
this.IsActive = false;
this.Queues = new List<WorkItemQueue>();
this.Workers = new List<TestWorker>();
}
#region Public Events and Properties
/// <summary>
/// Event that fires when the shift has ended
/// </summary>
public event EventHandler EndOfShift;
/// <summary>
/// Gets a flag indicating whether the shift is currently active
/// </summary>
public bool IsActive { get; private set; }
/// <summary>
/// Gets a list of the queues associated with this shift.
/// </summary>
/// <remarks>Used for testing</remarks>
public IList<WorkItemQueue> Queues { get; private set; }
/// <summary>
/// Gets the list of workers associated with this shift.
/// </summary>
public IList<TestWorker> Workers { get; private set; }
/// <summary>
/// Gets a bool indicating whether this shift has any work to do
/// </summary>
public bool HasWork
{
get
{
foreach (var q in Queues)
if (!q.IsEmpty)
return true;
return false;
}
}
#endregion
#region Public Methods
/// <summary>
/// Add a WorkItemQueue to the shift, starting it if the
/// shift is currently active.
/// </summary>
public void AddQueue(WorkItemQueue queue)
{
log.Debug("{0} shift adding queue {1}", _name, queue.Name);
Queues.Add(queue);
if (this.IsActive)
queue.Start();
}
/// <summary>
/// Assign a worker to the shift.
/// </summary>
/// <param name="worker"></param>
public void Assign(TestWorker worker)
{
log.Debug("{0} shift assigned worker {1}", _name, worker.Name);
Workers.Add(worker);
worker.Busy += (s, ea) => Interlocked.Increment(ref _busyCount);
worker.Idle += (s, ea) =>
{
// Quick check first using Interlocked.Decrement
if (Interlocked.Decrement(ref _busyCount) == 0)
lock (_syncRoot)
{
// Check busy count again under the lock
if (_busyCount == 0 && !HasWork)
this.EndShift();
}
};
worker.Start();
}
/// <summary>
/// Start or restart processing for the shift
/// </summary>
public void Start()
{
log.Info("{0} shift starting", _name);
this.IsActive = true;
foreach (var q in Queues)
q.Start();
}
/// <summary>
/// End the shift, pausing all queues and raising
/// the EndOfShift event.
/// </summary>
public void EndShift()
{
log.Info("{0} shift ending", _name);
this.IsActive = false;
// Pause all queues
foreach (var q in Queues)
q.Pause();
// Signal the dispatcher that shift ended
if (EndOfShift != null)
EndOfShift(this, EventArgs.Empty);
}
/// <summary>
/// Shut down the shift.
/// </summary>
public void ShutDown()
{
this.IsActive = false;
foreach (var q in Queues)
q.Stop();
}
/// <summary>
/// Cancel (abort or stop) the shift without completing all work
/// </summary>
/// <param name="force">true if the WorkShift should be aborted, false if it should allow its currently running tests to complete</param>
public void Cancel(bool force)
{
if (force)
this.IsActive = false;
foreach (var w in Workers)
w.Cancel(force);
}
#endregion
}
}
#endif
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using System;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using Leap.Unity.Space;
using Leap.Unity.Query;
using Leap.Unity.Attributes;
namespace Leap.Unity.GraphicalRenderer {
[LeapGraphicTag("Text")]
[Serializable]
public class LeapTextRenderer : LeapRenderingMethod<LeapTextGraphic>, ISupportsAddRemove {
public const string DEFAULT_FONT = "Arial.ttf";
public const string DEFAULT_SHADER = "LeapMotion/GraphicRenderer/Text/Dynamic";
public const float SCALE_CONSTANT = 0.001f;
[EditTimeOnly, SerializeField]
private Font _font;
[EditTimeOnly, SerializeField]
private float _dynamicPixelsPerUnit = 1.0f;
[EditTimeOnly, SerializeField]
public bool _useColor = true;
[EditTimeOnly, SerializeField]
public Color _globalTint = Color.white;
[Header("Rendering Settings")]
[EditTimeOnly, SerializeField]
private Shader _shader;
[EditTimeOnly, SerializeField]
private float _scale = 1f;
[SerializeField]
private RendererMeshData _meshData;
[SerializeField]
private Material _material;
//Curved space
private const string CURVED_PARAMETERS = LeapGraphicRenderer.PROPERTY_PREFIX + "Curved_GraphicParameters";
private List<Matrix4x4> _curved_worldToAnchor = new List<Matrix4x4>();
private List<Matrix4x4> _curved_meshTransforms = new List<Matrix4x4>();
private List<Vector4> _curved_graphicParameters = new List<Vector4>();
public override SupportInfo GetSpaceSupportInfo(LeapSpace space) {
return SupportInfo.FullSupport();
}
public void OnAddRemoveGraphics(List<int> dirtyIndexes) {
while(_meshData.Count > group.graphics.Count) {
_meshData.RemoveMesh(_meshData.Count - 1);
}
while(_meshData.Count < group.graphics.Count) {
group.graphics[_meshData.Count].isRepresentationDirty = true;
_meshData.AddMesh(new Mesh());
}
}
public override void OnEnableRenderer() {
foreach (var graphic in group.graphics) {
var textGraphic = graphic as LeapTextGraphic;
_font.RequestCharactersInTexture(textGraphic.text);
}
generateMaterial();
Font.textureRebuilt += onFontTextureRebuild;
}
public override void OnDisableRenderer() {
Font.textureRebuilt -= onFontTextureRebuild;
}
public override void OnUpdateRenderer() {
ensureFontIsUpToDate();
for (int i = 0; i < group.graphics.Count; i++) {
var graphic = group.graphics[i] as LeapTextGraphic;
if (graphic.isRepresentationDirtyOrEditTime || graphic.HasRectChanged()) {
generateTextMesh(i, graphic, _meshData[i]);
}
}
if (renderer.space == null) {
using (new ProfilerSample("Draw Meshes")) {
for (int i = 0; i < group.graphics.Count; i++) {
var graphic = group.graphics[i];
Graphics.DrawMesh(_meshData[i], graphic.transform.localToWorldMatrix, _material, 0);
}
}
} else if (renderer.space is LeapRadialSpace) {
var curvedSpace = renderer.space as LeapRadialSpace;
using (new ProfilerSample("Build Material Data")) {
_curved_worldToAnchor.Clear();
_curved_meshTransforms.Clear();
_curved_graphicParameters.Clear();
for (int i = 0; i < _meshData.Count; i++) {
var graphic = group.graphics[i];
var transformer = graphic.anchor.transformer;
Vector3 localPos = renderer.transform.InverseTransformPoint(graphic.transform.position);
Matrix4x4 mainTransform = renderer.transform.localToWorldMatrix * transformer.GetTransformationMatrix(localPos);
Matrix4x4 deform = renderer.transform.worldToLocalMatrix * Matrix4x4.TRS(renderer.transform.position - graphic.transform.position, Quaternion.identity, Vector3.one) * graphic.transform.localToWorldMatrix;
Matrix4x4 total = mainTransform * deform;
_curved_graphicParameters.Add((transformer as IRadialTransformer).GetVectorRepresentation(graphic.transform));
_curved_meshTransforms.Add(total);
_curved_worldToAnchor.Add(mainTransform.inverse);
}
}
using (new ProfilerSample("Upload Material Data")) {
_material.SetFloat(SpaceProperties.RADIAL_SPACE_RADIUS, curvedSpace.radius);
_material.SetMatrixArraySafe("_GraphicRendererCurved_WorldToAnchor", _curved_worldToAnchor);
_material.SetMatrix("_GraphicRenderer_LocalToWorld", renderer.transform.localToWorldMatrix);
_material.SetVectorArraySafe("_GraphicRendererCurved_GraphicParameters", _curved_graphicParameters);
}
using (new ProfilerSample("Draw Meshes")) {
for (int i = 0; i < _meshData.Count; i++) {
Graphics.DrawMesh(_meshData[i], _curved_meshTransforms[i], _material, 0);
}
}
}
}
#if UNITY_EDITOR
public override void OnEnableRendererEditor() {
base.OnEnableRendererEditor();
_font = Resources.GetBuiltinResource<Font>(DEFAULT_FONT);
_shader = Shader.Find(DEFAULT_SHADER);
}
public override void OnUpdateRendererEditor() {
base.OnUpdateRendererEditor();
if (_font == null) {
_font = Resources.GetBuiltinResource<Font>(DEFAULT_FONT);
}
if (_shader == null) {
_shader = Shader.Find(DEFAULT_SHADER);
}
_meshData.Validate(this);
//Make sure we have enough meshes to render all our graphics
while (_meshData.Count > group.graphics.Count) {
UnityEngine.Object.DestroyImmediate(_meshData[_meshData.Count - 1]);
_meshData.RemoveMesh(_meshData.Count - 1);
}
while (_meshData.Count < group.graphics.Count) {
_meshData.AddMesh(new Mesh());
}
generateMaterial();
PreventDuplication(ref _material);
}
#endif
private void onFontTextureRebuild(Font font) {
if (font != _font) {
return;
}
foreach (var graphic in group.graphics) {
graphic.isRepresentationDirty = true;
}
}
private void generateMaterial() {
if (_material == null) {
_material = new Material(_font.material);
}
#if UNITY_EDITOR
Undo.RecordObject(_material, "Touched material");
#endif
_material.mainTexture = _font.material.mainTexture;
_material.name = "Font material";
_material.shader = _shader;
foreach (var keyword in _material.shaderKeywords) {
_material.DisableKeyword(keyword);
}
if (renderer.space != null) {
if (renderer.space is LeapCylindricalSpace) {
_material.EnableKeyword(SpaceProperties.CYLINDRICAL_FEATURE);
} else if (renderer.space is LeapSphericalSpace) {
_material.EnableKeyword(SpaceProperties.SPHERICAL_FEATURE);
}
}
if (_useColor) {
_material.EnableKeyword(LeapGraphicRenderer.FEATURE_PREFIX + "VERTEX_COLORS");
}
}
private void ensureFontIsUpToDate() {
CharacterInfo info;
bool doesNeedRebuild = false;
for (int i = 0; i < group.graphics.Count; i++) {
var graphic = group.graphics[i] as LeapTextGraphic;
int scaledFontSize = Mathf.RoundToInt(graphic.fontSize * _dynamicPixelsPerUnit);
if (graphic.isRepresentationDirtyOrEditTime) {
for (int j = 0; j < graphic.text.Length; j++) {
char character = graphic.text[j];
if (!_font.GetCharacterInfo(character, out info, scaledFontSize, graphic.fontStyle)) {
doesNeedRebuild = true;
break;
}
}
if (doesNeedRebuild) {
break;
}
}
}
if (!doesNeedRebuild) {
return;
}
for (int i = 0; i < group.graphics.Count; i++) {
var graphic = group.graphics[i] as LeapTextGraphic;
int scaledFontSize = Mathf.RoundToInt(graphic.fontSize * _dynamicPixelsPerUnit);
graphic.isRepresentationDirty = true;
_font.RequestCharactersInTexture(graphic.text,
scaledFontSize,
graphic.fontStyle);
}
}
private List<TextWrapper.Line> _tempLines = new List<TextWrapper.Line>();
private List<Vector3> _verts = new List<Vector3>();
private List<Vector4> _uvs = new List<Vector4>();
private List<Color> _colors = new List<Color>();
private List<int> _tris = new List<int>();
private void generateTextMesh(int index, LeapTextGraphic graphic, Mesh mesh) {
using (new ProfilerSample("Generate Text Mesh")) {
mesh.Clear();
graphic.isRepresentationDirty = false;
int scaledFontSize = Mathf.RoundToInt(graphic.fontSize * _dynamicPixelsPerUnit);
//Check for characters not found in the font
{
HashSet<char> unfoundCharacters = null;
CharacterInfo info;
foreach (var character in graphic.text) {
if (character == '\n') {
continue;
}
if (unfoundCharacters != null && unfoundCharacters.Contains(character)) {
continue;
}
if (!_font.GetCharacterInfo(character, out info, scaledFontSize, graphic.fontStyle)) {
if (unfoundCharacters == null) unfoundCharacters = new HashSet<char>();
unfoundCharacters.Add(character);
Debug.LogError("Could not find character [" + character + "] in font " + _font + "!");
}
}
}
var textGraphic = graphic as LeapTextGraphic;
var text = textGraphic.text;
float _charScale = this._scale * SCALE_CONSTANT / _dynamicPixelsPerUnit;
float _scale = _charScale * graphic.fontSize / _font.fontSize;
float lineHeight = _scale * textGraphic.lineSpacing * _font.lineHeight * _dynamicPixelsPerUnit;
RectTransform rectTransform = textGraphic.transform as RectTransform;
float maxWidth;
if (rectTransform != null) {
maxWidth = rectTransform.rect.width;
} else {
maxWidth = float.MaxValue;
}
_widthCalculator.font = _font;
_widthCalculator.charScale = _charScale;
_widthCalculator.fontStyle = graphic.fontStyle;
_widthCalculator.scaledFontSize = scaledFontSize;
TextWrapper.Wrap(text, textGraphic.tokens, _tempLines, _widthCalculator.func, maxWidth);
float textHeight = _tempLines.Count * lineHeight;
Vector3 origin = Vector3.zero;
origin.y -= _font.ascent * _scale * _dynamicPixelsPerUnit;
if (rectTransform != null) {
origin.y -= rectTransform.rect.y;
switch (textGraphic.verticalAlignment) {
case LeapTextGraphic.VerticalAlignment.Center:
origin.y -= (rectTransform.rect.height - textHeight) / 2;
break;
case LeapTextGraphic.VerticalAlignment.Bottom:
origin.y -= (rectTransform.rect.height - textHeight);
break;
}
}
foreach (var line in _tempLines) {
if (rectTransform != null) {
origin.x = rectTransform.rect.x;
switch (textGraphic.horizontalAlignment) {
case LeapTextGraphic.HorizontalAlignment.Center:
origin.x += (rectTransform.rect.width - line.width) / 2;
break;
case LeapTextGraphic.HorizontalAlignment.Right:
origin.x += (rectTransform.rect.width - line.width);
break;
}
} else {
switch (textGraphic.horizontalAlignment) {
case LeapTextGraphic.HorizontalAlignment.Left:
origin.x = 0;
break;
case LeapTextGraphic.HorizontalAlignment.Center:
origin.x = -line.width / 2;
break;
case LeapTextGraphic.HorizontalAlignment.Right:
origin.x = -line.width;
break;
}
}
for (int i = line.start; i < line.end; i++) {
char c = text[i];
CharacterInfo info;
if (!_font.GetCharacterInfo(c, out info, scaledFontSize, graphic.fontStyle)) {
continue;
}
int offset = _verts.Count;
_tris.Add(offset + 0);
_tris.Add(offset + 1);
_tris.Add(offset + 2);
_tris.Add(offset + 0);
_tris.Add(offset + 2);
_tris.Add(offset + 3);
_verts.Add(_charScale * new Vector3(info.minX, info.maxY, 0) + origin);
_verts.Add(_charScale * new Vector3(info.maxX, info.maxY, 0) + origin);
_verts.Add(_charScale * new Vector3(info.maxX, info.minY, 0) + origin);
_verts.Add(_charScale * new Vector3(info.minX, info.minY, 0) + origin);
_uvs.Add(info.uvTopLeft);
_uvs.Add(info.uvTopRight);
_uvs.Add(info.uvBottomRight);
_uvs.Add(info.uvBottomLeft);
if (_useColor) {
_colors.Append(4, _globalTint * graphic.color);
}
origin.x += info.advance * _charScale;
}
origin.y -= lineHeight;
}
for (int i = 0; i < _uvs.Count; i++) {
Vector4 uv = _uvs[i];
uv.w = index;
_uvs[i] = uv;
}
mesh.SetVertices(_verts);
mesh.SetTriangles(_tris, 0);
mesh.SetUVs(0, _uvs);
if (_useColor) {
mesh.SetColors(_colors);
}
_verts.Clear();
_uvs.Clear();
_tris.Clear();
_colors.Clear();
_tempLines.Clear();
}
}
private CharWidthCalculator _widthCalculator = new CharWidthCalculator();
private class CharWidthCalculator {
public Font font;
public int scaledFontSize;
public FontStyle fontStyle;
public float charScale;
public Func<char, float> func;
public CharWidthCalculator() {
func = funcMethod;
}
private float funcMethod(char c) {
CharacterInfo info;
font.GetCharacterInfo(c, out info, scaledFontSize, fontStyle);
return info.advance * charScale;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ELGManager : MonoBehaviour {
// DELEGATE
public delegate void onGestureRecognised(EasyLeapGesture gesture);
public static event onGestureRecognised GestureRecognised;
private Leap.Controller leapController;
private Leap.Frame mFrame;
private Dictionary<int,EasyLeapGesture> gestureList = new Dictionary<int, EasyLeapGesture>();
public static bool circleGestureRegistered = true;
public static bool swipeGestureRegistered = true;
public static bool keytapGestureRegistered = true;
public static bool screentapGestureRegistered = true;
public static bool numbersGestureRegistered = true;
public static bool closeFistRegistered = true;
public static bool openFistRegistered = true;
public static bool pushGestureRegistered = true;
public static bool pullGestureRegistered = true;
public static bool doubleInwardsSwipeGestureRegistered = true;
public static bool doubleOutwardsSwipeGestureRegistered = true;
public static bool clapGestureRegistered = true;
public static bool twoFingerKeytapRegistered = true;
public static bool threeFingerKeytapRegistered = true;
public static bool twoFingerScreentapRegistered = true;
public static bool threeFingerScreentapRegistered = true;
public static bool steeringWheelRegistered = true;
private float pushRestTime = 0f;
private float pullRestTime = 0f;
private float doubleInSwipeRestTime = 0f;
private float doubleOutSwipeRestTime = 0f;
private float clapRestTime = 0f;
// Use this for initialization
void Start () {
leapController = new Leap.Controller();
leapController.EnableGesture(Leap.Gesture.GestureType.TYPECIRCLE,true);
leapController.EnableGesture(Leap.Gesture.GestureType.TYPESWIPE,true);
leapController.EnableGesture(Leap.Gesture.GestureType.TYPEKEYTAP,true);
leapController.EnableGesture(Leap.Gesture.GestureType.TYPESCREENTAP,true);
}
// Update is called once per frame
void Update () {
mFrame = leapController.Frame ();
int fingerCount = 0;
if(numbersGestureRegistered || closeFistRegistered || openFistRegistered ||
keytapGestureRegistered || twoFingerKeytapRegistered || threeFingerKeytapRegistered ||
screentapGestureRegistered || twoFingerScreentapRegistered || threeFingerScreentapRegistered || steeringWheelRegistered)
fingerCount = GetFingerCount();
foreach(Leap.Gesture gesture in mFrame.Gestures ()) {
switch(gesture.Type) {
case Leap.Gesture.GestureType.TYPECIRCLE:
if(circleGestureRegistered) BuiltInGestureRecognised(gesture,EasyLeapGestureType.TYPECIRCLE);
break;
case Leap.Gesture.GestureType.TYPESWIPE:
if(swipeGestureRegistered) BuiltInGestureRecognised(gesture,EasyLeapGestureType.TYPESWIPE);
break;
case Leap.Gesture.GestureType.TYPEKEYTAP:
if(keytapGestureRegistered && fingerCount == 1) BuiltInGestureRecognised(gesture,EasyLeapGestureType.TYPEKEYTAP);
if(twoFingerKeytapRegistered && fingerCount == 2) BuiltInImprovedGestureRecognised(gesture,EasyLeapGestureType.TWO_FINGERS_KEYTAP);
if(threeFingerKeytapRegistered && fingerCount == 3) BuiltInImprovedGestureRecognised(gesture,EasyLeapGestureType.THREE_FINGERS_KEYTAP);
break;
case Leap.Gesture.GestureType.TYPESCREENTAP:
if(screentapGestureRegistered && fingerCount == 1) BuiltInGestureRecognised(gesture,EasyLeapGestureType.TYPESCREENTAP);
if(twoFingerScreentapRegistered && fingerCount == 2) BuiltInImprovedGestureRecognised(gesture,EasyLeapGestureType.TWO_FINGERS_SCREENTAP);
if(threeFingerScreentapRegistered && fingerCount == 3) BuiltInImprovedGestureRecognised(gesture,EasyLeapGestureType.THREE_FINGERS_SCREENTAP);
break;
}
}
if(mFrame.Gestures ().Count == 0) ClearDraggingGestures();
if(numbersGestureRegistered || closeFistRegistered || openFistRegistered) {
switch(fingerCount) {
case 0:
// NO FINGERS
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.DEFAULT);
if(closeFistRegistered) {
if(mFrame.Hands.Count == 1) {
if(PalmIsHorizontal(mFrame.Hands[0])) CloseFistGestureRecognised(EasyLeapGestureState.STATESTOP);
}
else CloseFistGestureRecognised(EasyLeapGestureState.STATEINVALID);
}
if(openFistRegistered) {
if(mFrame.Hands.Count == 1) {
if(PalmIsHorizontal(mFrame.Hands[0])) OpenFistGestureRecognised(EasyLeapGestureState.STATESTART);
}
else OpenFistGestureRecognised(EasyLeapGestureState.STATEINVALID);
}
break;
case 1:
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.ONE);
break;
case 2:
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.TWO);
break;
case 3:
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.THREE);
break;
case 4:
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.FOUR);
break;
case 5:
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.FIVE);
if(closeFistRegistered && mFrame.Hands.Count == 1) CloseFistGestureRecognised(EasyLeapGestureState.STATESTART);
if(openFistRegistered) OpenFistGestureRecognised(EasyLeapGestureState.STATESTOP);
break;
case 6:
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.SIX);
break;
case 7:
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.SEVEN);
break;
case 8:
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.EIGHT);
break;
case 9:
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.NINE);
break;
case 10:
if(numbersGestureRegistered) NumbersGestureRecognised(EasyLeapGestureType.TEN);
break;
}
}
if(pushGestureRegistered || pullGestureRegistered) {
if(mFrame.Hands.Count == 1) {
if(pushGestureRegistered) {
if(mFrame.Hands[0].PalmVelocity.y < -EasyLeapGesture.MinPushPullVelocity) PushGestureRecognised(EasyLeapGestureState.STATESTART);
else PushGestureRecognised(EasyLeapGestureState.STATEINVALID);
}
if(pullGestureRegistered) {
if(mFrame.Hands[0].PalmVelocity.y > EasyLeapGesture.MinPushPullVelocity) PullGestureRecognised(EasyLeapGestureState.STATESTART);
else PullGestureRecognised(EasyLeapGestureState.STATEINVALID);
}
} else {
PushGestureRecognised(EasyLeapGestureState.STATEINVALID);
PullGestureRecognised(EasyLeapGestureState.STATEINVALID);
}
}
if(doubleInwardsSwipeGestureRegistered || doubleOutwardsSwipeGestureRegistered) {
if(mFrame.Hands.Count == 2) {
bool leftHandSwipeIn = (PalmIsHorizontal(mFrame.Hands.Leftmost)) && mFrame.Hands.Leftmost.PalmVelocity.x > EasyLeapGesture.MinSwipeVelocity;
bool rightHandSwipeIn = (PalmIsHorizontal(mFrame.Hands.Rightmost)) && mFrame.Hands.Rightmost.PalmVelocity.x < -EasyLeapGesture.MinSwipeVelocity;
if(doubleInwardsSwipeGestureRegistered && (leftHandSwipeIn && rightHandSwipeIn)) {
if(mFrame.Hands[0].StabilizedPalmPosition.DistanceTo(mFrame.Hands[1].StabilizedPalmPosition) < EasyLeapGesture.MaxPalmDistance) DoubleInwardsSwipeRecognised(EasyLeapGestureState.STATESTART);
} else DoubleInwardsSwipeRecognised(EasyLeapGestureState.STATEINVALID);
bool leftHandSwipeOut = (PalmIsHorizontal(mFrame.Hands.Leftmost)) && mFrame.Hands.Leftmost.PalmVelocity.x < -EasyLeapGesture.MinSwipeVelocity;
bool rightHandSwipeOut = (PalmIsHorizontal(mFrame.Hands.Rightmost)) && mFrame.Hands.Rightmost.PalmVelocity.x > EasyLeapGesture.MinSwipeVelocity;
if(doubleOutwardsSwipeGestureRegistered && leftHandSwipeOut && rightHandSwipeOut) {
if(mFrame.Hands[0].StabilizedPalmPosition.DistanceTo(mFrame.Hands[1].StabilizedPalmPosition) > EasyLeapGesture.MaxPalmDistance) DoubleOutwardsSwipeRecognised(EasyLeapGestureState.STATESTART);
} else DoubleOutwardsSwipeRecognised(EasyLeapGestureState.STATEINVALID);
}
}
if(clapGestureRegistered) {
if(mFrame.Hands.Count == 2) {
bool leftHandSwipeIn = (!PalmIsHorizontal(mFrame.Hands.Leftmost)) && mFrame.Hands.Leftmost.PalmVelocity.x > EasyLeapGesture.MinClapVelocity;
bool rightHandSwipeIn = (!PalmIsHorizontal(mFrame.Hands.Rightmost)) && mFrame.Hands.Rightmost.PalmVelocity.x < -EasyLeapGesture.MinClapVelocity;
if(leftHandSwipeIn && rightHandSwipeIn) {
if(mFrame.Hands[0].StabilizedPalmPosition.DistanceTo(mFrame.Hands[1].StabilizedPalmPosition) < EasyLeapGesture.MaxPalmClapDistance) ClapRecognised(EasyLeapGestureState.STATESTART);
} else ClapRecognised(EasyLeapGestureState.STATEINVALID);
}
}
if(steeringWheelRegistered) {
float palmsAngle = (mFrame.Hands.Leftmost.PalmNormal.AngleTo(mFrame.Hands.Rightmost.PalmNormal)*Mathf.Rad2Deg);
if(mFrame.Hands.Count >= 1 && fingerCount < 2 && (palmsAngle > 110 || palmsAngle < 70)) {
Leap.Vector leftMost = mFrame.Hands.Leftmost.StabilizedPalmPosition;
Leap.Vector rightMost = mFrame.Hands.Rightmost.StabilizedPalmPosition;
Leap.Vector steerVector = (leftMost - rightMost).Normalized;
//steerVector.z = 0;
float angle = steerVector.AngleTo(Leap.Vector.Left)*Mathf.Rad2Deg * (leftMost.y > rightMost.y ? 1 : -1);
SteeringWheelRecognised(angle, Mathf.Abs (leftMost.z) - Mathf.Abs (rightMost.z));
}
}
// Send gestures detected to all registered gesture listeners
SendGesturesToListeners();
}
// BUGGY: clear any gestures that have not been removed properly from the list -- to improve
private void ClearDraggingGestures() {
if(gestureList.Count == 0) return;
var keys = new List<int>(gestureList.Keys);
foreach(int cKey in keys) {
if(gestureList[cKey].Type == EasyLeapGestureType.TYPECIRCLE || gestureList[cKey].Type == EasyLeapGestureType.TYPESWIPE) {
EasyLeapGesture g = gestureList[cKey];
g.State = EasyLeapGestureState.STATESTOP;
gestureList[cKey] = g;
}
}
}
// Store the recognised gesture on the gesture List
private void RecordNewGesture(int id, EasyLeapGestureState startState, EasyLeapGestureState updateState, EasyLeapGestureType type, long duration, Leap.Vector position) {
if(gestureList.ContainsKey(id)) {
EasyLeapGesture g = gestureList[id];
g.State = updateState;
g.Duration = duration < 0 ? (long)(1000000*Time.deltaTime)+g.Duration : duration;
gestureList[id] = g;
} else {
EasyLeapGesture gest = new EasyLeapGesture();
gest.Duration = 0;
gest.Id = id;
gest.State = startState;
gest.Type = type;
gest.Frame = mFrame;
gest.Position = position;
gestureList.Add(id,gest);
}
}
// Individual gesture start-stop handler
private void SteeringWheelRecognised(float angle, float zDepth) {
RecordNewGesture(-(int)EasyLeapGestureType.STEERING_WHEEL,EasyLeapGestureState.STATESTOP,EasyLeapGestureState.STATESTOP,EasyLeapGestureType.STEERING_WHEEL,0,new Leap.Vector(angle,angle,zDepth));
}
private void ClapRecognised(EasyLeapGestureState state) {
if(state == EasyLeapGestureState.STATEINVALID || Time.time < clapRestTime + EasyLeapGesture.ClapRecoveryTime) {
gestureList.Remove(-(int)EasyLeapGestureType.CLAP);
return;
}
clapRestTime = Time.time;
RecordNewGesture(-(int)EasyLeapGestureType.CLAP,EasyLeapGestureState.STATESTART,EasyLeapGestureState.STATEUPDATE,EasyLeapGestureType.CLAP,-1,new Leap.Vector(mFrame.Hands[0].StabilizedPalmPosition.x + mFrame.Hands[1].StabilizedPalmPosition.x,mFrame.Hands[0].StabilizedPalmPosition.y,mFrame.Hands[0].StabilizedPalmPosition.z));
}
private void DoubleInwardsSwipeRecognised(EasyLeapGestureState state) {
if(state == EasyLeapGestureState.STATEINVALID || Time.time < doubleInSwipeRestTime + EasyLeapGesture.DoubleInwardsRecoveryTime) {
gestureList.Remove(-(int)EasyLeapGestureType.DOUBLE_SWIPE_IN);
return;
}
doubleInSwipeRestTime = Time.time;
RecordNewGesture(-(int)EasyLeapGestureType.DOUBLE_SWIPE_IN,EasyLeapGestureState.STATESTART,EasyLeapGestureState.STATEUPDATE,EasyLeapGestureType.DOUBLE_SWIPE_IN,-1,new Leap.Vector(mFrame.Hands[0].StabilizedPalmPosition.x + mFrame.Hands[1].StabilizedPalmPosition.x,mFrame.Hands[0].StabilizedPalmPosition.y,mFrame.Hands[0].StabilizedPalmPosition.z));
}
private void DoubleOutwardsSwipeRecognised(EasyLeapGestureState state) {
if(state == EasyLeapGestureState.STATEINVALID || Time.time < doubleOutSwipeRestTime + EasyLeapGesture.DoubleOutwardsRecoveryTime) {
gestureList.Remove(-(int)EasyLeapGestureType.DOUBLE_SWIPE_OUT);
return;
}
doubleOutSwipeRestTime = Time.time;
RecordNewGesture(-(int)EasyLeapGestureType.DOUBLE_SWIPE_OUT,EasyLeapGestureState.STATESTART,EasyLeapGestureState.STATEUPDATE,EasyLeapGestureType.DOUBLE_SWIPE_OUT,-1,new Leap.Vector(mFrame.Hands[0].StabilizedPalmPosition.x + mFrame.Hands[1].StabilizedPalmPosition.x,mFrame.Hands[0].StabilizedPalmPosition.y,mFrame.Hands[0].StabilizedPalmPosition.z));
}
private void PushGestureRecognised(EasyLeapGestureState state) {
if(state == EasyLeapGestureState.STATEINVALID || Time.time < pushRestTime + EasyLeapGesture.PushRecoveryTime) {
gestureList.Remove(-(int)EasyLeapGestureType.PUSH);
return;
}
pushRestTime = Time.time;
RecordNewGesture(-(int)EasyLeapGestureType.PUSH,EasyLeapGestureState.STATESTART,EasyLeapGestureState.STATEUPDATE,EasyLeapGestureType.PUSH,-1,mFrame.Hands[0].StabilizedPalmPosition);
}
private void PullGestureRecognised(EasyLeapGestureState state) {
if(state == EasyLeapGestureState.STATEINVALID || Time.time < pullRestTime + EasyLeapGesture.PullRecoveryTime) {
gestureList.Remove(-(int)EasyLeapGestureType.PULL);
return;
}
pullRestTime = Time.time;
RecordNewGesture(-(int)EasyLeapGestureType.PULL,EasyLeapGestureState.STATESTART,EasyLeapGestureState.STATEUPDATE,EasyLeapGestureType.PULL,-1,mFrame.Hands[0].StabilizedPalmPosition);
}
private void CloseFistGestureRecognised(EasyLeapGestureState state) {
if(EasyLeapGestureState.STATEINVALID == state) {
gestureList.Remove (-(int)EasyLeapGestureType.CLOSE_FIST);
return;
}
if(state == EasyLeapGestureState.STATESTOP && !gestureList.ContainsKey(-(int)EasyLeapGestureType.CLOSE_FIST)) return;
RecordNewGesture(-(int)EasyLeapGestureType.CLOSE_FIST,
EasyLeapGestureState.STATESTART,
state == EasyLeapGestureState.STATESTART ? EasyLeapGestureState.STATEUPDATE : EasyLeapGestureState.STATESTOP,
EasyLeapGestureType.CLOSE_FIST,
-1,
mFrame.Hands[0].StabilizedPalmPosition);
}
private void OpenFistGestureRecognised(EasyLeapGestureState state) {
if(EasyLeapGestureState.STATEINVALID == state) {
gestureList.Remove (-(int)EasyLeapGestureType.OPEN_FIST);
return;
}
if(state == EasyLeapGestureState.STATESTOP && !gestureList.ContainsKey(-(int)EasyLeapGestureType.OPEN_FIST)) return;
RecordNewGesture(-(int)EasyLeapGestureType.OPEN_FIST,
EasyLeapGestureState.STATESTART,
state == EasyLeapGestureState.STATESTART ? EasyLeapGestureState.STATEUPDATE : EasyLeapGestureState.STATESTOP,
EasyLeapGestureType.OPEN_FIST,
-1,
mFrame.Hands[0].StabilizedPalmPosition);
}
private void BuiltInImprovedGestureRecognised(Leap.Gesture gesture, EasyLeapGestureType type) {
if(!gestureList.ContainsKey(-(int)type)) {
RecordNewGesture(-(int)type,
EasyLeapGestureState.STATESTOP,
EasyLeapGestureState.STATEUPDATE,
type,
-1,
gesture.Hands[0].StabilizedPalmPosition);
}
}
private void BuiltInGestureRecognised(Leap.Gesture gesture, EasyLeapGestureType type) {
RecordNewGesture(gesture.Id,ConvertGestureState(gesture.State),ConvertGestureState(gesture.State),type,gesture.Duration,gesture.Hands[0].StabilizedPalmPosition);
}
private void NumbersGestureRecognised(EasyLeapGestureType type) {
if(type != EasyLeapGestureType.DEFAULT) {
RecordNewGesture(-(int)type,EasyLeapGestureState.STATESTART,EasyLeapGestureState.STATEUPDATE,type,-1,mFrame.Hands[0].StabilizedPalmPosition);
}
if(gestureList.Count == 0) return;
for(int ii =(int)EasyLeapGestureType.ONE; ii<=(int)EasyLeapGestureType.TEN; ii++) {
if(type != (EasyLeapGestureType)(ii) && gestureList.ContainsKey(-ii)) {
EasyLeapGesture g = gestureList[-ii];
g.State = EasyLeapGestureState.STATESTOP;
gestureList[-(int)ii] = g;
}
}
}
// Send Gestures to all registered listeners with gestures recognised on current frame
private void SendGesturesToListeners() {
Dictionary<int,EasyLeapGesture> copy = new Dictionary<int, EasyLeapGesture> (gestureList);
foreach(KeyValuePair<int,EasyLeapGesture> obj in copy) {
GestureRecognised(obj.Value);
if(obj.Value.State == EasyLeapGestureState.STATESTOP) gestureList.Remove (obj.Key);
}
}
// Auxiliary functions //
private int GetFingerCount() {
int count = 0;
foreach(Leap.Finger finger in mFrame.Fingers) {
if(Mathf.Rad2Deg*finger.Direction.AngleTo(finger.Hand.Direction) < EasyLeapGesture.MaxAngleFinger
&& finger.Length > EasyLeapGesture.MinDistanceFinger) count++;
}
return count;
}
private EasyLeapGestureState ConvertGestureState(Leap.Gesture.GestureState state) {
switch(state) {
case Leap.Gesture.GestureState.STATESTART:
return EasyLeapGestureState.STATESTART;
case Leap.Gesture.GestureState.STATEUPDATE:
return EasyLeapGestureState.STATEUPDATE;
case Leap.Gesture.GestureState.STATESTOP:
return EasyLeapGestureState.STATESTOP;
}
return EasyLeapGestureState.STATEINVALID;
}
private bool PalmIsHorizontal(Leap.Hand hand) {
return hand.PalmNormal.AngleTo(Leap.Vector.Down)*Mathf.Rad2Deg < EasyLeapGesture.MaxAnglePalm &&
Mathf.Abs (hand.StabilizedPalmPosition.x) < EasyLeapGesture.MaxFieldPalm &&
Mathf.Abs (hand.StabilizedPalmPosition.z) < EasyLeapGesture.MaxFieldPalm;
}
}
// Structs and enums //
public struct EasyLeapGesture {
public EasyLeapGestureType Type;
public EasyLeapGestureState State;
public long Duration;
public Leap.Frame Frame;
public Leap.Vector Position;
public int Id;
// configurable settings
public static float MaxAngleFinger = 45f; // max angle to consider a pointable a finger
public static float MinDistanceFinger = 25f; // min distance to consider a pointable a finger (away from hand)
public static float MaxAnglePalm = 25f; // max angle to consider a hand horizontal
public static float MaxFieldPalm = 180f; // max x and z to read palm pos
public static float PullRecoveryTime = 0.2f; // min time in between pull gestures
public static float PushRecoveryTime = 0.2f; // min time in between push gestures
public static float MinPushPullVelocity = 350f; // min velocity to recognise push pull gestures
public static float DoubleInwardsRecoveryTime = 0.2f; // min time in between double inwards swipe gestures
public static float DoubleOutwardsRecoveryTime = 0.2f; // min time in between double outwards swipe gestures
public static float MinSwipeVelocity = 200f; // min velocity to recognise double swipe gestures
public static float MaxPalmDistance = 120f; // max distance between palms to consider together -double swipe
public static float MinClapVelocity = 350f; // min velocity to recognise a clap gesture
public static float MaxPalmClapDistance = 90f; // max distance between palms to consider together -clap
public static float ClapRecoveryTime = 0.15f; // min time in between claps
}
public enum EasyLeapGestureType {
DEFAULT,
TYPECIRCLE,
TYPESWIPE,
TYPEKEYTAP,
TWO_FINGERS_KEYTAP,
THREE_FINGERS_KEYTAP,
TYPESCREENTAP,
TWO_FINGERS_SCREENTAP,
THREE_FINGERS_SCREENTAP,
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
CLOSE_FIST,
OPEN_FIST,
PUSH,
PULL,
DOUBLE_SWIPE_IN,
DOUBLE_SWIPE_OUT,
CLAP,
STEERING_WHEEL,
NUM_OF_ITEMS
}
public enum EasyLeapGestureState {
STATEINVALID,
STATESTART,
STATEUPDATE,
STATESTOP
}
| |
//-----------------------------------------------------------------------
// <copyright file="PersistentFSMBase.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Akka.Actor;
using Akka.Actor.Internal;
using Akka.Event;
using Akka.Persistence.Serialization;
using Akka.Routing;
using Akka.Util;
using Akka.Util.Internal;
namespace Akka.Persistence.Fsm
{
public abstract class PersistentFSMBase<TState, TData, TEvent> : PersistentActor, IListeners
{
public delegate State StateFunction(
FSMBase.Event<TData> fsmEvent, State state = null);
public delegate void TransitionHandler(TState initialState, TState nextState);
protected readonly ListenerSupport _listener = new ListenerSupport();
private readonly ILoggingAdapter _log = Context.GetLogger();
/// <summary>
/// State definitions
/// </summary>
private readonly Dictionary<TState, StateFunction> _stateFunctions = new Dictionary<TState, StateFunction>();
private readonly Dictionary<TState, TimeSpan?> _stateTimeouts = new Dictionary<TState, TimeSpan?>();
private readonly AtomicCounter _timerGen = new AtomicCounter(0);
/// <summary>
/// Timer handling
/// </summary>
protected readonly IDictionary<string, Timer> _timers = new Dictionary<string, Timer>();
/// <summary>
/// Transition handling
/// </summary>
private readonly IList<TransitionHandler> _transitionEvent = new List<TransitionHandler>();
/// <summary>
/// FSM state data and current timeout handling
/// </summary>
/// a
protected State _currentState;
protected long _generation;
private StateFunction _handleEvent;
private State _nextState;
/// <summary>
/// Termination handling
/// </summary>
private Action<FSMBase.StopEvent<TState, TData>> _terminateEvent = @event => { };
protected ICancelable _timeoutFuture;
/// <summary>
/// Can be set to enable debugging on certain actions taken by the FSM
/// </summary>
protected bool DebugEvent;
protected PersistentFSMBase()
{
if (this is ILoggingFSM)
DebugEvent = Context.System.Settings.FsmDebugEvent;
}
/// <summary>
/// Current state name
/// </summary>
public TState StateName
{
get { return _currentState.StateName; }
}
/// <summary>
/// Current state data
/// </summary>
public TData StateData
{
get { return _currentState.StateData; }
}
/// <summary>
/// Return next state data (available in <see cref="OnTransition" /> handlers)
/// </summary>
public TData NextStateData
{
get
{
if (_nextState == null)
throw new InvalidOperationException("NextStateData is only available during OnTransition");
return _nextState.StateData;
}
}
/// <summary>
/// Unhandled event handler
/// </summary>
private StateFunction HandleEventDefault
{
get
{
return delegate(FSMBase.Event<TData> @event, State state)
{
_log.Warning("unhandled event {0} in state {1}", @event.FsmEvent, StateName);
return Stay();
};
}
}
private StateFunction HandleEvent
{
get { return _handleEvent ?? (_handleEvent = HandleEventDefault); }
set { _handleEvent = value; }
}
public bool IsStateTimerActive { get; private set; }
public ListenerSupport Listeners
{
get { return _listener; }
}
/// <summary>
/// Insert a new <see cref="StateFunction" /> at the end of the processing chain for the
/// given state. If the stateTimeout parameter is set, entering this state without a
/// differing explicit timeout setting will trigger a <see cref="FSMBase.StateTimeout" />.
/// </summary>
/// <param name="stateName">designator for the state</param>
/// <param name="func">delegate describing this state's response to input</param>
/// <param name="timeout">default timeout for this state</param>
public void When(TState stateName, StateFunction func, TimeSpan? timeout = null)
{
Register(stateName, func, timeout);
}
/// <summary>
/// Sets the initial state for this FSM. Call this method from the constructor before the <see cref="Initialize" />
/// method.
/// If different state is needed after a restart this method, followed by <see cref="Initialize" />, can be used in the
/// actor
/// life cycle hooks <see cref="ActorBase.PreStart()" /> and <see cref="ActorBase.PostRestart" />.
/// </summary>
/// <param name="stateName">Initial state designator.</param>
/// <param name="stateData">Initial state data.</param>
/// <param name="timeout">State timeout for the initial state, overriding the default timeout for that state.</param>
public void StartWith(TState stateName, TData stateData, TimeSpan? timeout = null)
{
_currentState = new State(stateName, stateData, timeout);
}
/// <summary>
/// Produce transition to other state. Return this from a state function
/// in order to effect the transition.
/// </summary>
/// <param name="nextStateName">State designator for the next state</param>
/// <returns>State transition descriptor</returns>
public State GoTo(TState nextStateName)
{
return new State(nextStateName, _currentState.StateData);
}
/// <summary>
/// Produce transition to other state. Return this from a state function
/// in order to effect the transition.
/// </summary>
/// <param name="nextStateName">State designator for the next state</param>
/// <param name="stateData">Data for next state</param>
/// <returns>State transition descriptor</returns>
public State GoTo(TState nextStateName, TData stateData)
{
return new State(nextStateName, stateData);
}
/// <summary>
/// Produce "empty" transition descriptor. Return this from a state function
/// when no state change is to be effected.
/// </summary>
/// <returns>Descriptor for staying in the current state.</returns>
public State Stay()
{
return GoTo(_currentState.StateName);
}
/// <summary>
/// Produce change descriptor to stop this FSM actor with <see cref="FSMBase.Reason" /> <see cref="FSMBase.Normal" />
/// </summary>
public State Stop()
{
return Stop(new FSMBase.Normal());
}
/// <summary>
/// Produce change descriptor to stop this FSM actor with the specified <see cref="FSMBase.Reason" />.
/// </summary>
public State Stop(FSMBase.Reason reason)
{
return Stop(reason, _currentState.StateData);
}
public State Stop(FSMBase.Reason reason, TData stateData)
{
return Stay().Using(stateData).WithStopReason(reason);
}
/// <summary>
/// Schedule named timer to deliver message after given delay, possibly repeating.
/// Any existing timer with the same name will automatically be canceled before adding
/// the new timer.
/// </summary>
/// <param name="name">identifier to be used with <see cref="CancelTimer" />.</param>
/// <param name="msg">message to be delivered</param>
/// <param name="timeout">delay of first message delivery and between subsequent messages.</param>
/// <param name="repeat">send once if false, scheduleAtFixedRate if true</param>
public void SetTimer(string name, object msg, TimeSpan timeout, bool repeat = false)
{
if (DebugEvent)
_log.Debug("setting " + (repeat ? "repeating" : "") + "timer '{0}' / {1}: {2}", name, timeout, msg);
if (_timers.ContainsKey(name))
_timers[name].Cancel();
var timer = new Timer(name, msg, repeat, _timerGen.Next(), Context, DebugEvent ? _log : null);
timer.Schedule(Self, timeout);
if (!_timers.ContainsKey(name))
_timers.Add(name, timer);
else
_timers[name] = timer;
}
/// <summary>
/// Cancel a named <see cref="System.Threading.Timer" />, ensuring that the message is not subsequently delivered (no
/// race.)
/// </summary>
/// <param name="name">The name of the timer to cancel.</param>
public void CancelTimer(string name)
{
if (DebugEvent)
{
_log.Debug("Cancelling timer {0}", name);
}
if (_timers.ContainsKey(name))
{
_timers[name].Cancel();
_timers.Remove(name);
}
}
/// <summary>
/// Determines whether the named timer is still active. Returns true
/// unless the timer does not exist, has previously been cancelled, or
/// if it was a single-shot timer whose message was already received.
/// </summary>
public bool IsTimerActive(string name)
{
return _timers.ContainsKey(name);
}
/// <summary>
/// Set the state timeout explicitly. This method can be safely used from
/// within a state handler.
/// </summary>
public void SetStateTimeout(TState state, TimeSpan? timeout)
{
if (!_stateTimeouts.ContainsKey(state))
_stateTimeouts.Add(state, timeout);
else
_stateTimeouts[state] = timeout;
}
/// <summary>
/// Set handler which is called upon each state transition, i.e. not when
/// staying in the same state.
/// </summary>
public void OnTransition(TransitionHandler transitionHandler)
{
_transitionEvent.Add(transitionHandler);
}
/// <summary>
/// Set the handler which is called upon termination of this FSM actor. Calling this
/// method again will overwrite the previous contents.
/// </summary>
public void OnTermination(Action<FSMBase.StopEvent<TState, TData>> terminationHandler)
{
_terminateEvent = terminationHandler;
}
/// <summary>
/// Set handler which is called upon reception of unhandled FSM messages. Calling
/// this method again will overwrite the previous contents.
/// </summary>
/// <param name="stateFunction"></param>
public void WhenUnhandled(StateFunction stateFunction)
{
HandleEvent = OrElse(stateFunction, HandleEventDefault);
}
/// <summary>
/// Verify the existence of initial state and setup timers. This should be the
/// last call within the constructor or <see cref="ActorBase.PreStart" /> and
/// <see cref="ActorBase.PostRestart" />.
/// </summary>
public void Initialize()
{
MakeTransition(_currentState);
}
public TransformHelper Transform(StateFunction func)
{
return new TransformHelper(func);
}
private void Register(TState name, StateFunction function, TimeSpan? timeout)
{
if (_stateFunctions.ContainsKey(name))
{
_stateFunctions[name] = OrElse(_stateFunctions[name], function);
_stateTimeouts[name] = _stateTimeouts[name] ?? timeout;
}
else
{
_stateFunctions.Add(name, function);
_stateTimeouts.Add(name, timeout);
}
}
private void HandleTransition(TState previous, TState next)
{
foreach (var tran in _transitionEvent)
{
tran.Invoke(previous, next);
}
}
/// <summary>
/// C# port of Scala's orElse method for partial function chaining.
/// See http://scalachina.com/api/scala/PartialFunction.html
/// </summary>
/// <param name="original">The original <see cref="StateFunction" /> to be called</param>
/// <param name="fallback">The <see cref="StateFunction" /> to be called if <paramref name="original" /> returns null</param>
/// <returns>
/// A <see cref="StateFunction" /> which combines both the results of <paramref name="original" /> and
/// <paramref name="fallback" />
/// </returns>
private static StateFunction OrElse(StateFunction original, StateFunction fallback)
{
StateFunction chained = delegate(FSMBase.Event<TData> @event, State state)
{
var originalResult = original.Invoke(@event, state);
if (originalResult == null) return fallback.Invoke(@event, state);
return originalResult;
};
return chained;
}
protected void ProcessMsg(object any, object source)
{
var fsmEvent = new FSMBase.Event<TData>(any, _currentState.StateData);
ProcessEvent(fsmEvent, source);
}
private void ProcessEvent(FSMBase.Event<TData> fsmEvent, object source)
{
if (DebugEvent)
{
var srcStr = GetSourceString(source);
_log.Debug("processing {0} from {1}", fsmEvent, srcStr);
}
var stateFunc = _stateFunctions[_currentState.StateName];
var oldState = _currentState;
State upcomingState = null;
if (stateFunc != null)
{
upcomingState = stateFunc(fsmEvent);
}
if (upcomingState == null)
{
upcomingState = HandleEvent(fsmEvent);
}
ApplyState(upcomingState);
if (DebugEvent && !Equals(oldState, upcomingState))
{
_log.Debug("transition {0} -> {1}", oldState, upcomingState);
}
}
private string GetSourceString(object source)
{
var s = source as string;
if (s != null) return s;
var timer = source as Timer;
if (timer != null) return "timer '" + timer.Name + "'";
var actorRef = source as IActorRef;
if (actorRef != null) return actorRef.ToString();
return "unknown";
}
protected virtual void ApplyState(State upcomingState)
{
if (upcomingState.StopReason == null)
{
MakeTransition(upcomingState);
return;
}
var replies = upcomingState.Replies;
replies.Reverse();
foreach (var reply in replies)
{
Sender.Tell(reply);
}
Terminate(upcomingState);
Context.Stop(Self);
}
private void MakeTransition(State upcomingState)
{
if (!_stateFunctions.ContainsKey(upcomingState.StateName))
{
Terminate(
Stay()
.WithStopReason(
new FSMBase.Failure(string.Format("Next state {0} does not exist", upcomingState.StateName))));
}
else
{
var replies = upcomingState.Replies;
replies.Reverse();
foreach (var r in replies)
{
Sender.Tell(r);
}
if (!_currentState.StateName.Equals(upcomingState.StateName))
{
_nextState = upcomingState;
HandleTransition(_currentState.StateName, _nextState.StateName);
Listeners.Gossip(new FSMBase.Transition<TState>(Self, _currentState.StateName, _nextState.StateName));
_nextState = null;
}
_currentState = upcomingState;
var timeout = _currentState.Timeout ?? _stateTimeouts[_currentState.StateName];
if (timeout.HasValue)
{
var t = timeout.Value;
if (t < TimeSpan.MaxValue)
{
_timeoutFuture = Context.System.Scheduler.ScheduleTellOnceCancelable(t, Context.Self,
new TimeoutMarker(_generation), Context.Self);
}
}
}
}
protected override bool ReceiveCommand(object message)
{
var match = message.Match()
.With<TimeoutMarker>(marker =>
{
if (_generation == marker.Generation)
{
ProcessMsg(new StateTimeout(), "state timeout");
}
})
.With<Timer>(t =>
{
if (_timers.ContainsKey(t.Name) && _timers[t.Name].Generation == t.Generation)
{
if (_timeoutFuture != null)
{
_timeoutFuture.Cancel(false);
_timeoutFuture = null;
}
_generation++;
if (!t.Repeat)
{
_timers.Remove(t.Name);
}
ProcessMsg(t.Message, t);
}
})
.With<FSMBase.SubscribeTransitionCallBack>(cb =>
{
Context.Watch(cb.ActorRef);
Listeners.Add(cb.ActorRef);
//send the current state back as a reference point
cb.ActorRef.Tell(new FSMBase.CurrentState<TState>(Self, _currentState.StateName));
})
.With<Listen>(l =>
{
Context.Watch(l.Listener);
Listeners.Add(l.Listener);
l.Listener.Tell(new FSMBase.CurrentState<TState>(Self, _currentState.StateName));
})
.With<FSMBase.UnsubscribeTransitionCallBack>(ucb =>
{
Context.Unwatch(ucb.ActorRef);
Listeners.Remove(ucb.ActorRef);
})
.With<Deafen>(d =>
{
Context.Unwatch(d.Listener);
Listeners.Remove(d.Listener);
})
.With<InternalActivateFsmLogging>(_ => { DebugEvent = true; })
.Default(msg =>
{
if (_timeoutFuture != null)
{
_timeoutFuture.Cancel(false);
_timeoutFuture = null;
}
_generation++;
ProcessMsg(msg, Sender);
});
return match.WasHandled;
}
protected void Terminate(State upcomingState)
{
if (_currentState.StopReason == null)
{
var reason = upcomingState.StopReason;
LogTermination(reason);
foreach (var t in _timers)
{
t.Value.Cancel();
}
_timers.Clear();
_currentState = upcomingState;
var stopEvent = new FSMBase.StopEvent<TState, TData>(reason, _currentState.StateName,
_currentState.StateData);
_terminateEvent(stopEvent);
}
}
/// <summary>
/// Call the <see cref="OnTermination" /> hook if you want to retain this behavior.
/// When overriding make sure to call base.PostStop();
/// Please note that this method is called by default from <see cref="ActorBase.PreRestart" /> so
/// override that one if <see cref="OnTermination" /> shall not be called during restart.
/// </summary>
protected override void PostStop()
{
/*
* Setting this instance's state to Terminated does no harm during restart, since
* the new instance will initialize fresh using StartWith.
*/
Terminate(Stay().WithStopReason(new FSMBase.Shutdown()));
base.PostStop();
}
/// <summary>
/// By default, <see cref="Failure" /> is logged at error level and other
/// reason types are not logged. It is possible to override this behavior.
/// </summary>
/// <param name="reason"></param>
protected virtual void LogTermination(FSMBase.Reason reason)
{
reason.Match()
.With<FSMBase.Failure>(f =>
{
if (f.Cause is Exception)
{
_log.Error(f.Cause.AsInstanceOf<Exception>(), "terminating due to Failure");
}
else
{
_log.Error(f.Cause.ToString());
}
});
}
public sealed class TransformHelper
{
public TransformHelper(StateFunction func)
{
Func = func;
}
public StateFunction Func { get; private set; }
public StateFunction Using(Func<State, State> andThen)
{
StateFunction continuedDelegate = (@event, state) => andThen.Invoke(Func.Invoke(@event, state));
return continuedDelegate;
}
}
public class StateChangeEvent : IMessage
{
public StateChangeEvent(TState state, TimeSpan? timeOut)
{
State = state;
TimeOut = timeOut;
}
public TState State { get; private set; }
public TimeSpan? TimeOut { get; private set; }
}
#region States
/// <summary>
/// Used in the event of a timeout between transitions
/// </summary>
public class StateTimeout
{
}
/*
* INTERNAL API - used for ensuring that state changes occur on-time
*/
internal class TimeoutMarker
{
public TimeoutMarker(long generation)
{
Generation = generation;
}
public long Generation { get; private set; }
}
[DebuggerDisplay("Timer {Name,nq}, message: {Message")]
public class Timer : INoSerializationVerificationNeeded
{
private readonly ILoggingAdapter _debugLog;
private readonly ICancelable _ref;
private readonly IScheduler _scheduler;
public Timer(string name, object message, bool repeat, int generation, IActorContext context,
ILoggingAdapter debugLog)
{
_debugLog = debugLog;
Context = context;
Generation = generation;
Repeat = repeat;
Message = message;
Name = name;
var scheduler = context.System.Scheduler;
_scheduler = scheduler;
_ref = new Cancelable(scheduler);
}
public string Name { get; private set; }
public object Message { get; private set; }
public bool Repeat { get; private set; }
public int Generation { get; private set; }
public IActorContext Context { get; private set; }
public void Schedule(IActorRef actor, TimeSpan timeout)
{
var name = Name;
var message = Message;
Action send;
if (_debugLog != null)
send = () =>
{
_debugLog.Debug("{0}Timer '{1}' went off. Sending {2} -> {3}",
_ref.IsCancellationRequested ? "Cancelled " : "", name, message, actor);
actor.Tell(this, Context.Self);
};
else
send = () => actor.Tell(this, Context.Self);
if (Repeat) _scheduler.Advanced.ScheduleRepeatedly(timeout, timeout, send, _ref);
else _scheduler.Advanced.ScheduleOnce(timeout, send, _ref);
}
public void Cancel()
{
if (!_ref.IsCancellationRequested)
{
_ref.Cancel(false);
}
}
}
/// <summary>
/// This captures all of the managed state of the <see cref="PersistentFSM{T,S,E}" />: the state name,
/// the state data, possibly custom timeout, stop reason, and replies accumulated while
/// processing the last message.
/// </summary>
[Obsolete("This was left for backward compatibility. Use type parameterless class instead. Can be removed in future releases.")]
public class State<TS, TD, TE>
where TS : TState where TD : TData where TE : TEvent
{
private State _state;
public State(State state)
{
_state = state;
}
public State(
TState stateName,
TData stateData,
TimeSpan? timeout = null,
FSMBase.Reason stopReason = null,
List<object> replies = null,
ILinearSeq<TEvent> domainEvents = null,
Action<TData> afterTransitionDo = null)
{
_state = new State(stateName, stateData, timeout, stopReason, replies, domainEvents, afterTransitionDo);
}
/// <summary>
/// Converts original object to wrapper
/// </summary>
/// <param name="state">The original object</param>
public static implicit operator State(State<TS, TD, TE> state)
{
return state._state;
}
/// <summary>
/// Converts original object to wrapper
/// </summary>
/// <param name="state">The original object</param>
public static implicit operator State<TS, TD, TE>(State state)
{
return new State<TS, TD, TE>(state);
}
public Action<TData> AfterTransitionHandler
{
get
{
return _state.AfterTransitionHandler;
}
}
public ILinearSeq<TEvent> DomainEvents
{
get
{
return _state.DomainEvents;
}
}
public bool Notifies
{
get
{
return _state.Notifies;
}
set
{
_state.Notifies = value;
}
}
public State Applying(ILinearSeq<TEvent> events)
{
return _state.Applying(events);
}
/// <summary>
/// Specify domain event to be applied when transitioning to the new state.
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public State Applying(TEvent e)
{
return _state.Applying(e);
}
/// <summary>
/// Register a handler to be triggered after the state has been persisted successfully
/// </summary>
/// <param name="handler"></param>
/// <returns></returns>
public State AndThen(Action<TData> handler)
{
return _state.AndThen(handler);
}
public State Copy(
TimeSpan? timeout,
FSMBase.Reason stopReason = null,
List<object> replies = null,
ILinearSeq<TEvent> domainEvents = null,
Action<TData> afterTransitionDo = null)
{
return _state.Copy(timeout, stopReason, replies, domainEvents, afterTransitionDo);
}
/// <summary>
/// Modify state transition descriptor with new state data. The data will be set
/// when transitioning to the new state.
/// </summary>
public State Using(TData nextStateData)
{
return _state.Using(nextStateData);
}
public State Replying(object replyValue)
{
return _state.Replying(replyValue);
}
public State ForMax(TimeSpan timeout)
{
return _state.ForMax(timeout);
}
public List<object> Replies
{
get
{
return _state.Replies;
}
}
public TState StateName
{
get
{
return _state.StateName;
}
}
public TData StateData
{
get
{
return _state.StateData;
}
}
public TimeSpan? Timeout
{
get
{
return _state.Timeout;
}
}
public FSMBase.Reason StopReason
{
get
{
return _state.StopReason;
}
}
}
/// <summary>
/// This captures all of the managed state of the <see cref="PersistentFSM{T,S,E}" />: the state name,
/// the state data, possibly custom timeout, stop reason, and replies accumulated while
/// processing the last message.
/// </summary>
public class State : FSMBase.State<TState, TData>
{
public Action<TData> AfterTransitionHandler { get; private set; }
public State(TState stateName, TData stateData, TimeSpan? timeout = null, FSMBase.Reason stopReason = null,
List<object> replies = null, ILinearSeq<TEvent> domainEvents = null, Action<TData> afterTransitionDo = null)
: base(stateName, stateData, timeout, stopReason, replies)
{
AfterTransitionHandler = afterTransitionDo;
DomainEvents = domainEvents;
Notifies = true;
}
public ILinearSeq<TEvent> DomainEvents { get; private set; }
public bool Notifies { get; set; }
/// <summary>
/// Specify domain events to be applied when transitioning to the new state.
/// </summary>
/// <param name="events"></param>
/// <returns></returns>
public State Applying(ILinearSeq<TEvent> events)
{
if (DomainEvents == null)
{
return Copy(null, null, null, events);
}
return Copy(null, null, null, new ArrayLinearSeq<TEvent>(DomainEvents.Concat(events).ToArray()));
}
/// <summary>
/// Specify domain event to be applied when transitioning to the new state.
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public State Applying(TEvent e)
{
if (DomainEvents == null)
{
return Copy(null, null, null, new ArrayLinearSeq<TEvent>(new[] {e}));
}
var events = new List<TEvent>();
events.AddRange(DomainEvents);
events.Add(e);
return Copy(null, null, null, new ArrayLinearSeq<TEvent>(DomainEvents.Concat(events).ToArray()));
}
/// <summary>
/// Register a handler to be triggered after the state has been persisted successfully
/// </summary>
/// <param name="handler"></param>
/// <returns></returns>
public State AndThen(Action<TData> handler)
{
return Copy(null, null, null, null, handler);
}
public State Copy(TimeSpan? timeout, FSMBase.Reason stopReason = null,
List<object> replies = null, ILinearSeq<TEvent> domainEvents = null, Action<TData> afterTransitionDo = null)
{
return new State(StateName, StateData, timeout ?? Timeout, stopReason ?? StopReason,
replies ?? Replies,
domainEvents ?? DomainEvents, afterTransitionDo ?? AfterTransitionHandler);
}
/// <summary>
/// Modify state transition descriptor with new state data. The data will be set
/// when transitioning to the new state.
/// </summary>
public new State Using(TData nextStateData)
{
return new State(StateName, nextStateData, Timeout, StopReason, Replies);
}
public new State Replying(object replyValue)
{
if (Replies == null) Replies = new List<object>();
var newReplies = Replies.ToArray().ToList();
newReplies.Add(replyValue);
return Copy(Timeout, replies: newReplies);
}
public new State ForMax(TimeSpan timeout)
{
if (timeout <= TimeSpan.MaxValue) return Copy(timeout);
return Copy(null);
}
/// <summary>
/// INTERNAL API
/// </summary>
internal State WithStopReason(FSMBase.Reason reason)
{
return Copy(null, reason);
}
#endregion
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
namespace System.Configuration
{
public sealed class ConfigurationProperty
{
internal static readonly ConfigurationValidatorBase s_nonEmptyStringValidator = new StringValidator(1);
private static readonly ConfigurationValidatorBase s_defaultValidatorInstance = new DefaultValidator();
internal const string DefaultCollectionPropertyName = "";
private TypeConverter _converter;
private volatile bool _isConfigurationElementType;
private volatile bool _isTypeInited;
private ConfigurationPropertyOptions _options;
public ConfigurationProperty(string name, Type type)
{
object defaultValue = null;
ConstructorInit(name, type, ConfigurationPropertyOptions.None, null, null, null);
if (type == typeof(string))
{
defaultValue = string.Empty;
}
else if (type.IsValueType)
{
defaultValue = TypeUtil.CreateInstance(type);
}
SetDefaultValue(defaultValue);
}
public ConfigurationProperty(string name, Type type, object defaultValue)
: this(name, type, defaultValue, ConfigurationPropertyOptions.None)
{ }
public ConfigurationProperty(string name, Type type, object defaultValue, ConfigurationPropertyOptions options)
: this(name, type, defaultValue, null, null, options)
{ }
public ConfigurationProperty(string name,
Type type,
object defaultValue,
TypeConverter typeConverter,
ConfigurationValidatorBase validator,
ConfigurationPropertyOptions options)
: this(name, type, defaultValue, typeConverter, validator, options, null)
{ }
public ConfigurationProperty(string name,
Type type,
object defaultValue,
TypeConverter typeConverter,
ConfigurationValidatorBase validator,
ConfigurationPropertyOptions options,
string description)
{
ConstructorInit(name, type, options, validator, typeConverter, description);
SetDefaultValue(defaultValue);
}
internal ConfigurationProperty(PropertyInfo info)
{
Debug.Assert(info != null, "info != null");
ConfigurationPropertyAttribute propertyAttribute = null;
DescriptionAttribute descriptionAttribute = null;
// For compatibility we read the component model default value attribute. It is only
// used if ConfigurationPropertyAttribute doesn't provide the default value.
DefaultValueAttribute defaultValueAttribute = null;
TypeConverter typeConverter = null;
ConfigurationValidatorBase validator = null;
// Look for relevant attributes
foreach (Attribute attribute in Attribute.GetCustomAttributes(info))
{
if (attribute is TypeConverterAttribute)
{
typeConverter = TypeUtil.CreateInstance<TypeConverter>(((TypeConverterAttribute)attribute).ConverterTypeName);
}
else if (attribute is ConfigurationPropertyAttribute)
{
propertyAttribute = (ConfigurationPropertyAttribute)attribute;
}
else if (attribute is ConfigurationValidatorAttribute)
{
if (validator != null)
{
// We only allow one validator to be specified on a property.
//
// Consider: introduce a new validator type ( CompositeValidator ) that is a
// list of validators and executes them all
throw new ConfigurationErrorsException(
SR.Format(SR.Validator_multiple_validator_attributes, info.Name));
}
ConfigurationValidatorAttribute validatorAttribute = (ConfigurationValidatorAttribute)attribute;
validatorAttribute.SetDeclaringType(info.DeclaringType);
validator = validatorAttribute.ValidatorInstance;
}
else if (attribute is DescriptionAttribute)
{
descriptionAttribute = (DescriptionAttribute)attribute;
}
else if (attribute is DefaultValueAttribute)
{
defaultValueAttribute = (DefaultValueAttribute)attribute;
}
}
Type propertyType = info.PropertyType;
// If the property is a Collection we need to look for the ConfigurationCollectionAttribute for
// additional customization.
if (typeof(ConfigurationElementCollection).IsAssignableFrom(propertyType))
{
// Look for the ConfigurationCollection attribute on the property itself, fall back
// on the property type.
ConfigurationCollectionAttribute collectionAttribute =
Attribute.GetCustomAttribute(info,
typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute ??
Attribute.GetCustomAttribute(propertyType,
typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
if (collectionAttribute != null)
{
if (collectionAttribute.AddItemName.IndexOf(',') == -1) AddElementName = collectionAttribute.AddItemName; // string.Contains(char) is .NetCore2.1+ specific
RemoveElementName = collectionAttribute.RemoveItemName;
ClearElementName = collectionAttribute.ClearItemsName;
}
}
// This constructor shouldn't be invoked if the reflection info is not for an actual config property
Debug.Assert(propertyAttribute != null, "attribProperty != null");
ConstructorInit(propertyAttribute.Name,
info.PropertyType,
propertyAttribute.Options,
validator,
typeConverter,
descriptionAttribute?.Description);
// Figure out the default value
InitDefaultValueFromTypeInfo(propertyAttribute, defaultValueAttribute);
}
public string Name { get; private set; }
public string Description { get; private set; }
internal string ProvidedName { get; private set; }
internal bool IsConfigurationElementType
{
get
{
if (_isTypeInited)
return _isConfigurationElementType;
_isConfigurationElementType = typeof(ConfigurationElement).IsAssignableFrom(Type);
_isTypeInited = true;
return _isConfigurationElementType;
}
}
public Type Type { get; private set; }
public object DefaultValue { get; private set; }
public bool IsRequired => (_options & ConfigurationPropertyOptions.IsRequired) != 0;
public bool IsKey => (_options & ConfigurationPropertyOptions.IsKey) != 0;
public bool IsDefaultCollection => (_options & ConfigurationPropertyOptions.IsDefaultCollection) != 0;
public bool IsTypeStringTransformationRequired
=> (_options & ConfigurationPropertyOptions.IsTypeStringTransformationRequired) != 0;
public bool IsAssemblyStringTransformationRequired
=> (_options & ConfigurationPropertyOptions.IsAssemblyStringTransformationRequired) != 0;
public bool IsVersionCheckRequired => (_options & ConfigurationPropertyOptions.IsVersionCheckRequired) != 0;
public TypeConverter Converter
{
get
{
CreateConverter();
return _converter;
}
}
public ConfigurationValidatorBase Validator { get; private set; }
internal string AddElementName { get; }
internal string RemoveElementName { get; }
internal string ClearElementName { get; }
private void ConstructorInit(
string name,
Type type,
ConfigurationPropertyOptions options,
ConfigurationValidatorBase validator,
TypeConverter converter,
string description)
{
if (typeof(ConfigurationSection).IsAssignableFrom(type))
{
throw new ConfigurationErrorsException(
SR.Format(SR.Config_properties_may_not_be_derived_from_configuration_section, name));
}
// save the provided name so we can check for default collection names
ProvidedName = name;
if (((options & ConfigurationPropertyOptions.IsDefaultCollection) != 0) && string.IsNullOrEmpty(name))
{
name = DefaultCollectionPropertyName;
}
else
{
ValidatePropertyName(name);
}
Name = name;
Description = description;
Type = type;
_options = options;
Validator = validator;
_converter = converter;
// Use the default validator if none was supplied
if (Validator == null)
{
Validator = s_defaultValidatorInstance;
}
else
{
// Make sure the supplied validator supports the type of this property
if (!Validator.CanValidate(Type))
throw new ConfigurationErrorsException(SR.Format(SR.Validator_does_not_support_prop_type, Name));
}
}
private void ValidatePropertyName(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException(SR.String_null_or_empty, nameof(name));
if (BaseConfigurationRecord.IsReservedAttributeName(name))
throw new ArgumentException(SR.Format(SR.Property_name_reserved, name));
}
private void SetDefaultValue(object value)
{
// Validate the default value if any. This should make errors from invalid defaults easier to catch
if (ConfigurationElement.IsNullOrNullProperty(value))
return;
if (!Type.IsInstanceOfType(value))
{
if (!Converter.CanConvertFrom(value.GetType()))
throw new ConfigurationErrorsException(SR.Format(SR.Default_value_wrong_type, Name));
value = Converter.ConvertFrom(value);
}
Validate(value);
DefaultValue = value;
}
private void InitDefaultValueFromTypeInfo(
ConfigurationPropertyAttribute configurationProperty,
DefaultValueAttribute defaultValueAttribute)
{
object defaultValue = configurationProperty.DefaultValue;
// If the ConfigurationPropertyAttribute has no default try the DefaultValueAttribute
if (ConfigurationElement.IsNullOrNullProperty(defaultValue))
defaultValue = defaultValueAttribute?.Value;
// Convert the default value from string if necessary
if (defaultValue is string && (Type != typeof(string)))
{
try
{
defaultValue = Converter.ConvertFromInvariantString((string)defaultValue);
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(SR.Format(SR.Default_value_conversion_error_from_string,
Name, ex.Message));
}
}
// If we still have no default, use string Empty for string or the default for value types
if (ConfigurationElement.IsNullOrNullProperty(defaultValue))
{
if (Type == typeof(string))
{
defaultValue = string.Empty;
}
else if (Type.IsValueType)
{
defaultValue = TypeUtil.CreateInstance(Type);
}
}
SetDefaultValue(defaultValue);
}
internal object ConvertFromString(string value)
{
object result;
try
{
result = Converter.ConvertFromInvariantString(value);
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(SR.Format(SR.Top_level_conversion_error_from_string, Name,
ex.Message));
}
return result;
}
internal string ConvertToString(object value)
{
try
{
if (Type == typeof(bool))
{
// The boolean converter will break 1.1 compat for bool
return (bool)value ? "true" : "false";
}
else
{
return Converter.ConvertToInvariantString(value);
}
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(
SR.Format(SR.Top_level_conversion_error_to_string, Name, ex.Message));
}
}
internal void Validate(object value)
{
try
{
Validator.Validate(value);
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(
SR.Format(SR.Top_level_validation_error, Name, ex.Message), ex);
}
}
private void CreateConverter()
{
if (_converter != null) return;
if (Type.IsEnum)
{
// We use our custom converter for all enums
_converter = new GenericEnumConverter(Type);
}
else if (Type.IsSubclassOf(typeof(ConfigurationElement)))
{
// Type converters aren't allowed on ConfigurationElement
// derived classes.
return;
}
else
{
_converter = TypeDescriptor.GetConverter(Type);
if ((_converter == null) ||
!_converter.CanConvertFrom(typeof(string)) ||
!_converter.CanConvertTo(typeof(string)))
{
// Need to be able to convert to/from string
throw new ConfigurationErrorsException(SR.Format(SR.No_converter, Name, Type.Name));
}
}
}
}
}
| |
/*
* 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 autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// Describes an Auto Scaling group.
/// </summary>
public partial class AutoScalingGroup
{
private string _autoScalingGroupARN;
private string _autoScalingGroupName;
private List<string> _availabilityZones = new List<string>();
private DateTime? _createdTime;
private int? _defaultCooldown;
private int? _desiredCapacity;
private List<EnabledMetric> _enabledMetrics = new List<EnabledMetric>();
private int? _healthCheckGracePeriod;
private string _healthCheckType;
private List<Instance> _instances = new List<Instance>();
private string _launchConfigurationName;
private List<string> _loadBalancerNames = new List<string>();
private int? _maxSize;
private int? _minSize;
private string _placementGroup;
private string _status;
private List<SuspendedProcess> _suspendedProcesses = new List<SuspendedProcess>();
private List<TagDescription> _tags = new List<TagDescription>();
private List<string> _terminationPolicies = new List<string>();
private string _vpcZoneIdentifier;
/// <summary>
/// Gets and sets the property AutoScalingGroupARN.
/// <para>
/// The Amazon Resource Name (ARN) of the group.
/// </para>
/// </summary>
public string AutoScalingGroupARN
{
get { return this._autoScalingGroupARN; }
set { this._autoScalingGroupARN = value; }
}
// Check to see if AutoScalingGroupARN property is set
internal bool IsSetAutoScalingGroupARN()
{
return this._autoScalingGroupARN != null;
}
/// <summary>
/// Gets and sets the property AutoScalingGroupName.
/// <para>
/// The name of the group.
/// </para>
/// </summary>
public string AutoScalingGroupName
{
get { return this._autoScalingGroupName; }
set { this._autoScalingGroupName = value; }
}
// Check to see if AutoScalingGroupName property is set
internal bool IsSetAutoScalingGroupName()
{
return this._autoScalingGroupName != null;
}
/// <summary>
/// Gets and sets the property AvailabilityZones.
/// <para>
/// One or more Availability Zones for the group.
/// </para>
/// </summary>
public List<string> AvailabilityZones
{
get { return this._availabilityZones; }
set { this._availabilityZones = value; }
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this._availabilityZones != null && this._availabilityZones.Count > 0;
}
/// <summary>
/// Gets and sets the property CreatedTime.
/// <para>
/// The date and time the group was created.
/// </para>
/// </summary>
public DateTime CreatedTime
{
get { return this._createdTime.GetValueOrDefault(); }
set { this._createdTime = value; }
}
// Check to see if CreatedTime property is set
internal bool IsSetCreatedTime()
{
return this._createdTime.HasValue;
}
/// <summary>
/// Gets and sets the property DefaultCooldown.
/// <para>
/// The number of seconds after a scaling activity completes before any further scaling
/// activities can start.
/// </para>
/// </summary>
public int DefaultCooldown
{
get { return this._defaultCooldown.GetValueOrDefault(); }
set { this._defaultCooldown = value; }
}
// Check to see if DefaultCooldown property is set
internal bool IsSetDefaultCooldown()
{
return this._defaultCooldown.HasValue;
}
/// <summary>
/// Gets and sets the property DesiredCapacity.
/// <para>
/// The desired size of the group.
/// </para>
/// </summary>
public int DesiredCapacity
{
get { return this._desiredCapacity.GetValueOrDefault(); }
set { this._desiredCapacity = value; }
}
// Check to see if DesiredCapacity property is set
internal bool IsSetDesiredCapacity()
{
return this._desiredCapacity.HasValue;
}
/// <summary>
/// Gets and sets the property EnabledMetrics.
/// <para>
/// The metrics enabled for the group.
/// </para>
/// </summary>
public List<EnabledMetric> EnabledMetrics
{
get { return this._enabledMetrics; }
set { this._enabledMetrics = value; }
}
// Check to see if EnabledMetrics property is set
internal bool IsSetEnabledMetrics()
{
return this._enabledMetrics != null && this._enabledMetrics.Count > 0;
}
/// <summary>
/// Gets and sets the property HealthCheckGracePeriod.
/// <para>
/// The amount of time that Auto Scaling waits before checking an instance's health status.
/// The grace period begins when an instance comes into service.
/// </para>
/// </summary>
public int HealthCheckGracePeriod
{
get { return this._healthCheckGracePeriod.GetValueOrDefault(); }
set { this._healthCheckGracePeriod = value; }
}
// Check to see if HealthCheckGracePeriod property is set
internal bool IsSetHealthCheckGracePeriod()
{
return this._healthCheckGracePeriod.HasValue;
}
/// <summary>
/// Gets and sets the property HealthCheckType.
/// <para>
/// The service of interest for the health status check, which can be either <code>EC2</code>
/// for Amazon EC2 or <code>ELB</code> for Elastic Load Balancing.
/// </para>
/// </summary>
public string HealthCheckType
{
get { return this._healthCheckType; }
set { this._healthCheckType = value; }
}
// Check to see if HealthCheckType property is set
internal bool IsSetHealthCheckType()
{
return this._healthCheckType != null;
}
/// <summary>
/// Gets and sets the property Instances.
/// <para>
/// The EC2 instances associated with the group.
/// </para>
/// </summary>
public List<Instance> Instances
{
get { return this._instances; }
set { this._instances = value; }
}
// Check to see if Instances property is set
internal bool IsSetInstances()
{
return this._instances != null && this._instances.Count > 0;
}
/// <summary>
/// Gets and sets the property LaunchConfigurationName.
/// <para>
/// The name of the associated launch configuration.
/// </para>
/// </summary>
public string LaunchConfigurationName
{
get { return this._launchConfigurationName; }
set { this._launchConfigurationName = value; }
}
// Check to see if LaunchConfigurationName property is set
internal bool IsSetLaunchConfigurationName()
{
return this._launchConfigurationName != null;
}
/// <summary>
/// Gets and sets the property LoadBalancerNames.
/// <para>
/// One or more load balancers associated with the group.
/// </para>
/// </summary>
public List<string> LoadBalancerNames
{
get { return this._loadBalancerNames; }
set { this._loadBalancerNames = value; }
}
// Check to see if LoadBalancerNames property is set
internal bool IsSetLoadBalancerNames()
{
return this._loadBalancerNames != null && this._loadBalancerNames.Count > 0;
}
/// <summary>
/// Gets and sets the property MaxSize.
/// <para>
/// The maximum size of the group.
/// </para>
/// </summary>
public int MaxSize
{
get { return this._maxSize.GetValueOrDefault(); }
set { this._maxSize = value; }
}
// Check to see if MaxSize property is set
internal bool IsSetMaxSize()
{
return this._maxSize.HasValue;
}
/// <summary>
/// Gets and sets the property MinSize.
/// <para>
/// The minimum size of the group.
/// </para>
/// </summary>
public int MinSize
{
get { return this._minSize.GetValueOrDefault(); }
set { this._minSize = value; }
}
// Check to see if MinSize property is set
internal bool IsSetMinSize()
{
return this._minSize.HasValue;
}
/// <summary>
/// Gets and sets the property PlacementGroup.
/// <para>
/// The name of the placement group into which you'll launch your instances, if any. For
/// more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html">Placement
/// Groups</a>.
/// </para>
/// </summary>
public string PlacementGroup
{
get { return this._placementGroup; }
set { this._placementGroup = value; }
}
// Check to see if PlacementGroup property is set
internal bool IsSetPlacementGroup()
{
return this._placementGroup != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The current state of the group when <a>DeleteAutoScalingGroup</a> is in progress.
/// </para>
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property SuspendedProcesses.
/// <para>
/// The suspended processes associated with the group.
/// </para>
/// </summary>
public List<SuspendedProcess> SuspendedProcesses
{
get { return this._suspendedProcesses; }
set { this._suspendedProcesses = value; }
}
// Check to see if SuspendedProcesses property is set
internal bool IsSetSuspendedProcesses()
{
return this._suspendedProcesses != null && this._suspendedProcesses.Count > 0;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// The tags for the group.
/// </para>
/// </summary>
public List<TagDescription> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property TerminationPolicies.
/// <para>
/// The termination policies for the group.
/// </para>
/// </summary>
public List<string> TerminationPolicies
{
get { return this._terminationPolicies; }
set { this._terminationPolicies = value; }
}
// Check to see if TerminationPolicies property is set
internal bool IsSetTerminationPolicies()
{
return this._terminationPolicies != null && this._terminationPolicies.Count > 0;
}
/// <summary>
/// Gets and sets the property VPCZoneIdentifier.
/// <para>
/// One or more subnet IDs, if applicable, separated by commas.
/// </para>
///
/// <para>
/// If you specify <code>VPCZoneIdentifier</code> and <code>AvailabilityZones</code>,
/// ensure that the Availability Zones of the subnets match the values for <code>AvailabilityZones</code>.
/// </para>
/// </summary>
public string VPCZoneIdentifier
{
get { return this._vpcZoneIdentifier; }
set { this._vpcZoneIdentifier = value; }
}
// Check to see if VPCZoneIdentifier property is set
internal bool IsSetVPCZoneIdentifier()
{
return this._vpcZoneIdentifier != null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// AnyAllSearchOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// The any/all operators work the same way. They search for the occurrence of a predicate
/// value in the data source, and upon the first occurrence of such a value, yield a
/// particular value. Specifically:
///
/// - Any returns true if the predicate for any element evaluates to true.
/// - All returns false if the predicate for any element evaluates to false.
///
/// This uniformity is used to apply a general purpose algorithm. Both sentences above
/// take the form of "returns XXX if the predicate for any element evaluates to XXX."
/// Therefore, we just parameterize on XXX, called the qualification below, and if we
/// ever find an occurrence of XXX in the input data source, we also return XXX. Otherwise,
/// we return !XXX. Obviously, XXX in this case is a bool.
///
/// This is a search algorithm. So once any single partition finds an element, it will
/// return so that execution can stop. This is done with a "cancellation" flag that is
/// polled by all parallel workers. The first worker to find an answer sets it, and all
/// other workers notice it and quit as quickly as possible.
/// </summary>
/// <typeparam name="TInput"></typeparam>
internal sealed class AnyAllSearchOperator<TInput> : UnaryQueryOperator<TInput, bool>
{
private readonly Func<TInput, bool> _predicate; // The predicate used to test membership.
private readonly bool _qualification; // Whether we're looking for true (any) or false (all).
//---------------------------------------------------------------------------------------
// Constructs a new instance of an any/all search operator.
//
// Arguments:
// child - the child tree to enumerate.
// qualification - the predicate value we require for an element to be considered
// a member of the set; for any this is true, for all it is false.
//
internal AnyAllSearchOperator(IEnumerable<TInput> child, bool qualification, Func<TInput, bool> predicate)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
Debug.Assert(predicate != null, "need a predicate function");
_qualification = qualification;
_predicate = predicate;
}
//---------------------------------------------------------------------------------------
// Executes the entire query tree, and aggregates the individual partition results to
// form an overall answer to the search operation.
//
internal bool Aggregate()
{
// Because the final reduction is typically much cheaper than the intermediate
// reductions over the individual partitions, and because each parallel partition
// could do a lot of work to produce a single output element, we prefer to turn off
// pipelining, and process the final reductions serially.
using (IEnumerator<bool> enumerator = GetEnumerator(ParallelMergeOptions.FullyBuffered, true))
{
// Any value equal to our qualification means that we've found an element matching
// the condition, and so we return the qualification without looking in subsequent
// partitions.
while (enumerator.MoveNext())
{
if (enumerator.Current == _qualification)
{
return _qualification;
}
}
}
return !_qualification;
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<bool> Open(
QuerySettings settings, bool preferStriping)
{
// We just open the child operator.
QueryResults<TInput> childQueryResults = Child.Open(settings, preferStriping);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TInput, TKey> inputStream, IPartitionedStreamRecipient<bool> recipient, bool preferStriping, QuerySettings settings)
{
// Create a shared cancellation variable and then return a possibly wrapped new enumerator.
Shared<bool> resultFoundFlag = new Shared<bool>(false);
int partitionCount = inputStream.PartitionCount;
PartitionedStream<bool, int> outputStream = new PartitionedStream<bool, int>(
partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new AnyAllSearchOperatorEnumerator<TKey>(inputStream[i], _qualification, _predicate, i, resultFoundFlag,
settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<bool> AsSequentialQuery(CancellationToken token)
{
Debug.Fail("This method should never be called as it is an ending operator with LimitsParallelism=false.");
throw new NotSupportedException();
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
//---------------------------------------------------------------------------------------
// This enumerator performs the search over its input data source. It also cancels peer
// enumerators when an answer was found, and polls this cancellation flag to stop when
// requested.
//
private class AnyAllSearchOperatorEnumerator<TKey> : QueryOperatorEnumerator<bool, int>
{
private readonly QueryOperatorEnumerator<TInput, TKey> _source; // The source data.
private readonly Func<TInput, bool> _predicate; // The predicate.
private readonly bool _qualification; // Whether this is an any (true) or all (false) operator.
private readonly int _partitionIndex; // The partition's index.
private readonly Shared<bool> _resultFoundFlag; // Whether to cancel the search for elements.
private readonly CancellationToken _cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new any/all search operator.
//
internal AnyAllSearchOperatorEnumerator(QueryOperatorEnumerator<TInput, TKey> source, bool qualification,
Func<TInput, bool> predicate, int partitionIndex, Shared<bool> resultFoundFlag,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(predicate != null);
Debug.Assert(resultFoundFlag != null);
_source = source;
_qualification = qualification;
_predicate = predicate;
_partitionIndex = partitionIndex;
_resultFoundFlag = resultFoundFlag;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// This enumerates the entire input source to perform the search. If another peer
// partition finds an answer before us, we will voluntarily return (propagating the
// peer's result).
//
internal override bool MoveNext(ref bool currentElement, ref int currentKey)
{
Debug.Assert(_predicate != null);
// Avoid enumerating if we've already found an answer.
if (_resultFoundFlag.Value)
return false;
// We just scroll through the enumerator and accumulate the result.
TInput element = default(TInput);
TKey keyUnused = default(TKey);
if (_source.MoveNext(ref element, ref keyUnused))
{
currentElement = !_qualification;
currentKey = _partitionIndex;
int i = 0;
// Continue walking the data so long as we haven't found an item that satisfies
// the condition we are searching for.
do
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
if (_resultFoundFlag.Value)
{
// If cancellation occurred, it's because a successful answer was found.
return false;
}
if (_predicate(element) == _qualification)
{
// We have found an item that satisfies the search. Tell other
// workers that are concurrently searching, and return.
_resultFoundFlag.Value = true;
currentElement = _qualification;
break;
}
}
while (_source.MoveNext(ref element, ref keyUnused));
return true;
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if USE_MDT_EVENTSOURCE
using Microsoft.Diagnostics.Tracing;
#else
using System.Diagnostics.Tracing;
#endif
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace BasicEventSourceTests
{
/// <summary>
/// Tests the user experience for common user errors.
/// </summary>
public partial class TestsUserErrors
{
/// <summary>
/// Try to pass a user defined class (even with EventData)
/// to a manifest based eventSource
/// </summary>
[Fact]
public void Test_BadTypes_Manifest_UserClass()
{
var badEventSource = new BadEventSource_Bad_Type_UserClass();
Test_BadTypes_Manifest(badEventSource);
}
private void Test_BadTypes_Manifest(EventSource source)
{
try
{
using (var listener = new EventListenerListener())
{
var events = new List<Event>();
Debug.WriteLine("Adding delegate to onevent");
listener.OnEvent = delegate (Event data) { events.Add(data); };
listener.EventSourceCommand(source.Name, EventCommand.Enable);
listener.Dispose();
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("EventSourceMessage", _event.EventName);
// Check the exception text if not ProjectN.
if (!PlatformDetection.IsNetNative)
{
string message = _event.PayloadString(0, "message");
// expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. "
Assert.True(Regex.IsMatch(message, "Unsupported type"));
}
}
}
finally
{
source.Dispose();
}
}
/// <summary>
/// Test the
/// </summary>
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // ActiveIssue: https://github.com/dotnet/corefx/issues/29754
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Depends on inspecting IL at runtime.")]
public void Test_BadEventSource_MismatchedIds()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
var onStartups = new bool[] { false, true };
var listenerGenerators = new List<Func<Listener>>();
listenerGenerators.Add(() => new EventListenerListener());
var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat };
// For every interesting combination, run the test and see that we get a nice failure message.
foreach (bool onStartup in onStartups)
{
foreach (Func<Listener> listenerGenerator in listenerGenerators)
{
foreach (EventSourceSettings setting in settings)
{
Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting);
}
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
/// <summary>
/// A helper that can run the test under a variety of conditions
/// * Whether the eventSource is enabled at startup
/// * Whether the listener is ETW or an EventListern
/// * Whether the ETW output is self describing or not.
/// </summary>
private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, EventSourceSettings settings)
{
var eventSourceName = typeof(BadEventSource_MismatchedIds).Name;
Debug.WriteLine("***** Test_BadEventSource_Startup(OnStartUp: " + onStartup + " Listener: " + listener + " Settings: " + settings + ")");
// Activate the source before the source exists (if told to).
if (onStartup)
listener.EventSourceCommand(eventSourceName, EventCommand.Enable);
var events = new List<Event>();
listener.OnEvent = delegate (Event data) { events.Add(data); };
using (var source = new BadEventSource_MismatchedIds(settings))
{
Assert.Equal(eventSourceName, source.Name);
// activate the source after the source exists (if told to).
if (!onStartup)
listener.EventSourceCommand(eventSourceName, EventCommand.Enable);
source.Event1(1); // Try to send something.
}
listener.Dispose();
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("EventSourceMessage", _event.EventName);
string message = _event.PayloadString(0, "message");
Debug.WriteLine(string.Format("Message=\"{0}\"", message));
// expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent. "
if (!PlatformDetection.IsFullFramework) // Full framework has typo
Assert.True(Regex.IsMatch(message, "Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent"));
}
[Fact]
public void Test_Bad_WriteRelatedID_ParameterName()
{
#if true
Debug.WriteLine("Test disabled because the fix it tests is not in CoreCLR yet.");
#else
BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter bes = null;
EventListenerListener listener = null;
try
{
Guid oldGuid;
Guid newGuid = Guid.NewGuid();
Guid newGuid2 = Guid.NewGuid();
EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid);
bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter();
using (var listener = new EventListenerListener())
{
var events = new List<Event>();
listener.OnEvent = delegate (Event data) { events.Add(data); };
listener.EventSourceCommand(bes.Name, EventCommand.Enable);
bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB");
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("EventSourceMessage", _event.EventName);
string message = _event.PayloadString(0, "message");
// expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId."
Assert.True(Regex.IsMatch(message, "EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId."));
}
}
finally
{
if (bes != null)
{
bes.Dispose();
}
if (listener != null)
{
listener.Dispose();
}
}
#endif
}
}
/// <summary>
/// This EventSource has a common user error, and we want to make sure EventSource
/// gives a reasonable experience in that case.
/// </summary>
internal class BadEventSource_MismatchedIds : EventSource
{
public BadEventSource_MismatchedIds(EventSourceSettings settings) : base(settings) { }
public void Event1(int arg) { WriteEvent(1, arg); }
// Error Used the same event ID for this event.
public void Event2(int arg) { WriteEvent(1, arg); }
}
/// <summary>
/// A manifest based provider with a bad type byte[]
/// </summary>
internal class BadEventSource_Bad_Type_ByteArray : EventSource
{
public void Event1(byte[] myArray) { WriteEvent(1, myArray); }
}
public sealed class BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter : EventSource
{
public void E2()
{
this.Write("sampleevent", new { a = "a string" });
}
[Event(7, Keywords = Keywords.Debug, Message = "Hello Message 7", Channel = EventChannel.Admin, Opcode = EventOpcode.Send)]
public void RelatedActivity(Guid guid, string message, int value, string componentName, string instanceId)
{
WriteEventWithRelatedActivityId(7, guid, message, value, componentName, instanceId);
}
public class Keywords
{
public const EventKeywords Debug = (EventKeywords)0x0002;
}
}
[EventData]
public class UserClass
{
public int i;
};
/// <summary>
/// A manifest based provider with a bad type (only supported in self describing)
/// </summary>
internal class BadEventSource_Bad_Type_UserClass : EventSource
{
public void Event1(UserClass myClass) { WriteEvent(1, myClass); }
}
}
| |
// 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBIteratorTests : CSharpPDBTestBase
{
[WorkItem(543376, "DevDiv")]
[Fact]
public void SimpleIterator1()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> Foo()
{
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Foo"">
<customDebugInfo>
<forwardIterator name=""<Foo>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Program+<Foo>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" />
<entry offset=""0x18"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(543376, "DevDiv")]
[Fact]
public void SimpleIterator2()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> Foo()
{
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Foo"">
<customDebugInfo>
<forwardIterator name=""<Foo>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Program+<Foo>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" />
<entry offset=""0x18"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(543490, "DevDiv")]
[Fact]
public void SimpleIterator3()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> Foo()
{
yield return 1; //hidden sequence point after this.
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Foo"">
<customDebugInfo>
<forwardIterator name=""<Foo>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Program+<Foo>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x1f"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" />
<entry offset=""0x20"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""0"" />
<entry offset=""0x30"" hidden=""true"" document=""0"" />
<entry offset=""0x37"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithLocals_ReleasePdb()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> IEI<T>(int i0, int i1)
{
int x = i0;
yield return x;
yield return x;
{
int y = i1;
yield return y;
yield return y;
}
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.ReleaseDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""IEI"" parameterNames=""i0, i1"">
<customDebugInfo>
<forwardIterator name=""<IEI>d__0"" />
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""23"" endLine=""17"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Program+<IEI>d__0`1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x2a"" endOffset=""0xb3"" />
<slot startOffset=""0x6e"" endOffset=""0xb1"" />
</hoistedLocalScopes>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x2a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""20"" document=""0"" />
<entry offset=""0x36"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""0"" />
<entry offset=""0x4b"" hidden=""true"" document=""0"" />
<entry offset=""0x52"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""0"" />
<entry offset=""0x67"" hidden=""true"" document=""0"" />
<entry offset=""0x6e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""24"" document=""0"" />
<entry offset=""0x7a"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" document=""0"" />
<entry offset=""0x8f"" hidden=""true"" document=""0"" />
<entry offset=""0x96"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""28"" document=""0"" />
<entry offset=""0xab"" hidden=""true"" document=""0"" />
<entry offset=""0xb2"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""21"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithLocals_DebugPdb()
{
var text = @"
class Program
{
System.Collections.Generic.IEnumerable<int> IEI<T>(int i0, int i1)
{
int x = i0;
yield return x;
yield return x;
{
int y = i1;
yield return y;
yield return y;
}
yield break;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""IEI"" parameterNames=""i0, i1"">
<customDebugInfo>
<forwardIterator name=""<IEI>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""101"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""21"" endLine=""17"" endColumn=""22"" document=""0"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""23"" endLine=""17"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Program+<IEI>d__0`1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x39"" endOffset=""0xc5"" />
<slot startOffset=""0x7e"" endOffset=""0xc3"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x39"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" />
<entry offset=""0x3a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""20"" document=""0"" />
<entry offset=""0x46"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""0"" />
<entry offset=""0x5b"" hidden=""true"" document=""0"" />
<entry offset=""0x62"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""0"" />
<entry offset=""0x77"" hidden=""true"" document=""0"" />
<entry offset=""0x7e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""0"" />
<entry offset=""0x7f"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""24"" document=""0"" />
<entry offset=""0x8b"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" document=""0"" />
<entry offset=""0xa0"" hidden=""true"" document=""0"" />
<entry offset=""0xa7"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""28"" document=""0"" />
<entry offset=""0xbc"" hidden=""true"" document=""0"" />
<entry offset=""0xc3"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""0"" />
<entry offset=""0xc4"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""21"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithCapturedSyntheticVariables()
{
// this iterator captures the synthetic variable generated from the expansion of the foreach loop
var text = @"// Based on LegacyTest csharp\Source\Conformance\iterators\blocks\using001.cs
using System;
using System.Collections.Generic;
class Test<T>
{
public static IEnumerator<T> M(IEnumerable<T> items)
{
T val = default(T);
foreach (T item in items)
{
val = item;
yield return val;
}
yield return val;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test`1"" name=""M"" parameterNames=""items"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""5"" offset=""42"" />
<slot kind=""0"" offset=""42"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Test`1"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""19"" startColumn=""21"" endLine=""19"" endColumn=""22"" document=""0"" />
<entry offset=""0x1"" startLine=""19"" startColumn=""23"" endLine=""19"" endColumn=""24"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""Test`1+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x32"" endOffset=""0xe1"" />
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0x5b"" endOffset=""0xa4"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x32"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x33"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""28"" document=""0"" />
<entry offset=""0x3f"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""16"" document=""0"" />
<entry offset=""0x40"" startLine=""11"" startColumn=""28"" endLine=""11"" endColumn=""33"" document=""0"" />
<entry offset=""0x59"" hidden=""true"" document=""0"" />
<entry offset=""0x5b"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""24"" document=""0"" />
<entry offset=""0x6c"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""0"" />
<entry offset=""0x6d"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""0"" />
<entry offset=""0x79"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""30"" document=""0"" />
<entry offset=""0x90"" hidden=""true"" document=""0"" />
<entry offset=""0x98"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""0"" />
<entry offset=""0xa5"" startLine=""11"" startColumn=""25"" endLine=""11"" endColumn=""27"" document=""0"" />
<entry offset=""0xc0"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""26"" document=""0"" />
<entry offset=""0xd7"" hidden=""true"" document=""0"" />
<entry offset=""0xde"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" />
<entry offset=""0xe2"" hidden=""true"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(542705, "DevDiv"), WorkItem(528790, "DevDiv"), WorkItem(543490, "DevDiv")]
[Fact()]
public void IteratorBackToNextStatementAfterYieldReturn()
{
var text = @"
using System.Collections.Generic;
class C
{
IEnumerable<decimal> M()
{
const decimal d1 = 0.1M;
yield return d1;
const decimal dx = 1.23m;
yield return dx;
{
const decimal d2 = 0.2M;
yield return d2;
}
yield break;
}
static void Main()
{
foreach (var i in new C().M())
{
System.Console.WriteLine(i);
}
}
}
";
using (new CultureContext("en-US"))
{
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.ReleaseExe);
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
</customDebugInfo>
</method>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""21"" startColumn=""27"" endLine=""21"" endColumn=""38"" document=""0"" />
<entry offset=""0x10"" hidden=""true"" document=""0"" />
<entry offset=""0x12"" startLine=""21"" startColumn=""18"" endLine=""21"" endColumn=""23"" document=""0"" />
<entry offset=""0x18"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""41"" document=""0"" />
<entry offset=""0x1d"" startLine=""21"" startColumn=""24"" endLine=""21"" endColumn=""26"" document=""0"" />
<entry offset=""0x27"" hidden=""true"" document=""0"" />
<entry offset=""0x31"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x32"">
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x26"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""0"" />
<entry offset=""0x3f"" hidden=""true"" document=""0"" />
<entry offset=""0x46"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""25"" document=""0"" />
<entry offset=""0x60"" hidden=""true"" document=""0"" />
<entry offset=""0x67"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""29"" document=""0"" />
<entry offset=""0x80"" hidden=""true"" document=""0"" />
<entry offset=""0x87"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""21"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x89"">
<scope startOffset=""0x26"" endOffset=""0x89"">
<constant name=""d1"" value=""0.1"" type=""Decimal"" />
<constant name=""dx"" value=""1.23"" type=""Decimal"" />
<scope startOffset=""0x67"" endOffset=""0x87"">
<constant name=""d2"" value=""0.2"" type=""Decimal"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>");
}
}
[WorkItem(543490, "DevDiv")]
[Fact()]
public void IteratorMultipleEnumerables()
{
var text = @"
using System;
using System.Collections;
using System.Collections.Generic;
public class Test<T> : IEnumerable<T> where T : class
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
foreach (var v in this.IterProp)
{
yield return v;
}
foreach (var v in IterMethod())
{
yield return v;
}
}
public IEnumerable<T> IterProp
{
get
{
yield return null;
yield return null;
}
}
public IEnumerable<T> IterMethod()
{
yield return default(T);
yield return null;
yield break;
}
}
public class Test
{
public static void Main()
{
foreach (var v in new Test<string>()) { }
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugExe);
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""Test"" methodName=""Main"" />
<methods>
<method containingType=""Test`1"" name=""System.Collections.IEnumerable.GetEnumerator"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""32"" document=""0"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xc"">
<namespace name=""System"" />
<namespace name=""System.Collections"" />
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""Test`1"" name=""GetEnumerator"">
<customDebugInfo>
<forwardIterator name=""<GetEnumerator>d__1"" />
<encLocalSlotMap>
<slot kind=""5"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""5"" offset=""104"" />
<slot kind=""0"" offset=""104"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Test`1"" name=""get_IterProp"">
<customDebugInfo>
<forwardIterator name=""<get_IterProp>d__3"" />
</customDebugInfo>
</method>
<method containingType=""Test`1"" name=""IterMethod"">
<customDebugInfo>
<forwardIterator name=""<IterMethod>d__4"" />
</customDebugInfo>
</method>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<encLocalSlotMap>
<slot kind=""5"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""45"" startColumn=""5"" endLine=""45"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""46"" startColumn=""9"" endLine=""46"" endColumn=""16"" document=""0"" />
<entry offset=""0x2"" startLine=""46"" startColumn=""27"" endLine=""46"" endColumn=""45"" document=""0"" />
<entry offset=""0xd"" hidden=""true"" document=""0"" />
<entry offset=""0xf"" startLine=""46"" startColumn=""18"" endLine=""46"" endColumn=""23"" document=""0"" />
<entry offset=""0x16"" startLine=""46"" startColumn=""47"" endLine=""46"" endColumn=""48"" document=""0"" />
<entry offset=""0x17"" startLine=""46"" startColumn=""49"" endLine=""46"" endColumn=""50"" document=""0"" />
<entry offset=""0x18"" startLine=""46"" startColumn=""24"" endLine=""46"" endColumn=""26"" document=""0"" />
<entry offset=""0x22"" hidden=""true"" document=""0"" />
<entry offset=""0x2d"" startLine=""47"" startColumn=""5"" endLine=""47"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2e"">
<scope startOffset=""0xf"" endOffset=""0x18"">
<local name=""v"" il_index=""1"" il_start=""0xf"" il_end=""0x18"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""Test`1+<GetEnumerator>d__1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0x54"" endOffset=""0x94"" />
<slot startOffset=""0x0"" endOffset=""0x0"" />
<slot startOffset=""0xd1"" endOffset=""0x10e"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x32"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""0"" />
<entry offset=""0x33"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""16"" document=""0"" />
<entry offset=""0x34"" startLine=""15"" startColumn=""27"" endLine=""15"" endColumn=""40"" document=""0"" />
<entry offset=""0x52"" hidden=""true"" document=""0"" />
<entry offset=""0x54"" startLine=""15"" startColumn=""18"" endLine=""15"" endColumn=""23"" document=""0"" />
<entry offset=""0x65"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" />
<entry offset=""0x66"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" document=""0"" />
<entry offset=""0x80"" hidden=""true"" document=""0"" />
<entry offset=""0x88"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""0"" />
<entry offset=""0x95"" startLine=""15"" startColumn=""24"" endLine=""15"" endColumn=""26"" document=""0"" />
<entry offset=""0xb0"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" document=""0"" />
<entry offset=""0xb1"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""39"" document=""0"" />
<entry offset=""0xcf"" hidden=""true"" document=""0"" />
<entry offset=""0xd1"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" document=""0"" />
<entry offset=""0xe2"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" document=""0"" />
<entry offset=""0xe3"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""28"" document=""0"" />
<entry offset=""0xfa"" hidden=""true"" document=""0"" />
<entry offset=""0x102"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""0"" />
<entry offset=""0x10f"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" document=""0"" />
<entry offset=""0x12a"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""0"" />
<entry offset=""0x12e"" hidden=""true"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Test`1+<get_IterProp>d__3"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x2a"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""0"" />
<entry offset=""0x2b"" startLine=""29"" startColumn=""13"" endLine=""29"" endColumn=""31"" document=""0"" />
<entry offset=""0x40"" hidden=""true"" document=""0"" />
<entry offset=""0x47"" startLine=""30"" startColumn=""13"" endLine=""30"" endColumn=""31"" document=""0"" />
<entry offset=""0x5c"" hidden=""true"" document=""0"" />
<entry offset=""0x63"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""10"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Test`1+<IterMethod>d__4"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x2a"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""0"" />
<entry offset=""0x2b"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""33"" document=""0"" />
<entry offset=""0x40"" hidden=""true"" document=""0"" />
<entry offset=""0x47"" startLine=""37"" startColumn=""9"" endLine=""37"" endColumn=""27"" document=""0"" />
<entry offset=""0x5c"" hidden=""true"" document=""0"" />
<entry offset=""0x63"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""21"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void VariablesWithSubstitutedType1()
{
var text = @"
using System.Collections.Generic;
class C
{
static IEnumerable<T> F<T>(T[] o)
{
int i = 0;
T t = default(T);
yield return t;
yield return o[i];
}
}
";
var v = CompileAndVerify(text, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"o", "<>3__o",
"<i>5__1",
"<t>5__2"
}, module.GetFieldNames("C.<F>d__0"));
});
v.VerifyPdb("C+<F>d__0`1.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<F>d__0`1"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x2a"" endOffset=""0x82"" />
<slot startOffset=""0x2a"" endOffset=""0x82"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x2a"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""0"" />
<entry offset=""0x2b"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""0"" />
<entry offset=""0x32"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""0"" />
<entry offset=""0x3e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" />
<entry offset=""0x53"" hidden=""true"" document=""0"" />
<entry offset=""0x5a"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""27"" document=""0"" />
<entry offset=""0x7a"" hidden=""true"" document=""0"" />
<entry offset=""0x81"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x83"">
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void IteratorWithConditionalBranchDiscriminator1()
{
var text = @"
using System.Collections.Generic;
class C
{
static bool B() => false;
static IEnumerable<int> F()
{
if (B())
{
yield return 1;
}
}
}
";
// Note that conditional branch discriminator is not hoisted.
var v = CompileAndVerify(text, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
}, module.GetFieldNames("C.<F>d__1"));
});
v.VerifyIL("C.<F>d__1.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 68 (0x44)
.maxstack 2
.locals init (int V_0,
bool V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__1.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003a
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__1.<>1__state""
IL_001f: nop
IL_0020: call ""bool C.B()""
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: brfalse.s IL_0042
IL_0029: nop
IL_002a: ldarg.0
IL_002b: ldc.i4.1
IL_002c: stfld ""int C.<F>d__1.<>2__current""
IL_0031: ldarg.0
IL_0032: ldc.i4.1
IL_0033: stfld ""int C.<F>d__1.<>1__state""
IL_0038: ldc.i4.1
IL_0039: ret
IL_003a: ldarg.0
IL_003b: ldc.i4.m1
IL_003c: stfld ""int C.<F>d__1.<>1__state""
IL_0041: nop
IL_0042: ldc.i4.0
IL_0043: ret
}
");
v.VerifyPdb("C+<F>d__1.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<F>d__1"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x1f"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x20"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""17"" document=""0"" />
<entry offset=""0x26"" hidden=""true"" document=""0"" />
<entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""0"" />
<entry offset=""0x2a"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" document=""0"" />
<entry offset=""0x3a"" hidden=""true"" document=""0"" />
<entry offset=""0x41"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""0"" />
<entry offset=""0x42"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x44"">
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SynthesizedVariables1()
{
var source =
@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> M(IDisposable disposable)
{
foreach (var item in new[] { 1, 2, 3 }) { lock (this) { yield return 1; } }
foreach (var item in new[] { 1, 2, 3 }) { }
lock (this) { yield return 2; }
if (disposable != null) { using (disposable) { yield return 3; } }
lock (this) { yield return 4; }
if (disposable != null) { using (disposable) { } }
lock (this) { }
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<>4__this",
"disposable",
"<>3__disposable",
"<>7__wrap1",
"<>7__wrap2",
"<>7__wrap3",
"<>7__wrap4",
"<>7__wrap5",
}, module.GetFieldNames("C.<M>d__0"));
});
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"disposable",
"<>3__disposable",
"<>4__this",
"<>s__1",
"<>s__2",
"<item>5__3",
"<>s__4",
"<>s__5",
"<>s__6",
"<>s__7",
"<item>5__8",
"<>s__9",
"<>s__10",
"<>s__11",
"<>s__12",
"<>s__13",
"<>s__14",
"<>s__15",
"<>s__16"
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""disposable"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""3"" offset=""53"" />
<slot kind=""2"" offset=""53"" />
<slot kind=""6"" offset=""96"" />
<slot kind=""8"" offset=""96"" />
<slot kind=""0"" offset=""96"" />
<slot kind=""3"" offset=""149"" />
<slot kind=""2"" offset=""149"" />
<slot kind=""4"" offset=""216"" />
<slot kind=""3"" offset=""266"" />
<slot kind=""2"" offset=""266"" />
<slot kind=""4"" offset=""333"" />
<slot kind=""3"" offset=""367"" />
<slot kind=""2"" offset=""367"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DisplayClass_AccrossSuspensionPoints_Debug()
{
string source = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
yield return x1 + x2 + x3;
yield return x1 + x2 + x3;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<>8__1", // hoisted display class
}, module.GetFieldNames("C.<M>d__0"));
});
// One iterator local entry for the lambda local.
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c__DisplayClass0_0"" methodName=""<M>b__0"" />
<hoistedLocalScopes>
<slot startOffset=""0x30"" endOffset=""0xea"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x30"" hidden=""true"" document=""0"" />
<entry offset=""0x3b"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x3c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x48"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" />
<entry offset=""0x54"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" />
<entry offset=""0x60"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" />
<entry offset=""0x77"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""35"" document=""0"" />
<entry offset=""0xa9"" hidden=""true"" document=""0"" />
<entry offset=""0xb0"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""35"" document=""0"" />
<entry offset=""0xe2"" hidden=""true"" document=""0"" />
<entry offset=""0xe9"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DisplayClass_InBetweenSuspensionPoints_Release()
{
string source = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
yield return 1;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
// TODO: Currently we don't have means necessary to pass information about the display
// class being pushed on evaluation stack, so that EE could find the locals.
// Thus the locals are not available in EE.
var v = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyIL("C.<M>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 90 (0x5a)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<M>d__0.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0010
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq.s IL_0051
IL_000e: ldc.i4.0
IL_000f: ret
IL_0010: ldarg.0
IL_0011: ldc.i4.m1
IL_0012: stfld ""int C.<M>d__0.<>1__state""
IL_0017: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_001c: dup
IL_001d: ldc.i4.1
IL_001e: stfld ""byte C.<>c__DisplayClass0_0.x1""
IL_0023: dup
IL_0024: ldc.i4.1
IL_0025: stfld ""byte C.<>c__DisplayClass0_0.x2""
IL_002a: dup
IL_002b: ldc.i4.1
IL_002c: stfld ""byte C.<>c__DisplayClass0_0.x3""
IL_0031: ldftn ""void C.<>c__DisplayClass0_0.<M>b__0()""
IL_0037: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_003c: callvirt ""void System.Action.Invoke()""
IL_0041: ldarg.0
IL_0042: ldc.i4.1
IL_0043: stfld ""int C.<M>d__0.<>2__current""
IL_0048: ldarg.0
IL_0049: ldc.i4.1
IL_004a: stfld ""int C.<M>d__0.<>1__state""
IL_004f: ldc.i4.1
IL_0050: ret
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: stfld ""int C.<M>d__0.<>1__state""
IL_0058: ldc.i4.0
IL_0059: ret
}
");
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" hidden=""true"" document=""0"" />
<entry offset=""0x1c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x23"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" />
<entry offset=""0x2a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" />
<entry offset=""0x31"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" />
<entry offset=""0x41"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""24"" document=""0"" />
<entry offset=""0x51"" hidden=""true"" document=""0"" />
<entry offset=""0x58"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void DisplayClass_InBetweenSuspensionPoints_Debug()
{
string source = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
byte x1 = 1;
byte x2 = 1;
byte x3 = 1;
((Action)(() => { x1 = x2 = x3; }))();
yield return 1;
// Possible EnC edit - add lambda:
// () => { x1 }
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
// We need to hoist display class variable to allow adding a new lambda after yield return
// that shares closure with the existing lambda.
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<>8__1", // hoisted display class
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyIL("C.<M>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 127 (0x7f)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<M>d__0.<>1__state""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_0076
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<M>d__0.<>1__state""
IL_001f: ldarg.0
IL_0020: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0025: stfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_002a: nop
IL_002b: ldarg.0
IL_002c: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_0031: ldc.i4.1
IL_0032: stfld ""byte C.<>c__DisplayClass0_0.x1""
IL_0037: ldarg.0
IL_0038: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_003d: ldc.i4.1
IL_003e: stfld ""byte C.<>c__DisplayClass0_0.x2""
IL_0043: ldarg.0
IL_0044: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_0049: ldc.i4.1
IL_004a: stfld ""byte C.<>c__DisplayClass0_0.x3""
IL_004f: ldarg.0
IL_0050: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1""
IL_0055: ldftn ""void C.<>c__DisplayClass0_0.<M>b__0()""
IL_005b: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_0060: callvirt ""void System.Action.Invoke()""
IL_0065: nop
IL_0066: ldarg.0
IL_0067: ldc.i4.1
IL_0068: stfld ""int C.<M>d__0.<>2__current""
IL_006d: ldarg.0
IL_006e: ldc.i4.1
IL_006f: stfld ""int C.<M>d__0.<>1__state""
IL_0074: ldc.i4.1
IL_0075: ret
IL_0076: ldarg.0
IL_0077: ldc.i4.m1
IL_0078: stfld ""int C.<M>d__0.<>1__state""
IL_007d: ldc.i4.0
IL_007e: ret
}
");
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x1f"" endOffset=""0x7e"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x1f"" hidden=""true"" document=""0"" />
<entry offset=""0x2a"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x2b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x37"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" />
<entry offset=""0x43"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" />
<entry offset=""0x4f"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" />
<entry offset=""0x66"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""24"" document=""0"" />
<entry offset=""0x76"" hidden=""true"" document=""0"" />
<entry offset=""0x7d"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""95"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[Fact]
public void DynamicLocal_AccrossSuspensionPoints_Debug()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
dynamic d = 1;
yield return d;
d.ToString();
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<d>5__1"
}, module.GetFieldNames("C.<M>d__0"));
});
// CHANGE: Dev12 emits a <dynamiclocal> entry for "d", but gives it slot "-1", preventing it from matching
// any locals when consumed by the EE (i.e. it has no effect). See FUNCBRECEE::IsLocalDynamic.
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x1f"" endOffset=""0xe2"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x20"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" />
<entry offset=""0x2c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" />
<entry offset=""0x82"" hidden=""true"" document=""0"" />
<entry offset=""0x89"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""22"" document=""0"" />
<entry offset=""0xe1"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
v.VerifyPdb("C.M", @"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""<M>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[WorkItem(836491, "DevDiv")]
[WorkItem(827337, "DevDiv")]
[WorkItem(1070519, "DevDiv")]
[Fact]
public void DynamicLocal_InBetweenSuspensionPoints_Release()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
dynamic d = 1;
yield return d;
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""d"" />
</dynamicLocals>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" />
<entry offset=""0x1e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" />
<entry offset=""0x6d"" hidden=""true"" document=""0"" />
<entry offset=""0x74"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x76"">
<scope startOffset=""0x17"" endOffset=""0x76"">
<local name=""d"" il_index=""1"" il_start=""0x17"" il_end=""0x76"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(1070519, "DevDiv")]
[Fact]
public void DynamicLocal_InBetweenSuspensionPoints_Debug()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> M()
{
dynamic d = 1;
yield return d;
// Possible EnC edit:
// System.Console.WriteLine(d);
}
public void F() { } // needs to be present to work around SymWriter bug #1068894
}
";
var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state",
"<>2__current",
"<>l__initialThreadId",
"<d>5__1",
}, module.GetFieldNames("C.<M>d__0"));
});
v.VerifyPdb("C+<M>d__0.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<M>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<hoistedLocalScopes>
<slot startOffset=""0x1f"" endOffset=""0x8a"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x20"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" />
<entry offset=""0x2c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" />
<entry offset=""0x82"" hidden=""true"" document=""0"" />
<entry offset=""0x89"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact, WorkItem(667579, "DevDiv")]
public void DebuggerHiddenIterator()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Diagnostics;
class C
{
static void Main(string[] args)
{
foreach (var x in F()) ;
}
[DebuggerHidden]
static IEnumerable<int> F()
{
throw new Exception();
yield break;
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll);
c.VerifyPdb("C+<F>d__1.MoveNext", @"
<symbols>
<methods>
<method containingType=""C+<F>d__1"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""0"" />
<entry offset=""0x18"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace RdrLib
{
public enum Reason
{
None,
Success,
WebError,
Timeout,
FileExists,
Canceled,
CompressionError,
Unknown
}
public interface IResponse
{
Reason Reason { get; }
HttpStatusCode? Status { get; set; }
Exception? Exception { get; set; }
}
public class StringResponse : IResponse
{
private readonly Uri uri;
public Reason Reason { get; } = Reason.None;
public HttpStatusCode? Status { get; set; } = null;
public Exception? Exception { get; set; } = null;
public string Text { get; set; } = string.Empty;
public StringResponse(Uri uri, Reason reason)
{
this.uri = uri;
Reason = reason;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine(uri.AbsoluteUri);
sb.AppendLine(Status.HasValue ? Status.Value.ToString() : "no status code");
sb.AppendLine($"reason: {Reason}");
sb.AppendLine($"string length: {Text.Length.ToString(CultureInfo.CurrentCulture)}");
return sb.ToString();
}
}
public class DataResponse : IResponse
{
private readonly Uri uri;
public Reason Reason { get; } = Reason.None;
public HttpStatusCode? Status { get; set; } = null;
public Exception? Exception { get; set; } = null;
public ReadOnlyMemory<byte> Data { get; set; } = new ReadOnlyMemory<byte>();
public DataResponse(Uri uri, Reason reason)
{
this.uri = uri;
Reason = reason;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine($"uri: {uri.AbsoluteUri}");
sb.AppendLine(Status.HasValue ? Status.Value.ToString() : "no status code");
sb.AppendLine($"reason: {Reason}");
sb.AppendLine($"data length: {Data.Length.ToString(CultureInfo.CurrentCulture)}");
return sb.ToString();
}
}
public class FileResponse : IResponse
{
private readonly Uri uri;
private readonly string path;
public Reason Reason { get; } = Reason.None;
public HttpStatusCode? Status { get; set; } = null;
public Exception? Exception { get; set; } = null;
public FileResponse(Uri uri, string path, Reason reason)
{
this.uri = uri;
this.path = path;
Reason = reason;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(base.ToString());
sb.AppendLine($"uri: {uri.AbsoluteUri}");
sb.AppendLine($"path: {path}");
sb.AppendLine(Status.HasValue ? Status.Value.ToString() : "no status code");
sb.AppendLine($"reason: {Reason}");
return sb.ToString();
}
}
public class FileProgress
{
public Int64 BytesWritten { get; } = 0L;
public Int64 TotalBytesWritten { get; } = 0L;
public Int64? ContentLength { get; } = -1L;
public FileProgress(Int64 bytesWritten, Int64 totalBytesWritten)
: this(bytesWritten, totalBytesWritten, null)
{ }
public FileProgress(Int64 bytesWritten, Int64 totalBytesWritten, Int64? contentLength)
{
BytesWritten = bytesWritten;
TotalBytesWritten = totalBytesWritten;
ContentLength = contentLength;
}
public decimal? GetPercent()
{
if (GetDownloadRatio() is decimal ratio)
{
return ratio * 100m;
}
else
{
return null;
}
}
[System.Diagnostics.DebuggerStepThrough]
public string? GetPercentFormatted() => GetPercentFormatted(CultureInfo.CurrentCulture);
public string? GetPercentFormatted(CultureInfo ci)
{
if (GetDownloadRatio() is decimal ratio)
{
string percentFormat = GetPercentFormatString(ci);
return ratio.ToString(percentFormat);
}
else
{
return null;
}
}
private decimal? GetDownloadRatio()
{
if (!ContentLength.HasValue)
{
return null;
}
return Convert.ToDecimal(TotalBytesWritten) / Convert.ToDecimal(ContentLength.Value);
}
private static string GetPercentFormatString(CultureInfo ci)
{
string separator = ci.NumberFormat.PercentDecimalSeparator;
string symbol = ci.NumberFormat.PercentSymbol;
return string.Format(ci, "0{0}00 {1}", separator, symbol);
}
}
public static class Web
{
private static readonly HttpClientHandler handler = new HttpClientHandler
{
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
MaxAutomaticRedirections = 5,
SslProtocols = SslProtocols.Tls12
};
private static readonly HttpClient client = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(10d)
};
[System.Diagnostics.DebuggerStepThrough]
public static Task<StringResponse> DownloadStringAsync(Uri uri)
=> DownloadStringAsync(uri, null);
public static async Task<StringResponse> DownloadStringAsync(Uri uri, Action<HttpRequestMessage>? configureRequest)
{
HttpRequestMessage request = new HttpRequestMessage()
{
RequestUri = uri
};
configureRequest?.Invoke(request);
HttpResponseMessage? response = null;
try
{
response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
string text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new StringResponse(uri, Reason.Success)
{
Status = response.StatusCode,
Text = text
};
}
catch (HttpRequestException ex)
{
return new StringResponse(uri, Reason.WebError)
{
Status = response?.StatusCode ?? null,
Text = ex.Message,
Exception = ex
};
}
catch (TaskCanceledException ex)
{
return new StringResponse(uri, Reason.Timeout)
{
Exception = ex
};
}
catch (OperationCanceledException ex)
{
return new StringResponse(uri, Reason.WebError)
{
Exception = ex
};
}
finally
{
request?.Dispose();
response?.Dispose();
}
}
[System.Diagnostics.DebuggerStepThrough]
public static Task<DataResponse> DownloadDataAsync(Uri uri)
=> DownloadDataAsync(uri, null);
public static async Task<DataResponse> DownloadDataAsync(Uri uri, Action<HttpRequestMessage>? configureRequest)
{
HttpRequestMessage request = new HttpRequestMessage()
{
RequestUri = uri
};
configureRequest?.Invoke(request);
HttpResponseMessage? response = null;
try
{
response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
ReadOnlyMemory<byte> data = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
return new DataResponse(uri, Reason.Success)
{
Status = response.StatusCode,
Data = data
};
}
catch (HttpRequestException ex)
{
return new DataResponse(uri, Reason.WebError)
{
Status = response?.StatusCode ?? null,
Exception = ex
};
}
catch (InvalidDataException ex)
{
return new DataResponse(uri, Reason.CompressionError)
{
Status = response?.StatusCode ?? null,
Exception = ex
};
}
catch (TaskCanceledException ex)
{
return new DataResponse(uri, Reason.Timeout)
{
Exception = ex
};
}
catch (OperationCanceledException ex)
{
return new DataResponse(uri, Reason.WebError)
{
Exception = ex
};
}
finally
{
request?.Dispose();
response?.Dispose();
}
}
[System.Diagnostics.DebuggerStepThrough]
public static Task<FileResponse> DownloadFileAsync(Uri uri, string path)
=> DownloadFileAsync(uri, path, null, null, CancellationToken.None);
[System.Diagnostics.DebuggerStepThrough]
public static Task<FileResponse> DownloadFileAsync(Uri uri, string path, Action<HttpRequestMessage> configureRequest)
=> DownloadFileAsync(uri, path, configureRequest, null, CancellationToken.None);
[System.Diagnostics.DebuggerStepThrough]
public static Task<FileResponse> DownloadFileAsync(Uri uri, string path, IProgress<FileProgress> progress)
=> DownloadFileAsync(uri, path, null, progress, CancellationToken.None);
public static async Task<FileResponse> DownloadFileAsync(Uri uri, string path, Action<HttpRequestMessage>? configureRequest, IProgress<FileProgress>? progress, CancellationToken token)
{
if (String.IsNullOrWhiteSpace(path)) { throw new ArgumentException("path cannot be NullOrWhiteSpace", nameof(path)); }
if (File.Exists(path)) { return new FileResponse(uri, path, Reason.FileExists); }
string inProgressPath = GetExtension(path, "inprogress");
FileResponse? fileResponse = null;
HttpRequestMessage request = new HttpRequestMessage()
{
RequestUri = uri
};
configureRequest?.Invoke(request);
HttpResponseMessage? response = null;
int receiveBufferSize = 1024 * 1024; // 1024 * 1024 = 1 MiB
int saveBufferSize = 4096 * 16;
Stream? receive = null;
Stream? save = new FileStream(inProgressPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, saveBufferSize, FileOptions.Asynchronous);
int bytesRead = 0;
byte[] buffer = new byte[receiveBufferSize];
Int64 totalBytesWritten = 0L;
Int64 prevTotalBytesWritten = 0L;
Int64 progressReportThreshold = 1024L * 100L; // 1024 * 100 = 100 KiB
try
{
response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
Int64? contentLength = response.Content.Headers.ContentLength;
receive = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
while ((bytesRead = await receive.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false)) > 0)
{
await save.WriteAsync(buffer, 0, bytesRead, token).ConfigureAwait(false);
totalBytesWritten += bytesRead;
if (progress != null)
{
if ((totalBytesWritten - prevTotalBytesWritten) > progressReportThreshold)
{
FileProgress fileProgress = new FileProgress(bytesRead, totalBytesWritten, contentLength);
progress.Report(fileProgress);
prevTotalBytesWritten = totalBytesWritten;
}
}
}
await save.FlushAsync().ConfigureAwait(false);
fileResponse = new FileResponse(uri, path, Reason.Success)
{
Status = response.StatusCode
};
}
catch (HttpRequestException ex)
{
fileResponse = new FileResponse(uri, path, Reason.WebError)
{
Status = response?.StatusCode ?? null,
Exception = ex
};
}
catch (IOException ex)
{
// IOException is thrown by FileStream with FileMode.CreateNew if the file already exists
// it might be thrown by other things as well
fileResponse = new FileResponse(uri, path, Reason.FileExists)
{
Exception = ex
};
}
catch (TaskCanceledException ex)
{
fileResponse = new FileResponse(uri, path, Reason.Canceled)
{
Exception = ex
};
}
catch (OperationCanceledException ex)
{
fileResponse = new FileResponse(uri, path, Reason.WebError)
{
Exception = ex
};
}
finally
{
request?.Dispose();
response?.Dispose();
receive?.Dispose();
save?.Dispose();
}
// probably unnecessary to wait beyond the finally, but eh, why not?
await Task.Delay(TimeSpan.FromMilliseconds(150d), token).ConfigureAwait(false);
string finalPath = fileResponse.Reason switch
{
Reason.Success => path,
Reason.WebError => GetExtension(path, "error"),
Reason.Canceled => GetExtension(path, "canceled"),
_ => GetExtension(path, "failed")
};
File.Move(inProgressPath, finalPath);
return fileResponse;
}
private static string GetExtension(string path, string extension)
{
Directory.CreateDirectory(new FileInfo(path).DirectoryName);
string newPath = $"{path}.{extension}";
if (!File.Exists(newPath))
{
return newPath;
}
for (int i = 1; i < 100; i++)
{
string nextAttemptedPath = $"{newPath}{i}";
if (!File.Exists(nextAttemptedPath))
{
return nextAttemptedPath;
}
}
return $"{path}{Guid.NewGuid()}";
}
}
}
| |
// ***********************************************************************
// Assembly : ACBr.Net.Sat
// Author : RFTD
// Created : 04-28-2016
//
// Last Modified By : RFTD
// Last Modified On : 04-28-2016
// ***********************************************************************
// <copyright file="infCFe.cs" company="ACBr.Net">
// The MIT License (MIT)
// Copyright (c) 2016 Grupo ACBr.Net
//
// 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>
// <summary></summary>
// ***********************************************************************
using ACBr.Net.Core.Extensions;
using ACBr.Net.DFe.Core.Attributes;
using ACBr.Net.DFe.Core.Serializer;
using PropertyChanged;
using System.Linq;
namespace ACBr.Net.Sat
{
/// <summary>
/// Class infCFe.
/// </summary>
[ImplementPropertyChanged]
public sealed class InfCFe
{
#region Fields
private CFe parent;
private CFeDetCollection det;
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="InfCFe"/> class.
/// </summary>
public InfCFe()
{
Ide = new CFeIde();
Emit = new CFeEmit();
Dest = new CFeDest();
Entrega = new CFeEntrega();
Det = new CFeDetCollection();
Total = new CFeTotal();
Pagto = new CFePgto();
InfAdic = new CFeInfAdic();
}
/// <summary>
/// Initializes a new instance of the <see cref="CFe" /> class.
/// </summary>
/// <returns>CFe.</returns>
public InfCFe(CFe parent) : this()
{
Parent = parent;
Det = new CFeDetCollection(Parent);
}
#endregion Constructor
#region Propriedades
/// <summary>
/// Gets the parent.
/// </summary>
/// <value>The parent.</value>
[DFeIgnore]
internal CFe Parent
{
get { return parent; }
set
{
parent = value;
Det.Parent = value;
}
}
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>The identifier.</value>
[DFeAttribute(TipoCampo.Str, "Id")]
public string Id { get; set; }
/// <summary>
/// Gets the versao.
/// </summary>
/// <value>The versao.</value>
[DFeAttribute(TipoCampo.De2, "versao", Min = 4, Max = 9, Ocorrencia = Ocorrencia.MaiorQueZero)]
public decimal Versao { get; set; }
/// <summary>
/// Gets the versao dados ent.
/// </summary>
/// <value>The versao dados ent.</value>
[DFeAttribute(TipoCampo.De2, "versaoDadosEnt", Min = 4, Max = 9, Ocorrencia = Ocorrencia.MaiorQueZero)]
public decimal VersaoDadosEnt { get; set; }
/// <summary>
/// Gets the versao sb.
/// </summary>
/// <value>The versao sb.</value>
[DFeAttribute(TipoCampo.De2, "versaoSB", Ocorrencia = Ocorrencia.MaiorQueZero)]
public decimal VersaoSb { get; set; }
/// <summary>
/// Gets the IDE.
/// </summary>
/// <value>The IDE.</value>
[DFeElement("ide", Id = "B01", Ocorrencia = Ocorrencia.Obrigatoria)]
public CFeIde Ide { get; set; }
/// <summary>
/// Gets the emit.
/// </summary>
/// <value>The emit.</value>
[DFeElement("emit", Id = "C01", Ocorrencia = Ocorrencia.Obrigatoria)]
public CFeEmit Emit { get; set; }
/// <summary>
/// Gets the dest.
/// </summary>
/// <value>The dest.</value>
[DFeElement("dest", Id = "E01", Ocorrencia = Ocorrencia.Obrigatoria)]
public CFeDest Dest { get; set; }
/// <summary>
/// Gets the entrega.
/// </summary>
/// <value>The entrega.</value>
[DFeElement("entrega", Id = "G01", Ocorrencia = Ocorrencia.NaoObrigatoria)]
public CFeEntrega Entrega { get; set; }
/// <summary>
/// Gets the det.
/// </summary>
/// <value>The det.</value>
[DFeCollection("det", Id = "H01", MinSize = 1, MaxSize = 500)]
public CFeDetCollection Det
{
get { return det; }
set
{
det = value;
if (det.Parent != parent)
{
det.Parent = parent;
}
}
}
/// <summary>
/// Gets the total.
/// </summary>
/// <value>The total.</value>
[DFeElement("total", Id = "W01", Ocorrencia = Ocorrencia.Obrigatoria)]
public CFeTotal Total { get; set; }
/// <summary>
/// Gets the pgto.
/// </summary>
/// <value>The pgto.</value>
[DFeElement("pgto", Id = "WA01", Ocorrencia = Ocorrencia.Obrigatoria)]
public CFePgto Pagto { get; set; }
/// <summary>
/// Gets the inf adic.
/// </summary>
/// <value>The inf adic.</value>
[DFeElement("infAdic", Id = "Z01", Ocorrencia = Ocorrencia.Obrigatoria)]
public CFeInfAdic InfAdic { get; set; }
#endregion Propriedades
#region Methods
private bool ShouldSerializeId()
{
return !Id.IsEmpty();
}
private bool ShouldSerializeEntrega()
{
return !Entrega.XLgr.IsEmpty() ||
!Entrega.Nro.IsEmpty() ||
!Entrega.XCpl.IsEmpty() ||
!Entrega.XBairro.IsEmpty() ||
!Entrega.XMun.IsEmpty() ||
!Entrega.UF.IsEmpty();
}
private bool ShouldSerializeInfAdic()
{
return !InfAdic.InfCpl.IsEmpty() || InfAdic.ObsFisco.Any();
}
#endregion Methods
}
}
| |
// 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.Reflection;
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 ConvertToVector256Int64UInt16()
{
var test = new SimpleUnaryOpTest__ConvertToVector256Int64UInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using the pointer overload
test.RunBasicScenario_Ptr();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using the pointer overload
test.RunReflectionScenario_Ptr();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ConvertToVector256Int64UInt16
{
private const int VectorSize = 32;
private const int Op1ElementCount = 16 / sizeof(UInt16);
private const int RetElementCount = VectorSize / sizeof(Int64);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector128<UInt16> _clsVar;
private Vector128<UInt16> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt16> _dataTable;
static SimpleUnaryOpTest__ConvertToVector256Int64UInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), 16);
}
public SimpleUnaryOpTest__ConvertToVector256Int64UInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), 16);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt16>(_data, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ConvertToVector256Int64(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Ptr()
{
var result = Avx2.ConvertToVector256Int64(
(UInt16*)(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ConvertToVector256Int64(
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ConvertToVector256Int64(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Ptr()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(UInt16*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArrayPtr, typeof(UInt16*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ConvertToVector256Int64(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr);
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ConvertToVector256Int64UInt16();
var result = Avx2.ConvertToVector256Int64(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ConvertToVector256Int64(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), 16);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
if (result[0] != firstOp[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != firstOp[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ConvertToVector256Int64)}<UInt64>(Vector128<UInt16>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;
namespace System.Runtime.InteropServices
{
public static partial class Marshal
{
public static int GetHRForException(Exception? e)
{
return e?.HResult ?? 0;
}
public static int AddRef(IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool AreComObjectsAvailableForCleanup() => false;
public static IntPtr CreateAggregatedObject(IntPtr pOuter, object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object BindToMoniker(string monikerName)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void CleanupUnusedObjectsInCurrentContext()
{
}
public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o) where T : notnull
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object? CreateWrapperOfType(object? o, Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static TWrapper CreateWrapperOfType<T, TWrapper>([AllowNull] T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void ChangeWrapperHandleStrength(object otp, bool fIsWeak)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int FinalReleaseComObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetComInterfaceForObject(object o, Type T)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetComInterfaceForObject<T, TInterface>([DisallowNull] T o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object? GetComObjectData(object obj, object key)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static IntPtr GetHINSTANCE(Module m)
{
if (m is null)
{
throw new ArgumentNullException(nameof(m));
}
return (IntPtr)(-1);
}
public static IntPtr GetIUnknownForObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void GetNativeVariantForObject(object? obj, IntPtr pDstNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void GetNativeVariantForObject<T>([AllowNull] T obj, IntPtr pDstNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetTypedObjectForIUnknown(IntPtr pUnk, Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetObjectForIUnknown(IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object? GetObjectForNativeVariant(IntPtr pSrcNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
[return: MaybeNull]
public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object?[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int GetStartComSlot(Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int GetEndComSlot(Type t)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Type GetTypeFromCLSID(Guid clsid)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static string GetTypeInfoName(ITypeInfo typeInfo)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetUniqueObjectForIUnknown(IntPtr unknown)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool IsComObject(object o)
{
if (o is null)
{
throw new ArgumentNullException(nameof(o));
}
return false;
}
public static bool IsTypeVisibleFromCom(Type t)
{
if (t is null)
{
throw new ArgumentNullException(nameof(t));
}
return false;
}
public static int QueryInterface(IntPtr pUnk, ref Guid iid, out IntPtr ppv)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int Release(IntPtr pUnk)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int ReleaseComObject(object o)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool SetComObjectData(object obj, object key, object? data)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using CSR.Parser;
namespace CSR.AST
{
/// <summary>
/// Abstract Expression class from which all other expressions inherit
/// </summary>
abstract class Expression
{
// Token is remembered for error reporting
public Token t;
// Return type (since all expressions, by definition, return a value)
public BaseType returnType;
/// <summary>
/// Evaluates this node and all its children
/// </summary>
/// <param name="scope">The scope of this expression</param>
/// <returns></returns>
public abstract Expression Evaluate(Scope scope);
/// <summary>
/// Emits code for this expression
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
public abstract void EmitCode(ILGenerator ilGen, Scope scope);
}
/// <summary>
/// ConstantExpression represents a literal value in the source code
/// </summary>
class ConstantExpression : Expression
{
// Value object (can be of any supported primitive type)
public object value;
/// <summary>
/// Creates a new ConstantExpression given a primitive type and a token
/// </summary>
/// <param name="type">Constant type</param>
/// <param name="t">Token containing value</param>
public ConstantExpression(Primitive type, Token t)
{
// Set return type and token
this.returnType = new PrimitiveType(type);
this.t = t;
// Processing is selected based on type
switch (type)
{
// Process string
case Primitive.String:
// Format string replacing escape characters
value = FormatString(t.val);
break;
// Process integer
case Primitive.Int:
try
{
// Attempt parsing the value of the token
value = Int32.Parse(t.val, NumberFormatInfo.InvariantInfo);
}
catch
{
value = 0;
// Invalid integer literal
Compiler.Compiler.errors.SemErr(t.line, t.col, "Invalid integer literal");
}
break;
// Process double
case Primitive.Double:
try
{
// Attempt parsing the value of the token
value = Double.Parse(t.val, NumberFormatInfo.InvariantInfo);
}
catch
{
value = 0;
// Invalid double literal
Compiler.Compiler.errors.SemErr(t.line, t.col, "Invalid double literal");
}
break;
// Process boolean
case Primitive.Bool:
try
{
// Attempt parsing the value of the token
value = Boolean.Parse(t.val);
}
catch
{
// Invalid boolean literal
Compiler.Compiler.errors.SemErr(t.line, t.col, "Invalid boolean literal");
}
break;
default:
break;
}
}
/// <summary>
/// Creates a new ConstantExpression given a primitive type and a string
/// </summary>
/// <param name="type">Constant type</param>
/// <param name="val">Value of constant as string</param>
public ConstantExpression(Primitive type, string val)
{
// Since this is used internally by the tree evaluator and optimizer, literals are guaranteed to be valid.
// No token info is saved and no error handling is needed
this.returnType = new PrimitiveType(type);
// Processing is selected based on type
switch (type)
{
// Process string
case Primitive.String:
value = FormatString(val);
break;
// Process integer
case Primitive.Int:
value = Int32.Parse(val, NumberFormatInfo.InvariantInfo);
break;
// Process double
case Primitive.Double:
value = Double.Parse(val, NumberFormatInfo.InvariantInfo);
break;
// Process boolean
case Primitive.Bool:
value = Boolean.Parse(val);
break;
default:
break;
}
}
/// <summary>
/// Creates a new ConstantExpression given a primitive type and an object
/// </summary>
/// <param name="type">Constant type</param>
/// <param name="obj">Value as an object</param>
public ConstantExpression(Primitive type, object obj)
: this(type, obj.ToString())
{
}
/// <summary>
/// Evaluates this node and all its children
/// </summary>
/// <param name="scope">The scope of this expression</param>
/// <returns></returns>
public override Expression Evaluate(Scope scope)
{
// Return type is set in constructor
// No changes needed
return this;
}
/// <summary>
/// Determins wheather this constant expression evaluates to a non-zero value
/// </summary>
/// <returns></returns>
public bool IsTrue()
{
// Evaluation is done depending on type
switch (((PrimitiveType)returnType).type)
{
case Primitive.Bool:
// For booleans, the object is just typecasted
return (bool)value;
case Primitive.Double:
// For doubles, the object is typecasted and compared to 0
return (double)value != 0;
case Primitive.Int:
// For integers, the object is typecasted and compared to 0
return (int)value != 0;
case Primitive.String:
// For strings, object must not be null
return value != null;
case Primitive.Unsupported:
case Primitive.Void:
// If constant is void or type is unsupported, return false
return false;
}
return false;
}
/// <summary>
/// Emits code for this expression
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Code generation method is determined depending on type
switch (((PrimitiveType)returnType).type)
{
// Emit code for boolean value
case Primitive.Bool:
if ((bool)value)
{
// If boolean is true, load 1 onto the stack (the CLR doesn't have boolean types)
ilGen.Emit(OpCodes.Ldc_I4_1);
}
else
{
// If boolean is false, load 0 onto the stack
ilGen.Emit(OpCodes.Ldc_I4_0);
}
break;
// Emit code for string
case Primitive.String:
// Load string onto the stack
ilGen.Emit(OpCodes.Ldstr, (string)value);
break;
// Emit code for integer value
case Primitive.Int:
// Cast to int
int val = (int)value;
// Perform CLR dependent optimiztion - use short form int constant loading
switch (val)
{
case 0:
ilGen.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
ilGen.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
ilGen.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
ilGen.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
ilGen.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
ilGen.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
ilGen.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
ilGen.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
ilGen.Emit(OpCodes.Ldc_I4_8);
break;
default:
// If constant is greater than 8, use normal load instruction
ilGen.Emit(OpCodes.Ldc_I4, (int)value);
break;
}
break;
// Emit code for double
case Primitive.Double:
// Load double value onto the stack
ilGen.Emit(OpCodes.Ldc_R8, (double)value);
break;
default:
break;
}
}
/// <summary>
/// Formats a string by removing first and last characters (") and replacing escape characters with theri respective
/// values
/// </summary>
/// <param name="str">String to format</param>
/// <returns></returns>
private string FormatString(string str)
{
// Trim quotes
string tmp = str.Substring(1, str.Length - 2);
// Formatted string
string formatted = "";
int i = 0;
// Format string replacing escape characters \\, \r, \n, \t and \" with their respective single character values
while (i < tmp.Length)
{
// If current character is different than \, add it to the formatted string
if (tmp[i] != '\\')
{
formatted += tmp[i];
i++;
}
else
{
i++;
// Process escaped characters
switch (tmp[i])
{
case '\\':
formatted += '\\';
break;
case 'r':
formatted += '\r';
break;
case 'n':
formatted += '\n';
break;
case 't':
formatted += '\t';
break;
case '"':
formatted += '"';
break;
default:
// Invalid escape character
Compiler.Compiler.errors.SemErr(t.line, t.col, string.Format("Unrecognized escape character '" + tmp[i] + "'"));
break;
}
i++;
}
}
// Return formatted string
return formatted;
}
}
/// <summary>
/// CallExpression represents a call to a method
/// </summary>
class CallExpression : Expression
{
// Name of method to call
public string methodName;
// Argument list composed by expressions
public List<Expression> arguments;
/// <summary>
/// Creates a new CallExpression
/// </summary>
public CallExpression()
{
arguments = new List<Expression>();
}
/// <summary>
/// Creates a new CallExpression given a method name and a token
/// </summary>
/// <param name="methodName">Method name</param>
/// <param name="t">Call token</param>
public CallExpression(string methodName, Token t)
: this()
{
// Set method name and token
this.methodName = methodName;
this.t = t;
}
/// <summary>
/// Adds an agrument expression to the argument list
/// </summary>
/// <param name="expr">Argument expression</param>
public void AddArgument(Expression expr)
{
arguments.Add(expr);
}
/// <summary>
/// Evaluates this node and all its children
/// </summary>
/// <param name="scope">The scope of this expression</param>
/// <returns></returns>
public override Expression Evaluate(Scope scope)
{
// Evaluate all arguments
for (int i = 0; i < arguments.Count; i++)
{
arguments[i] = arguments[i].Evaluate(scope);
}
// Get signature from symbol table
Signature sig = scope.GetFunction(this);
// If no function is retrieved
if (sig == null)
{
// Unknown function error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Unknown function or ambiguos call to " + methodName);
}
else
{
// Set return type
this.returnType = sig.returnType;
// Step through each argument
for (int i = 0; i < sig.arguments.Count; i++)
{
// If argument expression type is different than expected argument
// Arguments are guaranteed to be compatible since a matching signature was found in the symbol table
if (!arguments[i].returnType.Equals(sig.arguments[i]))
{
// Create implicit type cast to expected argument
Expression expr = arguments[i];
arguments[i] = new CastExpression(sig.arguments[i]);
(arguments[i] as CastExpression).operand = expr;
}
}
}
return this;
}
/// <summary>
/// Emits code for this expression
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Emit code for all arguments
foreach (Expression expr in arguments)
{
expr.EmitCode(ilGen, scope);
}
// Get metadata token for method from symbol table and emit call
ilGen.Emit(OpCodes.Call, scope.GetMethodInfo(this));
}
}
/// <summary>
/// Unary operators
/// </summary>
enum UnaryOperator
{
UMinus, // Unary minus
Not // Logical negation
}
/// <summary>
/// UnaryExpression represents an expression with a single operand
/// </summary>
class UnaryExpression : Expression
{
// Operator and operand
public UnaryOperator op;
public Expression operand;
/// <summary>
/// Creates a new UnaryExpression given an operator
/// </summary>
/// <param name="op">Expression operator</param>
public UnaryExpression(UnaryOperator op)
{
this.op = op;
}
/// <summary>
/// Evaluates this node and all its children
/// </summary>
/// <param name="scope">The scope of this expression</param>
/// <returns></returns>
public override Expression Evaluate(Scope scope)
{
// Evaluate operand expression
operand = operand.Evaluate(scope);
// Save operand return type
PrimitiveType pType = (PrimitiveType)operand.returnType;
if (pType == null)
{
return null;
}
// Processing is done depending on operator
switch (op)
{
// Process unary minus
case UnaryOperator.UMinus:
// If operand is integer or double
if (pType.type == Primitive.Int || pType.type == Primitive.Double)
{
// Set return type
this.returnType = new PrimitiveType(pType.type);
// If operand is constant perform folding
if (operand is ConstantExpression)
{
// Fold integer value
if (pType.type == Primitive.Int)
{
// Cast value to int, add unary minus and create new constant expression
return new ConstantExpression(Primitive.Int, (-(int)(operand as ConstantExpression).value).ToString());
}
else if (pType.type == Primitive.Double)
{
// Cast value to double, add unary minus and create new constant expression
return new ConstantExpression(Primitive.Double, (-(double)(operand as ConstantExpression).value).ToString());
}
}
}
else
{
// Unary minus cannot be applied on other types
this.returnType = PrimitiveType.UNSUPPORTED;
// Issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Can only apply '-' to numeric types");
return this;
}
break;
// Process logical negation
case UnaryOperator.Not:
// If operand is boolean
if (pType.type == Primitive.Bool)
{
// Set return type
this.returnType = new PrimitiveType(pType.type);
// If oprand is constant perform folding
if (operand is ConstantExpression)
{
// Cast value to bool, negate and create new constant expression
return new ConstantExpression(Primitive.Bool, (bool)(operand as ConstantExpression).value ? "false" : "true");
}
}
else
{
// Logical negation cannot be applied on other types
this.returnType = PrimitiveType.UNSUPPORTED;
// Issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Can only apply '!' to boolean types");
return this;
}
break;
}
return this;
}
/// <summary>
/// Emits code for this expression
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Emit code for operand
operand.EmitCode(ilGen, scope);
// Emitted code depends on operator
switch (op)
{
// Emit code for unary minus
case UnaryOperator.UMinus:
// Call neg
ilGen.Emit(OpCodes.Neg);
break;
// Emit code for logical negation
case UnaryOperator.Not:
// Logical negation is done by comparing value with 0 - opcode not creates a bitwise complement, not a
// negation
ilGen.Emit(OpCodes.Ldc_I4_0);
ilGen.Emit(OpCodes.Ceq);
break;
}
}
}
/// <summary>
/// CastExpression represents a typecast
/// </summary>
class CastExpression : Expression
{
// Operand expression
public Expression operand;
/// <summary>
/// Creates a new CastExpression given a type to cast to
/// </summary>
/// <param name="type">BaseType to cast to</param>
public CastExpression(BaseType type)
{
// Set return type
returnType = type;
}
/// <summary>
/// Evaluates this node and all its children
/// </summary>
/// <param name="scope">The scope of this expression</param>
/// <returns></returns>
public override Expression Evaluate(Scope scope)
{
// Evaluate operand
operand = operand.Evaluate(scope);
// If types are actually equal
if (operand.returnType.Equals(this.returnType))
{
// Issue warning
Compiler.Compiler.errors.Warning(t.line, t.col, "Typecast to the same type");
// Drop the typecast expression
return operand;
}
// If an implicit type cast exists, no need to evaluate further
if (operand.returnType.IsCompatible(this.returnType))
{
if (returnType.Equals(PrimitiveType.DOUBLE))
{
// If operand is constant, fold typecast
if (operand is ConstantExpression)
{
// Cast value to int, convert to double and create new constant expression
return new ConstantExpression(Primitive.Double, Convert.ToDouble((int)(operand as ConstantExpression).value));
}
return this;
}
}
// Only explicit typecast implemented is from Double to Int
if (operand.returnType.Equals(PrimitiveType.DOUBLE))
{
if (returnType.Equals(PrimitiveType.INT))
{
// If operand is constant, fold typecast
if (operand is ConstantExpression)
{
// Cast value to double, convert to int and create new constant expression
return new ConstantExpression(Primitive.Int, Convert.ToInt32((double)(operand as ConstantExpression).value));
}
return this;
}
}
// Execution shouldn't reach this line if cast is correct - issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Invalid typecast");
return this;
}
/// <summary>
/// Emits code for this expression
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Emit code for operand
operand.EmitCode(ilGen, scope);
// Only typecasts available are between primitive types
if (returnType is PrimitiveType)
{
// Code is emitted depending on cast type
switch (((PrimitiveType)returnType).type)
{
// Emit code for int cast
case Primitive.Int:
ilGen.Emit(OpCodes.Conv_I4);
break;
// Emit code for double cast
case Primitive.Double:
ilGen.Emit(OpCodes.Conv_R8);
break;
}
}
}
}
/// <summary>
/// AssignableExpression represents an abstract class from which all assignable expression inherit, such as variable
/// references and array indexers
/// </summary>
abstract class AssignableExpression : Expression
{
// Primitive or array name - all assignable expressions have names
public string name;
/// <summary>
/// Emits code for an assignement given the right-side expression of the assignement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
/// <param name="rightSide">Right-side expression</param>
public abstract void EmitAssignement(ILGenerator ilGen, Scope scope, Expression rightSide);
}
/// <summary>
/// IndexerExpression represents an indexed array position
/// </summary>
class IndexerExpression : AssignableExpression
{
// Expression that returns an array
public Expression operand;
// List of indexers for each dimension
public List<Expression> indexers;
/// <summary>
/// Creates a new IndexerExpression given an array reference
/// </summary>
/// <param name="expr">Variable reference expression</param>
public IndexerExpression(Expression expr)
{
// Initialize members
operand = expr;
t = expr.t;
indexers = new List<Expression>();
}
/// <summary>
/// Adds an indexer to the expression
/// </summary>
/// <param name="indexer">Indexer expression</param>
public void AddIndexer(Expression indexer)
{
indexers.Add(indexer);
}
/// <summary>
/// Evaluates this node and all its children
/// </summary>
/// <param name="scope">The scope of this expression</param>
/// <returns></returns>
public override Expression Evaluate(Scope scope)
{
// Iterate through indexers
for (int i = 0; i < indexers.Count; i++)
{
// Evaluate indexer
indexers[i] = indexers[i].Evaluate(scope);
// Check if indexer is of integer type
if (!indexers[i].returnType.Equals(PrimitiveType.INT))
{
// Ilegal indexer type - issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Indexers must be of integer type");
return this;
}
}
// Evaluate operand expression
operand = operand.Evaluate(scope);
if (operand is IndexerExpression)
{
Compiler.Compiler.errors.SemErr(operand.t.line, operand.t.col, "Cannot apply multiple indexers on array. Use [,] instead of [][]");
return this;
}
// Try to cast operand return type to ArrayType
ArrayType refType = operand.returnType as ArrayType;
// Check if cast was successful
if (refType == null)
{
// Indexers can only be applied to array types - issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Cannot apply indexers to non-array type");
return this;
}
// Check if the dimension of the array is equal to the number of indexers
if (refType.dimensions != indexers.Count)
{
// Cannot assign to arrays, only to values - issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Invalid number of indexers");
return this;
}
// Set return type
this.returnType = refType.type;
return this;
}
/// <summary>
/// Emits code for this expression
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Emit code to index array
EmitIndexers(ilGen, scope);
// Call Get to retrieve value at indexed position
ilGen.Emit(OpCodes.Call, ((ArrayType)operand.returnType).ToCLRType().GetMethod("Get"));
}
/// <summary>
/// Emits code for assignement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
/// <param name="rightSide">Right-side expression</param>
public override void EmitAssignement(ILGenerator ilGen, Scope scope, Expression rightSide)
{
// Emit code to index array
EmitIndexers(ilGen, scope);
// Emit code for right-side expression
rightSide.EmitCode(ilGen, scope);
// Call Set to store value at indexed position
ilGen.Emit(OpCodes.Call, ((ArrayType)operand.returnType).ToCLRType().GetMethod("Set"));
}
/// <summary>
/// Emits code for indexers
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
private void EmitIndexers(ILGenerator ilGen, Scope scope)
{
// Emit code for the variable reference
operand.EmitCode(ilGen, scope);
// Emit code for each indexer
foreach (Expression indexer in indexers)
{
indexer.EmitCode(ilGen, scope);
}
}
}
/// <summary>
/// Binary operators
/// </summary>
enum BinaryOperator
{
// Arithmetic operators
Add = 1, // Addition
Sub, // Subtraction
Mul, // Multiplication
Div, // Division
Rem, // Modulo
// Equality operators
Eq, // Equals
Neq, // Not equals
Leq, // Less than or equals
Geq, // Greater than or equals
Lt, // Less than
Gt, // Greater than
// Logical operators
And, // Logical and
Or, // Logical or
Xor // Logical exlusive or
}
/// <summary>
/// BinaryExpression represents an expression with two operands
/// </summary>
class BinaryExpression : Expression
{
// Left and right operands and operator
public Expression leftOperand;
public Expression rightOperand;
public BinaryOperator op;
/// <summary>
/// Creates a new BinaryExpression given a left operand
/// </summary>
/// <param name="leftOperand"></param>
public BinaryExpression(Expression leftOperand)
{
this.leftOperand = leftOperand;
}
/// <summary>
/// Evaluates this node and all its children
/// </summary>
/// <param name="scope">The scope of this expression</param>
/// <returns></returns>
public override Expression Evaluate(Scope scope)
{
// Evaluate operands
leftOperand = leftOperand.Evaluate(scope);
rightOperand = rightOperand.Evaluate(scope);
// Check if both operands are of the same type
if (leftOperand.returnType.ToCLRType() != rightOperand.returnType.ToCLRType())
{
// If not, check if left operand can be implicitely typecasted to right operand type
if (leftOperand.returnType.IsCompatible(rightOperand.returnType))
{
// Create implicit cast
CastExpression implicitCast = new CastExpression(rightOperand.returnType);
implicitCast.operand = leftOperand;
// Evaluate typecast for folding
this.leftOperand = implicitCast.Evaluate(scope);
// Set return type
this.returnType = rightOperand.returnType;
}
// If not, check if right operand can be implicitely typecasted to left operand type
else if (rightOperand.returnType.IsCompatible(leftOperand.returnType))
{
// Create implicit cast
CastExpression implicitCast = new CastExpression(leftOperand.returnType);
implicitCast.operand = rightOperand;
// Evaluate for folding
this.rightOperand = implicitCast.Evaluate(scope);
// Set return type
this.returnType = leftOperand.returnType;
}
else
{
// Types are incompatible - issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Incompatible types");
this.returnType = PrimitiveType.UNSUPPORTED;
return this;
}
}
// If operands are of the same type
else
{
// Set return type
this.returnType = leftOperand.returnType;
}
// If operand is not arithmetic, overwrite return type
if ((int)op >= 6)
{
this.returnType = PrimitiveType.BOOL;
}
// Check if operator and operands are compatible
switch (op)
{
// Addition is accepted for strings and numeric types
case BinaryOperator.Add:
// If type is not string, check if it is numerical
if (!leftOperand.returnType.Equals(PrimitiveType.STRING))
{
goto case BinaryOperator.Leq;
}
break;
// Other arithmetic operators and comparisons (except equals and not equals) are accepted for numeric types
case BinaryOperator.Sub:
case BinaryOperator.Mul:
case BinaryOperator.Div:
case BinaryOperator.Gt:
case BinaryOperator.Lt:
case BinaryOperator.Geq:
case BinaryOperator.Leq:
// Check if type is not integer or double
if (!leftOperand.returnType.Equals(PrimitiveType.INT) &&
!leftOperand.returnType.Equals(PrimitiveType.DOUBLE))
{
// Issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Arithmetic operator can only be applied to numerical types");
}
break;
// Modulo operator is accepted only for integer type
case BinaryOperator.Rem:
// Check if type is not integer
if (!leftOperand.returnType.Equals(PrimitiveType.INT))
{
// Issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Reminder operator can only be applied to integer type");
}
break;
// Equality and non equality are accepted for all types
case BinaryOperator.Eq:
case BinaryOperator.Neq:
break;
// Default case stands for logical operators
default:
// Check if type is not boolean
if (!leftOperand.returnType.Equals(PrimitiveType.BOOL))
{
// Issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Logical operator can only be applied to boolean type");
}
break;
}
// If both operands are constant expressions, perform constant folding
if ((leftOperand is ConstantExpression) && (rightOperand is ConstantExpression))
{
// Compile time evaluation of expressions is done based on type and operator
// If type is boolean
if (leftOperand.returnType.Equals(PrimitiveType.BOOL))
{
switch (op)
{
// Compute equality
case BinaryOperator.Eq:
// Cast values to bool, compare and create new constant expression
return new ConstantExpression(Primitive.Bool, (bool)(leftOperand as ConstantExpression).value ==
(bool)(rightOperand as ConstantExpression).value);
// Compute non-equality
case BinaryOperator.Neq:
// Same as exclusive or for boolean values
goto case BinaryOperator.Xor;
// Compute logical and
case BinaryOperator.And:
// Cast values to bool, apply operation and create constant expression
return new ConstantExpression(Primitive.Bool, (bool)(leftOperand as ConstantExpression).value &&
(bool)(rightOperand as ConstantExpression).value);
// Compute logical or
case BinaryOperator.Or:
// Cast values to bool, apply operation and create constant expression
return new ConstantExpression(Primitive.Bool, (bool)(leftOperand as ConstantExpression).value ||
(bool)(rightOperand as ConstantExpression).value);
// Compute logical exclusive or
case BinaryOperator.Xor:
// Cast values to bool, apply operation and create constant expression (xor is equivalent to a
// non-equality check)
return new ConstantExpression(Primitive.Bool, (bool)(leftOperand as ConstantExpression).value !=
(bool)(rightOperand as ConstantExpression).value);
}
}
// If type is double
else if (leftOperand.returnType.Equals(PrimitiveType.DOUBLE))
{
switch (op)
{
// Compute equality
case BinaryOperator.Eq:
// Cast values to double, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (double)(leftOperand as ConstantExpression).value ==
(double)(rightOperand as ConstantExpression).value);
// Compute non-equality
case BinaryOperator.Neq:
// Cast values to double, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (double)(leftOperand as ConstantExpression).value !=
(double)(rightOperand as ConstantExpression).value);
// Compute greater than
case BinaryOperator.Gt:
// Cast values to double, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (double)(leftOperand as ConstantExpression).value >
(double)(rightOperand as ConstantExpression).value);
// Compute greater than or equal to
case BinaryOperator.Geq:
// Cast values to double, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (double)(leftOperand as ConstantExpression).value >=
(double)(rightOperand as ConstantExpression).value);
// Compute less than
case BinaryOperator.Lt:
// Cast values to double, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (double)(leftOperand as ConstantExpression).value <
(double)(rightOperand as ConstantExpression).value);
// Compute less than or equal to
case BinaryOperator.Leq:
// Cast values to double, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (double)(leftOperand as ConstantExpression).value <=
(double)(rightOperand as ConstantExpression).value);
// Compute addition
case BinaryOperator.Add:
// Cast values to double, apply operation and create constant expression
return new ConstantExpression(Primitive.Double, ((double)(leftOperand as ConstantExpression).value +
(double)(rightOperand as ConstantExpression).value).ToString(NumberFormatInfo.InvariantInfo));
// Compute subtraction
case BinaryOperator.Sub:
// Cast values to double, apply operation and create constant expression
return new ConstantExpression(Primitive.Double, ((double)(leftOperand as ConstantExpression).value -
(double)(rightOperand as ConstantExpression).value).ToString(NumberFormatInfo.InvariantInfo));
// Compute multiplication
case BinaryOperator.Mul:
// Cast values to double, apply operation and create constant expression
return new ConstantExpression(Primitive.Double, ((double)(leftOperand as ConstantExpression).value *
(double)(rightOperand as ConstantExpression).value).ToString(NumberFormatInfo.InvariantInfo));
// Compute division
case BinaryOperator.Div:
// Cast values to double, apply operation and create constant expression
return new ConstantExpression(Primitive.Double, ((double)(leftOperand as ConstantExpression).value /
(double)(rightOperand as ConstantExpression).value).ToString(NumberFormatInfo.InvariantInfo));
}
}
// If type is integer
else if (leftOperand.returnType.Equals(PrimitiveType.INT))
{
switch (op)
{
// Compute equality
case BinaryOperator.Eq:
// Cast values to int, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (int)(leftOperand as ConstantExpression).value ==
(int)(rightOperand as ConstantExpression).value);
// Compute non-equality
case BinaryOperator.Neq:
// Cast values to int, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (int)(leftOperand as ConstantExpression).value !=
(int)(rightOperand as ConstantExpression).value);
// Compute greater than
case BinaryOperator.Gt:
// Cast values to int, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (int)(leftOperand as ConstantExpression).value >
(int)(rightOperand as ConstantExpression).value);
// Compute greater than or equal to
case BinaryOperator.Geq:
// Cast values to int, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (int)(leftOperand as ConstantExpression).value >=
(int)(rightOperand as ConstantExpression).value);
// Compute less than
case BinaryOperator.Lt:
// Cast values to int, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (int)(leftOperand as ConstantExpression).value <
(int)(rightOperand as ConstantExpression).value);
// Compute less than or equal to
case BinaryOperator.Leq:
// Cast values to int, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (int)(leftOperand as ConstantExpression).value <=
(int)(rightOperand as ConstantExpression).value);
// Compute addition
case BinaryOperator.Add:
// Cast values to int, apply operation and create constant expression
return new ConstantExpression(Primitive.Int, ((int)(leftOperand as ConstantExpression).value +
(int)(rightOperand as ConstantExpression).value).ToString(NumberFormatInfo.InvariantInfo));
// Compute subtraction
case BinaryOperator.Sub:
// Cast values to int, apply operation and create constant expression
return new ConstantExpression(Primitive.Int, ((int)(leftOperand as ConstantExpression).value -
(int)(rightOperand as ConstantExpression).value).ToString(NumberFormatInfo.InvariantInfo));
// Compute multiplication
case BinaryOperator.Mul:
// Cast values to int, apply operation and create constant expression
return new ConstantExpression(Primitive.Int, ((int)(leftOperand as ConstantExpression).value *
(int)(rightOperand as ConstantExpression).value).ToString(NumberFormatInfo.InvariantInfo));
// Compute division
case BinaryOperator.Div:
// Cast values to int, apply operation and create constant expression
return new ConstantExpression(Primitive.Int, ((int)(leftOperand as ConstantExpression).value /
(int)(rightOperand as ConstantExpression).value).ToString(NumberFormatInfo.InvariantInfo));
// Compute modulo
case BinaryOperator.Rem:
// Cast values to int, apply operation and create constant expression
return new ConstantExpression(Primitive.Int, ((int)(leftOperand as ConstantExpression).value %
(int)(rightOperand as ConstantExpression).value).ToString(NumberFormatInfo.InvariantInfo));
}
}
// If type is string
else if (leftOperand.returnType.Equals(PrimitiveType.STRING))
{
switch (op)
{
// Compute equality
case BinaryOperator.Eq:
// Convert values to string, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (leftOperand as ConstantExpression).value.ToString() ==
(rightOperand as ConstantExpression).value.ToString());
// Compute non-equality
case BinaryOperator.Neq:
// Convert values to string, apply operation and create constant (boolean) expression
return new ConstantExpression(Primitive.Bool, (leftOperand as ConstantExpression).value.ToString() !=
(rightOperand as ConstantExpression).value.ToString());
// Compute addition
case BinaryOperator.Add:
// Convert values to string, apply operation and create constant expression
return new ConstantExpression(Primitive.String, (leftOperand as ConstantExpression).value.ToString() +
(rightOperand as ConstantExpression).value.ToString());
}
}
}
return this;
}
/// <summary>
/// Emits code for this expression
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// If operator is arithmetical or a comparison (not logical)
if ((int)op < 12)
{
// Emit code for operands
leftOperand.EmitCode(ilGen, scope);
rightOperand.EmitCode(ilGen, scope);
// Code is emitted depending on operation
switch (op)
{
// Arithmetic operators
// Emit addition
case BinaryOperator.Add:
// Check if type is string
if (leftOperand.returnType.Equals(PrimitiveType.STRING))
{
// For strings, call method System.String.Concat(string, string)
ilGen.Emit(OpCodes.Call, Type.GetType("System.String").GetMethod("Concat", new Type[] { typeof(string), typeof(string) }));
}
else
{
// For numerical types, emit add
ilGen.Emit(OpCodes.Add);
}
break;
// Emit subtraction
case BinaryOperator.Sub:
ilGen.Emit(OpCodes.Sub);
break;
// Emit multiplication
case BinaryOperator.Mul:
ilGen.Emit(OpCodes.Mul);
break;
// Emit division
case BinaryOperator.Div:
ilGen.Emit(OpCodes.Div);
break;
// Emit modulo
case BinaryOperator.Rem:
ilGen.Emit(OpCodes.Rem);
break;
// Comparison operators
// Emit equality
case BinaryOperator.Eq:
ilGen.Emit(OpCodes.Ceq);
break;
// Emit non-equality
case BinaryOperator.Neq:
// Neq, leg and geq are simulated by negating eq, gt and lt respectively
// Emit equality check
ilGen.Emit(OpCodes.Ceq);
// Load 0 onto the stack
ilGen.Emit(OpCodes.Ldc_I4_0);
// Check equality
ilGen.Emit(OpCodes.Ceq);
break;
// Emit greater than
case BinaryOperator.Gt:
ilGen.Emit(OpCodes.Cgt);
break;
// Emit less than
case BinaryOperator.Lt:
ilGen.Emit(OpCodes.Clt);
break;
// Emit less than or equal to
case BinaryOperator.Leq:
// Emit greater than check
ilGen.Emit(OpCodes.Cgt);
// Load 0 onto the stack
ilGen.Emit(OpCodes.Ldc_I4_0);
// Check equality
ilGen.Emit(OpCodes.Ceq);
break;
// Emit greater than or equal to
case BinaryOperator.Geq:
// Emit less than check
ilGen.Emit(OpCodes.Clt);
// Load 0 onto the stack
ilGen.Emit(OpCodes.Ldc_I4_0);
// Check equality
ilGen.Emit(OpCodes.Ceq);
break;
}
}
// Operator is logical - logical operators are emitted following the rules:
// for and: if first operand is false, second operand is not evaluated and expression is considered false
// for or: if first operand is true, second operand is not vealuated and expression is considered true
else
{
// Labels needed to skip evaluations if necessary
Label falseLabel;
Label trueLabel;
Label endLabel;
// Code is emitted depending on operator
switch (op)
{
// Emit logical and
case BinaryOperator.And:
// Define labels
falseLabel = ilGen.DefineLabel();
endLabel = ilGen.DefineLabel();
// Emit code for left operand
leftOperand.EmitCode(ilGen, scope);
// Brake to false if first operand is false
ilGen.Emit(OpCodes.Brfalse, falseLabel);
// Emit code for right operand
rightOperand.EmitCode(ilGen, scope);
// Break to end
ilGen.Emit(OpCodes.Br, endLabel);
// Mark false label
ilGen.MarkLabel(falseLabel);
// Push 0 onto the stack - brfalse pops value from the stack while br doesn't
ilGen.Emit(OpCodes.Ldc_I4_0);
// Mark end label
ilGen.MarkLabel(endLabel);
break;
// Emit logical or
case BinaryOperator.Or:
// Define labels
trueLabel = ilGen.DefineLabel();
endLabel = ilGen.DefineLabel();
// Emit code for left operand
leftOperand.EmitCode(ilGen, scope);
// Break to true if first operand is true
ilGen.Emit(OpCodes.Brtrue, trueLabel);
// Emit code for right operand
rightOperand.EmitCode(ilGen, scope);
// Break to end
ilGen.Emit(OpCodes.Br, endLabel);
// Mark true label
ilGen.MarkLabel(trueLabel);
// Push 1 onto the stack - brtrue pops value from the stack while br doesn't
ilGen.Emit(OpCodes.Ldc_I4_1);
// Mark end label
ilGen.MarkLabel(endLabel);
break;
// Emit logical xor
case BinaryOperator.Xor:
// Emit code for operands
leftOperand.EmitCode(ilGen, scope);
rightOperand.EmitCode(ilGen, scope);
// Emit xor
ilGen.Emit(OpCodes.Xor);
break;
}
}
}
}
/// <summary>
/// VariableReferenceExpression represents a reference to a variable
/// </summary>
class VariableReferenceExpression : AssignableExpression
{
/// <summary>
/// Creates a new VariableReferenceExpression given a variable name
/// </summary>
/// <param name="name">Variable name</param>
public VariableReferenceExpression(string name)
{
this.name = name;
}
/// <summary>
/// Evaluates this node and all its children
/// </summary>
/// <param name="scope">The scope of this expression</param>
/// <returns></returns>
public override Expression Evaluate(Scope scope)
{
// Set return type by getting variable from symbol table
returnType = scope.GetVariable(name);
// Check if no type was returned
if (returnType == null)
{
// Issue error
Compiler.Compiler.errors.SemErr(t.line, t.col, "Unknown variable reference");
}
return this;
}
/// <summary>
/// Emits code for this expression
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
public override void EmitCode(ILGenerator ilGen, Scope scope)
{
// Variable references are emitted by the symbol table because different variables are referenced with
// different instructions and only the symbol table knows how to correctly refer them
scope.EmitVariableReference(name, ilGen);
}
/// <summary>
/// Emits code for an assignement given the right-side expression of the assignement
/// </summary>
/// <param name="ilGen">IL generator object</param>
/// <param name="scope">The scope of this expression</param>
/// <param name="rightSide">Right-side expression</param>
public override void EmitAssignement(ILGenerator ilGen, Scope scope, Expression rightSide)
{
// Emit code for right side expression
rightSide.EmitCode(ilGen, scope);
// Use symbol table to emit variable assignement
scope.EmitVariableAssignement(name, ilGen);
}
}
}
| |
using DevExpress.XtraReports.UI;
using EIDSS.Reports.Parameterized.Human.AJ.DataSets;
using EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1HeaderDataSetTableAdapters;
using EIDSS.Reports.Parameterized.Human.KZ.InfectiousParasiticKZDataSetTableAdapters;
namespace EIDSS.Reports.Parameterized.Human.KZ
{
partial class InfectiousParasiticKZReport
{
#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(InfectiousParasiticKZReport));
DevExpress.XtraReports.UI.XRSummary xrSummary1 = new DevExpress.XtraReports.UI.XRSummary();
this.ReportFooterBand = new DevExpress.XtraReports.UI.ReportFooterBand();
this.formattingRule1 = new DevExpress.XtraReports.UI.FormattingRule();
this.xrControlStyle1 = new DevExpress.XtraReports.UI.XRControlStyle();
this.m_Adapter = new EIDSS.Reports.Parameterized.Human.KZ.InfectiousParasiticKZDataSetTableAdapters.InfectiousDiseasesAdapter();
this.m_DataSet = new EIDSS.Reports.Parameterized.Human.KZ.InfectiousParasiticKZDataSet();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailBand = new DevExpress.XtraReports.UI.DetailBand();
this.DetailTable = new DevExpress.XtraReports.UI.XRTable();
this.DetailRow = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell61 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell62 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell63 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell65 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell66 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell67 = new DevExpress.XtraReports.UI.XRTableCell();
this.HeaderBand = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.DetailTableHeader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell();
this.TextTableHeader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.PeriodCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.LocationCell = new DevExpress.XtraReports.UI.XRTableCell();
this.GroupHeaderLine = new DevExpress.XtraReports.UI.GroupHeaderBand();
this.xrLine2 = new DevExpress.XtraReports.UI.XRLine();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.DateTimeLabel = new DevExpress.XtraReports.UI.XRLabel();
this.DateTimeCaptionLabel = new DevExpress.XtraReports.UI.XRLabel();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.DetailTable)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.DetailTableHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.TextTableHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// xrTable4
//
resources.ApplyResources(this.xrTable4, "xrTable4");
this.xrTable4.StylePriority.UseBorders = false;
this.xrTable4.StylePriority.UseFont = false;
this.xrTable4.StylePriority.UsePadding = false;
//
// 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.Expanded = false;
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// PageHeader
//
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.StylePriority.UsePadding = false;
//
// 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;
//
// ReportFooterBand
//
resources.ApplyResources(this.ReportFooterBand, "ReportFooterBand");
this.ReportFooterBand.Name = "ReportFooterBand";
this.ReportFooterBand.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.ReportFooterBand.StylePriority.UseFont = false;
this.ReportFooterBand.StylePriority.UsePadding = false;
this.ReportFooterBand.StylePriority.UseTextAlignment = false;
//
// formattingRule1
//
this.formattingRule1.Name = "formattingRule1";
//
// xrControlStyle1
//
this.xrControlStyle1.Name = "xrControlStyle1";
//
// m_Adapter
//
this.m_Adapter.ClearBeforeFill = true;
//
// m_DataSet
//
this.m_DataSet.DataSetName = "InfectiousParasiticKZDataSet";
this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailBand,
this.HeaderBand,
this.GroupHeaderLine,
this.ReportFooter});
this.DetailReport.DataAdapter = this.m_Adapter;
this.DetailReport.DataMember = "InfectiousDiseases";
this.DetailReport.DataSource = this.m_DataSet;
resources.ApplyResources(this.DetailReport, "DetailReport");
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
//
// DetailBand
//
this.DetailBand.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.DetailTable});
resources.ApplyResources(this.DetailBand, "DetailBand");
this.DetailBand.Name = "DetailBand";
//
// DetailTable
//
this.DetailTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.DetailTable, "DetailTable");
this.DetailTable.Name = "DetailTable";
this.DetailTable.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.DetailTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.DetailRow});
this.DetailTable.StylePriority.UseBorders = false;
this.DetailTable.StylePriority.UseFont = false;
this.DetailTable.StylePriority.UsePadding = false;
this.DetailTable.StylePriority.UseTextAlignment = false;
//
// DetailRow
//
this.DetailRow.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell59,
this.xrTableCell60,
this.xrTableCell61,
this.xrTableCell62,
this.xrTableCell63,
this.xrTableCell64,
this.xrTableCell65,
this.xrTableCell66,
this.xrTableCell67});
resources.ApplyResources(this.DetailRow, "DetailRow");
this.DetailRow.Name = "DetailRow";
//
// xrTableCell59
//
this.xrTableCell59.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "InfectiousDiseases.strDiseaseName")});
resources.ApplyResources(this.xrTableCell59, "xrTableCell59");
this.xrTableCell59.Name = "xrTableCell59";
this.xrTableCell59.StylePriority.UseBorders = false;
this.xrTableCell59.StylePriority.UseTextAlignment = false;
//
// xrTableCell60
//
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
this.xrTableCell60.Name = "xrTableCell60";
this.xrTableCell60.StylePriority.UseBorders = false;
this.xrTableCell60.StylePriority.UseTextAlignment = false;
resources.ApplyResources(xrSummary1, "xrSummary1");
xrSummary1.Func = DevExpress.XtraReports.UI.SummaryFunc.RecordNumber;
xrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Report;
this.xrTableCell60.Summary = xrSummary1;
//
// xrTableCell61
//
this.xrTableCell61.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "InfectiousDiseases.strICD10")});
resources.ApplyResources(this.xrTableCell61, "xrTableCell61");
this.xrTableCell61.Name = "xrTableCell61";
this.xrTableCell61.StylePriority.UseBorders = false;
this.xrTableCell61.StylePriority.UseTextAlignment = false;
//
// xrTableCell62
//
this.xrTableCell62.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "InfectiousDiseases.intTotal")});
resources.ApplyResources(this.xrTableCell62, "xrTableCell62");
this.xrTableCell62.Name = "xrTableCell62";
this.xrTableCell62.StylePriority.UseBorders = false;
this.xrTableCell62.StylePriority.UseTextAlignment = false;
//
// xrTableCell63
//
this.xrTableCell63.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "InfectiousDiseases.intAge_0_14")});
resources.ApplyResources(this.xrTableCell63, "xrTableCell63");
this.xrTableCell63.Name = "xrTableCell63";
this.xrTableCell63.StylePriority.UseBorders = false;
this.xrTableCell63.StylePriority.UseTextAlignment = false;
//
// xrTableCell64
//
this.xrTableCell64.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "InfectiousDiseases.intAge_15_17")});
resources.ApplyResources(this.xrTableCell64, "xrTableCell64");
this.xrTableCell64.Name = "xrTableCell64";
this.xrTableCell64.StylePriority.UseBorders = false;
this.xrTableCell64.StylePriority.UseTextAlignment = false;
//
// xrTableCell65
//
this.xrTableCell65.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "InfectiousDiseases.intRuralTotal")});
resources.ApplyResources(this.xrTableCell65, "xrTableCell65");
this.xrTableCell65.Name = "xrTableCell65";
this.xrTableCell65.StylePriority.UseBorders = false;
this.xrTableCell65.StylePriority.UseTextAlignment = false;
//
// xrTableCell66
//
this.xrTableCell66.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "InfectiousDiseases.intRuralAge_0_14")});
resources.ApplyResources(this.xrTableCell66, "xrTableCell66");
this.xrTableCell66.Name = "xrTableCell66";
this.xrTableCell66.StylePriority.UseBorders = false;
this.xrTableCell66.StylePriority.UseTextAlignment = false;
//
// xrTableCell67
//
this.xrTableCell67.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "InfectiousDiseases.intRuralAge_15_17")});
resources.ApplyResources(this.xrTableCell67, "xrTableCell67");
this.xrTableCell67.Name = "xrTableCell67";
this.xrTableCell67.StylePriority.UseBorders = false;
this.xrTableCell67.StylePriority.UseTextAlignment = false;
//
// HeaderBand
//
this.HeaderBand.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.DetailTableHeader,
this.TextTableHeader});
resources.ApplyResources(this.HeaderBand, "HeaderBand");
this.HeaderBand.Name = "HeaderBand";
//
// DetailTableHeader
//
this.DetailTableHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.DetailTableHeader, "DetailTableHeader");
this.DetailTableHeader.Name = "DetailTableHeader";
this.DetailTableHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.DetailTableHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow9,
this.xrTableRow11,
this.xrTableRow12,
this.xrTableRow13});
this.DetailTableHeader.StylePriority.UseBorders = false;
this.DetailTableHeader.StylePriority.UseFont = false;
this.DetailTableHeader.StylePriority.UsePadding = false;
this.DetailTableHeader.StylePriority.UseTextAlignment = false;
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell16,
this.xrTableCell19,
this.xrTableCell13,
this.xrTableCell21,
this.xrTableCell14});
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
this.xrTableRow9.Name = "xrTableRow9";
//
// xrTableCell16
//
this.xrTableCell16.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.StylePriority.UseBorders = false;
//
// xrTableCell19
//
this.xrTableCell19.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseBorders = false;
//
// xrTableCell13
//
this.xrTableCell13.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.StylePriority.UseBorders = false;
this.xrTableCell13.StylePriority.UseTextAlignment = false;
//
// xrTableCell21
//
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
//
// xrTableCell14
//
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell4,
this.xrTableCell5,
this.xrTableCell22,
this.xrTableCell23,
this.xrTableCell25,
this.xrTableCell26,
this.xrTableCell28});
resources.ApplyResources(this.xrTableRow11, "xrTableRow11");
this.xrTableRow11.Name = "xrTableRow11";
//
// xrTableCell4
//
this.xrTableCell4.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseBorders = false;
this.xrTableCell4.StylePriority.UseTextAlignment = false;
//
// xrTableCell5
//
this.xrTableCell5.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseBorders = false;
this.xrTableCell5.StylePriority.UseTextAlignment = false;
//
// xrTableCell22
//
this.xrTableCell22.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseBorders = false;
this.xrTableCell22.StylePriority.UseTextAlignment = false;
//
// xrTableCell23
//
this.xrTableCell23.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseBorders = false;
//
// xrTableCell25
//
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Name = "xrTableCell25";
//
// xrTableCell26
//
this.xrTableCell26.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseBorders = false;
//
// xrTableCell28
//
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
this.xrTableCell28.Name = "xrTableCell28";
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell29,
this.xrTableCell30,
this.xrTableCell31,
this.xrTableCell32,
this.xrTableCell33,
this.xrTableCell34,
this.xrTableCell35,
this.xrTableCell36,
this.xrTableCell37});
resources.ApplyResources(this.xrTableRow12, "xrTableRow12");
this.xrTableRow12.Name = "xrTableRow12";
//
// xrTableCell29
//
this.xrTableCell29.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.StylePriority.UseBorders = false;
//
// xrTableCell30
//
this.xrTableCell30.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Name = "xrTableCell30";
this.xrTableCell30.StylePriority.UseBorders = false;
this.xrTableCell30.StylePriority.UseTextAlignment = false;
//
// xrTableCell31
//
this.xrTableCell31.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
this.xrTableCell31.Name = "xrTableCell31";
this.xrTableCell31.StylePriority.UseBorders = false;
this.xrTableCell31.StylePriority.UseTextAlignment = false;
//
// xrTableCell32
//
this.xrTableCell32.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
this.xrTableCell32.Name = "xrTableCell32";
this.xrTableCell32.StylePriority.UseBorders = false;
this.xrTableCell32.StylePriority.UseTextAlignment = false;
//
// xrTableCell33
//
this.xrTableCell33.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
this.xrTableCell33.Name = "xrTableCell33";
this.xrTableCell33.StylePriority.UseBorders = false;
this.xrTableCell33.StylePriority.UseTextAlignment = false;
//
// xrTableCell34
//
this.xrTableCell34.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseBorders = false;
this.xrTableCell34.StylePriority.UseTextAlignment = false;
//
// xrTableCell35
//
this.xrTableCell35.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell35, "xrTableCell35");
this.xrTableCell35.Name = "xrTableCell35";
this.xrTableCell35.StylePriority.UseBorders = false;
this.xrTableCell35.StylePriority.UseTextAlignment = false;
//
// xrTableCell36
//
this.xrTableCell36.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell36, "xrTableCell36");
this.xrTableCell36.Name = "xrTableCell36";
this.xrTableCell36.StylePriority.UseBorders = false;
this.xrTableCell36.StylePriority.UseTextAlignment = false;
//
// xrTableCell37
//
this.xrTableCell37.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell37, "xrTableCell37");
this.xrTableCell37.Name = "xrTableCell37";
this.xrTableCell37.StylePriority.UseBorders = false;
this.xrTableCell37.StylePriority.UseTextAlignment = false;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell38,
this.xrTableCell39,
this.xrTableCell40,
this.xrTableCell41,
this.xrTableCell42,
this.xrTableCell43,
this.xrTableCell44,
this.xrTableCell45,
this.xrTableCell46});
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
this.xrTableRow13.Name = "xrTableRow13";
//
// xrTableCell38
//
this.xrTableCell38.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell38, "xrTableCell38");
this.xrTableCell38.Name = "xrTableCell38";
this.xrTableCell38.StylePriority.UseBorders = false;
//
// xrTableCell39
//
this.xrTableCell39.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell39, "xrTableCell39");
this.xrTableCell39.Name = "xrTableCell39";
this.xrTableCell39.StylePriority.UseBorders = false;
//
// xrTableCell40
//
this.xrTableCell40.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
this.xrTableCell40.Name = "xrTableCell40";
this.xrTableCell40.StylePriority.UseBorders = false;
this.xrTableCell40.StylePriority.UseTextAlignment = false;
//
// xrTableCell41
//
this.xrTableCell41.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.StylePriority.UseBorders = false;
//
// xrTableCell42
//
this.xrTableCell42.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell42, "xrTableCell42");
this.xrTableCell42.Name = "xrTableCell42";
this.xrTableCell42.StylePriority.UseBorders = false;
this.xrTableCell42.StylePriority.UseTextAlignment = false;
//
// xrTableCell43
//
this.xrTableCell43.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell43, "xrTableCell43");
this.xrTableCell43.Name = "xrTableCell43";
this.xrTableCell43.StylePriority.UseBorders = false;
this.xrTableCell43.StylePriority.UseTextAlignment = false;
//
// xrTableCell44
//
this.xrTableCell44.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell44, "xrTableCell44");
this.xrTableCell44.Name = "xrTableCell44";
this.xrTableCell44.StylePriority.UseBorders = false;
//
// xrTableCell45
//
this.xrTableCell45.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell45, "xrTableCell45");
this.xrTableCell45.Name = "xrTableCell45";
this.xrTableCell45.StylePriority.UseBorders = false;
this.xrTableCell45.StylePriority.UseTextAlignment = false;
//
// xrTableCell46
//
this.xrTableCell46.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell46, "xrTableCell46");
this.xrTableCell46.Name = "xrTableCell46";
this.xrTableCell46.StylePriority.UseBorders = false;
this.xrTableCell46.StylePriority.UseTextAlignment = false;
//
// TextTableHeader
//
resources.ApplyResources(this.TextTableHeader, "TextTableHeader");
this.TextTableHeader.Name = "TextTableHeader";
this.TextTableHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.TextTableHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2,
this.xrTableRow4,
this.xrTableRow5,
this.xrTableRow3,
this.xrTableRow6,
this.xrTableRow7,
this.xrTableRow8});
this.TextTableHeader.StylePriority.UsePadding = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell6});
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
this.xrTableRow2.Name = "xrTableRow2";
//
// xrTableCell6
//
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Multiline = true;
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseTextAlignment = false;
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell8});
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
this.xrTableRow4.Name = "xrTableRow4";
//
// xrTableCell8
//
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseFont = false;
this.xrTableCell8.StylePriority.UseTextAlignment = false;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell9});
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
this.xrTableRow5.Name = "xrTableRow5";
//
// xrTableCell9
//
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.StylePriority.UseFont = false;
this.xrTableCell9.StylePriority.UseTextAlignment = false;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell7});
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
this.xrTableRow3.Name = "xrTableRow3";
//
// xrTableCell7
//
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Multiline = true;
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseTextAlignment = false;
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell10});
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
this.xrTableRow6.Name = "xrTableRow6";
//
// xrTableCell10
//
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseFont = false;
this.xrTableCell10.StylePriority.UseTextAlignment = false;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.PeriodCell});
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
this.xrTableRow7.Name = "xrTableRow7";
//
// PeriodCell
//
resources.ApplyResources(this.PeriodCell, "PeriodCell");
this.PeriodCell.Name = "PeriodCell";
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.LocationCell});
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
this.xrTableRow8.Name = "xrTableRow8";
//
// LocationCell
//
resources.ApplyResources(this.LocationCell, "LocationCell");
this.LocationCell.Name = "LocationCell";
//
// GroupHeaderLine
//
this.GroupHeaderLine.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLine2});
resources.ApplyResources(this.GroupHeaderLine, "GroupHeaderLine");
this.GroupHeaderLine.Name = "GroupHeaderLine";
this.GroupHeaderLine.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.GroupHeaderLine.RepeatEveryPage = true;
this.GroupHeaderLine.StylePriority.UsePadding = false;
//
// xrLine2
//
this.xrLine2.BorderWidth = 0F;
resources.ApplyResources(this.xrLine2, "xrLine2");
this.xrLine2.LineWidth = 0;
this.xrLine2.Name = "xrLine2";
this.xrLine2.StylePriority.UseBorderWidth = false;
//
// ReportFooter
//
this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.DateTimeLabel,
this.DateTimeCaptionLabel});
resources.ApplyResources(this.ReportFooter, "ReportFooter");
this.ReportFooter.Name = "ReportFooter";
//
// DateTimeLabel
//
resources.ApplyResources(this.DateTimeLabel, "DateTimeLabel");
this.DateTimeLabel.Name = "DateTimeLabel";
this.DateTimeLabel.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.DateTimeLabel.StylePriority.UseTextAlignment = false;
//
// DateTimeCaptionLabel
//
resources.ApplyResources(this.DateTimeCaptionLabel, "DateTimeCaptionLabel");
this.DateTimeCaptionLabel.Name = "DateTimeCaptionLabel";
this.DateTimeCaptionLabel.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.DateTimeCaptionLabel.StylePriority.UseTextAlignment = false;
//
// InfectiousParasiticKZReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.ReportFooterBand,
this.DetailReport});
resources.ApplyResources(this, "$this");
this.FormattingRuleSheet.AddRange(new DevExpress.XtraReports.UI.FormattingRule[] {
this.formattingRule1});
this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.StyleSheet.AddRange(new DevExpress.XtraReports.UI.XRControlStyle[] {
this.xrControlStyle1});
this.Version = "14.1";
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.ReportFooterBand, 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.xrTable4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.DetailTable)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.DetailTableHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.TextTableHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooterBand;
private FormattingRule formattingRule1;
private XRControlStyle xrControlStyle1;
private InfectiousDiseasesAdapter m_Adapter;
private InfectiousParasiticKZDataSet m_DataSet;
private DetailReportBand DetailReport;
private DetailBand DetailBand;
private ReportHeaderBand HeaderBand;
private XRTable TextTableHeader;
private XRTableRow xrTableRow2;
private XRTableCell xrTableCell6;
private XRTableRow xrTableRow4;
private XRTableCell xrTableCell8;
private XRTableRow xrTableRow3;
private XRTableCell xrTableCell7;
private XRTableRow xrTableRow5;
private XRTableCell xrTableCell9;
private XRTableRow xrTableRow6;
private XRTableCell xrTableCell10;
private XRTableRow xrTableRow7;
private XRTableCell PeriodCell;
private XRTable DetailTableHeader;
private XRTableRow xrTableRow9;
private XRTableCell xrTableCell16;
private XRTableCell xrTableCell19;
private XRTableCell xrTableCell13;
private XRTableCell xrTableCell21;
private XRTableCell xrTableCell14;
private XRTableRow xrTableRow8;
private XRTableCell LocationCell;
private XRTableRow xrTableRow11;
private XRTableCell xrTableCell4;
private XRTableCell xrTableCell5;
private XRTableCell xrTableCell22;
private XRTableCell xrTableCell23;
private XRTableCell xrTableCell25;
private XRTableCell xrTableCell26;
private XRTableCell xrTableCell28;
private XRTableRow xrTableRow12;
private XRTableCell xrTableCell29;
private XRTableCell xrTableCell30;
private XRTableCell xrTableCell31;
private XRTableCell xrTableCell32;
private XRTableCell xrTableCell33;
private XRTableCell xrTableCell34;
private XRTableCell xrTableCell35;
private XRTableCell xrTableCell36;
private XRTableCell xrTableCell37;
private XRTableRow xrTableRow13;
private XRTableCell xrTableCell38;
private XRTableCell xrTableCell39;
private XRTableCell xrTableCell40;
private XRTableCell xrTableCell41;
private XRTableCell xrTableCell42;
private XRTableCell xrTableCell43;
private XRTableCell xrTableCell44;
private XRTableCell xrTableCell45;
private XRTableCell xrTableCell46;
private XRTable DetailTable;
private XRTableRow DetailRow;
private XRTableCell xrTableCell59;
private XRTableCell xrTableCell60;
private XRTableCell xrTableCell61;
private XRTableCell xrTableCell62;
private XRTableCell xrTableCell63;
private XRTableCell xrTableCell64;
private XRTableCell xrTableCell65;
private XRTableCell xrTableCell66;
private XRTableCell xrTableCell67;
private GroupHeaderBand GroupHeaderLine;
private XRLine xrLine2;
private ReportFooterBand ReportFooter;
private XRLabel DateTimeLabel;
private XRLabel DateTimeCaptionLabel;
}
}
| |
/* ====================================================================
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.UserModel
{
using System.Globalization;
using System;
using System.Text.RegularExpressions;
using System.Text;
/// <summary>
/// Contains methods for dealing with Excel dates.
/// @author Michael Harhen
/// @author Glen Stampoultzis (glens at apache.org)
/// @author Dan Sherman (dsherman at Isisph.com)
/// @author Hack Kampbjorn (hak at 2mba.dk)
/// @author Alex Jacoby (ajacoby at gmail.com)
/// @author Pavel Krupets (pkrupets at palmtreebusiness dot com)
/// @author Thies Wellpott
/// </summary>
public class DateUtil
{
public const int SECONDS_PER_MINUTE = 60;
public const int MINUTES_PER_HOUR = 60;
public const int HOURS_PER_DAY = 24;
public const int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE);
private const int BAD_DATE = -1; // used to specify that date Is invalid
public const long DAY_MILLISECONDS = 24 * 60 * 60 * 1000;
private static readonly char[] TIME_SEPARATOR_PATTERN = new char[] { ':' };
/// <summary>
/// Given a Calendar, return the number of days since 1899/12/31.
/// </summary>
/// <param name="cal">the date</param>
/// <param name="use1904windowing">if set to <c>true</c> [use1904windowing].</param>
/// <returns>number of days since 1899/12/31</returns>
public static int AbsoluteDay(DateTime cal, bool use1904windowing)
{
int daynum = (cal - new DateTime(1899, 12, 31)).Days;
if (cal > new DateTime(1900, 3, 1) && use1904windowing)
{
daynum++;
}
return daynum;
}
/// <summary>
/// Given a Date, Converts it into a double representing its internal Excel representation,
/// which Is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds.
/// </summary>
/// <param name="date">Excel representation of Date (-1 if error - test for error by Checking for less than 0.1)</param>
/// <returns>the Date</returns>
public static double GetExcelDate(DateTime date)
{
return GetExcelDate(date, false);
}
/// <summary>
/// Gets the excel date.
/// </summary>
/// <param name="year">The year.</param>
/// <param name="month">The month.</param>
/// <param name="day">The day.</param>
/// <param name="hour">The hour.</param>
/// <param name="minute">The minute.</param>
/// <param name="second">The second.</param>
/// <param name="use1904windowing">Should 1900 or 1904 date windowing be used?</param>
/// <returns></returns>
public static double GetExcelDate(int year, int month, int day, int hour, int minute, int second, bool use1904windowing)
{
if ((!use1904windowing && year < 1900) //1900 date system must bigger than 1900
|| (use1904windowing && year < 1904)) //1904 date system must bigger than 1904
{
return BAD_DATE;
}
DateTime startdate;
if (use1904windowing)
{
startdate = new DateTime(1904, 1, 1);
}
else
{
startdate = new DateTime(1900, 1, 1);
}
int nextyearmonth = 0;
if (month > 12)
{
nextyearmonth = month - 12;
month = 12;
}
int nextmonthday = 0;
if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12))
{
//big month
if (day > 31)
{
nextmonthday = day - 31;
day = 31;
}
}
else if ((month == 4 || month == 6 || month == 9 || month == 11))
{
//small month
if (day > 30)
{
nextmonthday = day - 30;
day = 30;
}
}
else if (DateTime.IsLeapYear(year))
{
//Feb. with leap year
if (day > 29)
{
nextmonthday = day - 29;
day = 29;
}
}
else
{
//Feb without leap year
if (day > 28)
{
nextmonthday = day - 28;
day = 28;
}
}
if (day <= 0)
{
nextmonthday = day - 1;
day = 1;
}
DateTime date = new DateTime(year, month, day, hour, minute, second);
date = date.AddMonths(nextyearmonth);
date = date.AddDays(nextmonthday);
double value = (date - startdate).TotalDays + 1;
if (!use1904windowing && value >= 60)
{
value++;
}
else if (use1904windowing)
{
value--;
}
return value;
}
/// <summary>
/// Given a Date, Converts it into a double representing its internal Excel representation,
/// which Is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds.
/// </summary>
/// <param name="date">The date.</param>
/// <param name="use1904windowing">Should 1900 or 1904 date windowing be used?</param>
/// <returns>Excel representation of Date (-1 if error - test for error by Checking for less than 0.1)</returns>
public static double GetExcelDate(DateTime date, bool use1904windowing)
{
if ((!use1904windowing && date.Year < 1900) //1900 date system must bigger than 1900
|| (use1904windowing && date.Year < 1904)) //1904 date system must bigger than 1904
{
return BAD_DATE;
}
DateTime startdate;
if (use1904windowing)
{
startdate = new DateTime(1904, 1, 1);
}
else
{
startdate = new DateTime(1900, 1, 1);
}
double value = (date - startdate).TotalDays + 1;
if (!use1904windowing && value >= 60)
{
value++;
}
else if (use1904windowing)
{
value--;
}
return value;
}
/// <summary>
/// Given an Excel date with using 1900 date windowing, and converts it to a java.util.Date.
/// Excel Dates and Times are stored without any timezone
/// information. If you know (through other means) that your file
/// uses a different TimeZone to the system default, you can use
/// this version of the getJavaDate() method to handle it.
/// </summary>
/// <param name="date">The Excel date.</param>
/// <returns>null if date is not a valid Excel date</returns>
public static DateTime GetJavaDate(double date)
{
return GetJavaDate(date, false);
}
/**
* Given an Excel date with either 1900 or 1904 date windowing,
* Converts it to a Date.
*
* NOTE: If the default <c>TimeZone</c> in Java uses Daylight
* Saving Time then the conversion back to an Excel date may not give
* the same value, that Is the comparison
* <CODE>excelDate == GetExcelDate(GetJavaDate(excelDate,false))</CODE>
* Is not always true. For example if default timezone Is
* <c>Europe/Copenhagen</c>, on 2004-03-28 the minute after
* 01:59 CET Is 03:00 CEST, if the excel date represents a time between
* 02:00 and 03:00 then it Is Converted to past 03:00 summer time
*
* @param date The Excel date.
* @param use1904windowing true if date uses 1904 windowing,
* or false if using 1900 date windowing.
* @return Java representation of the date, or null if date Is not a valid Excel date
* @see TimeZone
*/
public static DateTime GetJavaDate(double date, bool use1904windowing)
{
/*if (!IsValidExcelDate(date))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid Excel date double value: {0}", date));
}
int startYear = 1900;
int dayAdjust = -1; // Excel thinks 2/29/1900 Is a valid date, which it Isn't
int wholeDays = (int)Math.Floor(date);
if (use1904windowing)
{
startYear = 1904;
dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day
}
else if (wholeDays < 61)
{
// Date Is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists
// If Excel date == 2/29/1900, will become 3/1/1900 in Java representation
dayAdjust = 0;
}
DateTime startdate = new DateTime(startYear, 1, 1);
startdate = startdate.AddDays(wholeDays + dayAdjust - 1);
double millisecondsInDay = (int)((date - wholeDays) *
DAY_MILLISECONDS + 0.5);
return startdate.AddMilliseconds(millisecondsInDay);*/
return GetJavaCalendar(date, use1904windowing);
}
public static void SetCalendar(ref DateTime calendar, int wholeDays,
int millisecondsInDay, bool use1904windowing)
{
int startYear = 1900;
int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't
if (use1904windowing)
{
startYear = 1904;
dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day
}
else if (wholeDays < 61)
{
// Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists
// If Excel date == 2/29/1900, will become 3/1/1900 in Java representation
dayAdjust = 0;
}
DateTime dt = (new DateTime(startYear, 1, 1)).AddDays(wholeDays + dayAdjust - 1).AddMilliseconds(millisecondsInDay);
calendar = dt;
}
/// <summary>
/// Get EXCEL date as Java Calendar (with default time zone). This is like GetJavaDate(double, boolean) but returns a Calendar object.
/// </summary>
/// <param name="date">The Excel date.</param>
/// <param name="use1904windowing">true if date uses 1904 windowing, or false if using 1900 date windowing.</param>
/// <returns>null if date is not a valid Excel date</returns>
public static DateTime GetJavaCalendar(double date, bool use1904windowing)
{
if (!IsValidExcelDate(date))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid Excel date double value: {0}", date));
}
int wholeDays = (int)Math.Floor(date);
int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5);
DateTime calendar;
calendar = DateTime.Now; // using default time-zone
SetCalendar(ref calendar, wholeDays, millisecondsInDay, use1904windowing);
return calendar;
}
/// <summary>
/// Converts a string of format "HH:MM" or "HH:MM:SS" to its (Excel) numeric equivalent
/// </summary>
/// <param name="timeStr">The time STR.</param>
/// <returns> a double between 0 and 1 representing the fraction of the day</returns>
public static double ConvertTime(String timeStr)
{
try
{
return ConvertTimeInternal(timeStr);
}
catch (FormatException e)
{
String msg = "Bad time format '" + timeStr
+ "' expected 'HH:MM' or 'HH:MM:SS' - " + e.Message;
throw new ArgumentException(msg);
}
}
/// <summary>
/// Converts the time internal.
/// </summary>
/// <param name="timeStr">The time STR.</param>
/// <returns></returns>
private static double ConvertTimeInternal(String timeStr)
{
int len = timeStr.Length;
if (len < 4 || len > 8)
{
throw new FormatException("Bad length");
}
String[] parts = timeStr.Split(TIME_SEPARATOR_PATTERN);
String secStr;
switch (parts.Length)
{
case 2: secStr = "00"; break;
case 3: secStr = parts[2]; break;
default:
throw new FormatException("Expected 2 or 3 fields but got (" + parts.Length + ")");
}
String hourStr = parts[0];
String minStr = parts[1];
int hours = ParseInt(hourStr, "hour", HOURS_PER_DAY);
int minutes = ParseInt(minStr, "minute", MINUTES_PER_HOUR);
int seconds = ParseInt(secStr, "second", SECONDS_PER_MINUTE);
double totalSeconds = seconds + (minutes + (hours) * 60) * 60;
return totalSeconds / (SECONDS_PER_DAY);
}
/// <summary>
/// Given a format ID and its format String, will Check to see if the
/// format represents a date format or not.
/// Firstly, it will Check to see if the format ID corresponds to an
/// internal excel date format (eg most US date formats)
/// If not, it will Check to see if the format string only Contains
/// date formatting Chars (ymd-/), which covers most
/// non US date formats.
/// </summary>
/// <param name="formatIndex">The index of the format, eg from ExtendedFormatRecord.GetFormatIndex</param>
/// <param name="formatString">The format string, eg from FormatRecord.GetFormatString</param>
/// <returns>
/// <c>true</c> if [is A date format] [the specified format index]; otherwise, <c>false</c>.
/// </returns>
public static bool IsADateFormat(int formatIndex, String formatString)
{
// First up, Is this an internal date format?
if (IsInternalDateFormat(formatIndex))
{
return true;
}
// If we didn't Get a real string, it can't be
if (formatString == null || formatString.Length == 0)
{
return false;
}
String fs = formatString;
// If it end in ;@, that's some crazy dd/mm vs mm/dd
// switching stuff, which we can ignore
fs = Regex.Replace(fs, ";@", "");
StringBuilder sb = new StringBuilder(fs.Length);
for (int i = 0; i < fs.Length; i++)
{
char c = fs[i];
if (i < fs.Length - 1)
{
char nc = fs[i + 1];
if (c == '\\')
{
switch (nc)
{
case '-':
case ',':
case '.':
case ' ':
case '\\':
// skip current '\' and continue to the next char
continue;
}
}
else if (c == ';' && nc == '@')
{
i++;
// skip ";@" duplets
continue;
}
}
sb.Append(c);
}
fs = sb.ToString();
// short-circuit if it indicates elapsed time: [h], [m] or [s]
if (Regex.IsMatch(fs, "^\\[([hH]+|[mM]+|[sS]+)\\]"))
{
return true;
}
// If it starts with [$-...], then could be a date, but
// who knows what that starting bit Is all about
fs = Regex.Replace(fs, "^\\[\\$\\-.*?\\]", "");
// If it starts with something like [Black] or [Yellow],
// then it could be a date
fs = Regex.Replace(fs, "^\\[[a-zA-Z]+\\]", "");
// You're allowed something like dd/mm/yy;[red]dd/mm/yy
// which would place dates before 1900/1904 in red
// For now, only consider the first one
if (fs.IndexOf(';') > 0 && fs.IndexOf(';') < fs.Length - 1)
{
fs = fs.Substring(0, fs.IndexOf(';'));
}
// Otherwise, Check it's only made up, in any case, of:
// y m d h s - / , . :
// optionally followed by AM/PM
// Delete any string literals.
fs = Regex.Replace(fs, @"""[^""\\]*(?:\\.[^""\\]*)*""", "");
if (Regex.IsMatch(fs, @"^[\[\]yYmMdDhHsS\-/,. :\""\\]+0*[ampAMP/]*$"))
{
return true;
}
return false;
}
/// <summary>
/// Converts a string of format "YYYY/MM/DD" to its (Excel) numeric equivalent
/// </summary>
/// <param name="dateStr">The date STR.</param>
/// <returns>a double representing the (integer) number of days since the start of the Excel epoch</returns>
public static DateTime ParseYYYYMMDDDate(String dateStr)
{
try
{
return ParseYYYYMMDDDateInternal(dateStr);
}
catch (FormatException e)
{
String msg = "Bad time format " + dateStr
+ " expected 'YYYY/MM/DD' - " + e.Message;
throw new ArgumentException(msg);
}
}
/// <summary>
/// Parses the YYYYMMDD date internal.
/// </summary>
/// <param name="timeStr">The time string.</param>
/// <returns></returns>
private static DateTime ParseYYYYMMDDDateInternal(String timeStr)
{
if (timeStr.Length != 10)
{
throw new FormatException("Bad length");
}
String yearStr = timeStr.Substring(0, 4);
String monthStr = timeStr.Substring(5, 2);
String dayStr = timeStr.Substring(8, 2);
int year = ParseInt(yearStr, "year", short.MinValue, short.MaxValue);
int month = ParseInt(monthStr, "month", 1, 12);
int day = ParseInt(dayStr, "day", 1, 31);
DateTime cal = new DateTime(year, month, day, 0, 0, 0);
return cal;
}
/// <summary>
/// Parses the int.
/// </summary>
/// <param name="strVal">The string value.</param>
/// <param name="fieldName">Name of the field.</param>
/// <param name="rangeMax">The range max.</param>
/// <returns></returns>
private static int ParseInt(String strVal, String fieldName, int rangeMax)
{
return ParseInt(strVal, fieldName, 0, rangeMax - 1);
}
/// <summary>
/// Parses the int.
/// </summary>
/// <param name="strVal">The STR val.</param>
/// <param name="fieldName">Name of the field.</param>
/// <param name="lowerLimit">The lower limit.</param>
/// <param name="upperLimit">The upper limit.</param>
/// <returns></returns>
private static int ParseInt(String strVal, String fieldName, int lowerLimit, int upperLimit)
{
int result;
try
{
result = int.Parse(strVal, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new FormatException("Bad int format '" + strVal + "' for " + fieldName + " field");
}
if (result < lowerLimit || result > upperLimit)
{
throw new FormatException(fieldName + " value (" + result
+ ") is outside the allowable range(0.." + upperLimit + ")");
}
return result;
}
/// <summary>
/// Given a format ID this will Check whether the format represents an internal excel date format or not.
/// </summary>
/// <param name="format">The format.</param>
public static bool IsInternalDateFormat(int format)
{
bool retval = false;
switch (format)
{
// Internal Date Formats as described on page 427 in
// Microsoft Excel Dev's Kit...
case 0x0e:
case 0x0f:
case 0x10:
case 0x11:
case 0x12:
case 0x13:
case 0x14:
case 0x15:
case 0x16:
case 0x2d:
case 0x2e:
case 0x2f:
retval = true;
break;
default:
retval = false;
break;
}
return retval;
}
/// <summary>
/// Check if a cell Contains a date
/// Since dates are stored internally in Excel as double values
/// we infer it Is a date if it Is formatted as such.
/// </summary>
/// <param name="cell">The cell.</param>
public static bool IsCellDateFormatted(ICell cell)
{
if (cell == null) return false;
bool bDate = false;
double d = cell.NumericCellValue;
if (DateUtil.IsValidExcelDate(d))
{
ICellStyle style = cell.CellStyle;
if (style == null)
return false;
int i = style.DataFormat;
String f = style.GetDataFormatString();
bDate = IsADateFormat(i, f);
}
return bDate;
}
/// <summary>
/// Check if a cell contains a date, Checking only for internal excel date formats.
/// As Excel stores a great many of its dates in "non-internal" date formats, you will not normally want to use this method.
/// </summary>
/// <param name="cell">The cell.</param>
public static bool IsCellInternalDateFormatted(ICell cell)
{
if (cell == null) return false;
bool bDate = false;
double d = cell.NumericCellValue;
if (DateUtil.IsValidExcelDate(d))
{
ICellStyle style = cell.CellStyle;
int i = style.DataFormat;
bDate = IsInternalDateFormat(i);
}
return bDate;
}
/// <summary>
/// Given a double, Checks if it Is a valid Excel date.
/// </summary>
/// <param name="value">the double value.</param>
/// <returns>
/// <c>true</c> if [is valid excel date] [the specified value]; otherwise, <c>false</c>.
/// </returns>
public static bool IsValidExcelDate(double value)
{
//return true;
return value > -Double.Epsilon;
}
}
}
| |
// 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 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.BigQuery.Connection.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedConnectionServiceClientTest
{
[xunit::FactAttribute]
public void CreateConnectionRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.CreateConnection(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConnectionRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.CreateConnectionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.CreateConnectionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateConnection()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.CreateConnection(request.Parent, request.Connection, request.ConnectionId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConnectionAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.CreateConnectionAsync(request.Parent, request.Connection, request.ConnectionId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.CreateConnectionAsync(request.Parent, request.Connection, request.ConnectionId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateConnectionResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.CreateConnection(request.ParentAsLocationName, request.Connection, request.ConnectionId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConnectionResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.CreateConnectionAsync(request.ParentAsLocationName, request.Connection, request.ConnectionId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.CreateConnectionAsync(request.ParentAsLocationName, request.Connection, request.ConnectionId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnectionRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.GetConnection(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.GetConnectionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.GetConnectionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnection()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.GetConnection(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.GetConnectionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.GetConnectionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnectionResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.GetConnection(request.ConnectionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.GetConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.GetConnectionAsync(request.ConnectionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.GetConnectionAsync(request.ConnectionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateConnectionRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.UpdateConnection(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateConnectionRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.UpdateConnectionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.UpdateConnectionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateConnection()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.UpdateConnection(request.Name, request.Connection, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateConnectionAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.UpdateConnectionAsync(request.Name, request.Connection, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.UpdateConnectionAsync(request.Name, request.Connection, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateConnectionResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.UpdateConnection(request.ConnectionName, request.Connection, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateConnectionResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
CloudResource = new CloudResourceProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.UpdateConnectionAsync(request.ConnectionName, request.Connection, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.UpdateConnectionAsync(request.ConnectionName, request.Connection, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConnectionRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteConnection(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConnectionRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteConnectionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConnectionAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConnection()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteConnection(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConnectionAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteConnectionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConnectionAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConnectionResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteConnection(request.ConnectionName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConnectionResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteConnectionAsync(request.ConnectionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConnectionAsync(request.ConnectionName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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);
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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));
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request.Resource, request.Options);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, request.Options, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, request.Options, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request.ResourceAsResourceName, request.Options);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.ResourceAsResourceName, request.Options, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.ResourceAsResourceName, request.Options, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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);
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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));
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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);
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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));
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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);
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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));
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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);
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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));
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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);
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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));
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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);
ConnectionServiceClient client = new ConnectionServiceClientImpl(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<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
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));
ConnectionServiceClient client = new ConnectionServiceClientImpl(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.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace WEB.Models
{
public partial class Field
{
[NotMapped]
public string NewVariable
{
get
{
if (FieldType == FieldType.Guid) return "newGuid";
if (FieldType == FieldType.Int) return "newInt";
if (FieldType == FieldType.SmallInt) return "newInt";
if (FieldType == FieldType.TinyInt) return "newInt";
if (FieldType == FieldType.Date) return "newDate";
if (CustomType == CustomType.String) return "newString"; // changed from string.Empty to newString as string.Empty appears to be server side and this should be client side code?
throw new NotImplementedException("NewVariable for Type: " + FieldType);
}
}
[NotMapped]
public string EmptyValue
{
get
{
if (FieldType == FieldType.Guid) return "Guid.Empty";
if (FieldType == FieldType.Int) return "0";
if (FieldType == FieldType.SmallInt) return "0";
if (FieldType == FieldType.TinyInt) return "0";
if (FieldType == FieldType.Date) return "DateTime.MinValue";
if (CustomType == CustomType.String) return "string.Empty";
throw new NotImplementedException("EmptyValue for Type: " + FieldType);
}
}
[NotMapped]
public CustomType CustomType
{
get
{
switch (FieldType)
{
case FieldType.Enum:
return CustomType.Enum;
case FieldType.Bit:
return CustomType.Boolean;
case FieldType.Date:
case FieldType.DateTime:
case FieldType.SmallDateTime:
return CustomType.Date;
case FieldType.Guid:
return CustomType.Guid;
case FieldType.Int:
case FieldType.TinyInt:
case FieldType.SmallInt:
case FieldType.Decimal:
return CustomType.Number;
case FieldType.nVarchar:
case FieldType.nText:
case FieldType.Text:
case FieldType.Varchar:
return CustomType.String;
case FieldType.VarBinary:
return CustomType.Binary;
case FieldType.Geometry:
return CustomType.Geometry;
}
throw new NotImplementedException("CustomType: " + FieldType.ToString());
}
}
[NotMapped]
public string ControllerConstraintType
{
get
{
switch (FieldType)
{
case FieldType.Bit:
return "bool";
case FieldType.Date:
case FieldType.DateTime:
case FieldType.SmallDateTime:
return "DateTime";
case FieldType.Decimal:
return "decimal";
case FieldType.Guid:
return "Guid";
case FieldType.Int:
case FieldType.TinyInt:
case FieldType.SmallInt:
return "int";
case FieldType.nVarchar:
case FieldType.nText:
case FieldType.Text:
case FieldType.Varchar:
return "string";
}
throw new NotImplementedException("ControllerConstraintType: " + FieldType.ToString());
}
}
public static string GetNetType(FieldType fieldType, bool isNullable, Lookup lookup)
{
switch (fieldType)
{
case FieldType.Enum:
// this is used when using an enum as a search field, needs to get the type as int
//if(Lookup == null) return "int" + (IsNullable ? "?" : string.Empty);
if (lookup == null) throw new Exception("Lookup has not been set for an Enum field");
return lookup.Name + (isNullable ? "?" : string.Empty);
case FieldType.Bit:
return "bool" + (isNullable ? "?" : string.Empty);
case FieldType.Date:
case FieldType.DateTime:
case FieldType.SmallDateTime:
return "DateTime" + (isNullable ? "?" : string.Empty);
case FieldType.Guid:
return "Guid" + (isNullable ? "?" : string.Empty);
case FieldType.Int:
return "int" + (isNullable ? "?" : string.Empty);
case FieldType.TinyInt:
return "byte" + (isNullable ? "?" : string.Empty);
case FieldType.SmallInt:
return "short" + (isNullable ? "?" : string.Empty);
case FieldType.Decimal:
return "decimal" + (isNullable ? "?" : string.Empty);
case FieldType.nVarchar:
case FieldType.nText:
case FieldType.Text:
case FieldType.Varchar:
return "string";
case FieldType.VarBinary:
return "byte[]";
case FieldType.Geometry:
return "System.Data.Entity.Spatial.DbGeometry";
}
throw new NotImplementedException("NetType: " + fieldType.ToString());
}
[NotMapped]
public string NetType
{
get
{
return GetNetType(FieldType, IsNullable, Lookup);
}
}
[NotMapped]
public string ControllerSearchParams
{
get
{
var netType = (new Field { Name = Name, Lookup = Lookup, FieldType = FieldType, IsNullable = true }).NetType;
if (SearchType == SearchType.Range)
return "[FromUri]" + netType + " from" + Name + " = null, [FromUri]" + netType + " to" + Name + " = null";
else
return "[FromUri]" + netType + " " + Name.ToCamelCase() + " = null";
}
}
[NotMapped]
public string ListFieldHtml
{
get
{
if (Entity.RelationshipsAsChild.Any(r => r.RelationshipFields.Any(f => f.ChildFieldId == FieldId)))
{
var relationship = Entity.GetParentSearchRelationship(this);
return $"{{{{ { Entity.CamelCaseName}.{ relationship.ParentName.ToCamelCase()}.{relationship.ParentField.Name.ToCamelCase()} }}}}";
}
else
{
if (CustomType == CustomType.Date)
{
if (IsNullable)
return $"{{{{ { Entity.CamelCaseName}.{ Name.ToCamelCase()} === null ? \"\" : vm.moment({ Entity.CamelCaseName}.{ Name.ToCamelCase()}).format('DD MMM YYYY{(FieldType == FieldType.Date ? string.Empty : " HH:mm" + (FieldType == FieldType.SmallDateTime ? "" : ":ss"))}') }}}}";
else
return $"{{{{ vm.moment({ Entity.CamelCaseName}.{ Name.ToCamelCase()}).format('DD MMM YYYY{(FieldType == FieldType.Date ? string.Empty : " HH:mm" + (FieldType == FieldType.SmallDateTime ? "" : ":ss"))}') }}}}";
}
else if (CustomType == CustomType.Enum)
return $"{{{{ vm.appSettings.find(vm.appSettings.{Lookup.Name.ToCamelCase()}, {Entity.CamelCaseName}.{Name.ToCamelCase()}).label }}}}";
else if (FieldType == FieldType.Date)
return $"{{{{ { Entity.Name.ToCamelCase()}.{ Name.ToCamelCase() } | toLocaleDateString }}}}";
else if (FieldType == FieldType.Bit)
return $"{{{{ { Entity.Name.ToCamelCase()}.{ Name.ToCamelCase() } ? \"Yes\" : \"No\" }}}}";
else
return $"{{{{ { Entity.CamelCaseName}.{ Name.ToCamelCase()} }}}}";
}
}
}
public override string ToString()
{
return Name;
}
public string NotNullCheck(string fieldName)
{
if (CustomType == CustomType.String) return fieldName + " != null";
else return fieldName + ".HasValue";
}
}
public enum CustomType
{
Enum, Boolean, Date, Guid, Number, String, Binary, Geometry
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using TypeVisualiser.Geometry;
using TypeVisualiser.Messaging;
using TypeVisualiser.Model;
using TypeVisualiser.Model.Persistence;
using TypeVisualiser.UI.WpfUtilities;
namespace TypeVisualiser.UI.Views
{
/// <summary>
/// Interaction logic for Viewport.xaml
/// </summary>
public partial class Viewport
{
private Timer connectorLineFixTimer;
private bool pauseRearrangeEvents;
private VisualisableTypeSubject subjectDataContext;
private VisualisedTypeViewMetadata subjectMetadata;
public Viewport()
{
}
private void AddArrowHeadToDiagramSpace(VisualisedTypeViewMetadata associate, UserControl head)
{
// Arrow head is added to diagram before the connector line.
//this.DiagramSpace.Children.Add(head);
//head.DataContext = null;
//var relocateHeadArrow = new Action(() =>
// {
// if (this.pauseRearrangeEvents)
// {
// return;
// }
// ConnectionRoute route = ConnectionRoute.FindBestConnectionRoute(this.subjectMetadata.Area, associate.Area, IsOverlappingWithOtherControls);
// associate.LineRoute = route;
// route.CalculateArrowHeadRotationAndTranslation(ConnectionRoute.LineEnd.ArrowHead, head.ActualWidth, head.ActualHeight, associate.DataContext);
// // move the arrow head to position into gap between line end and the target.
// head.DataContext = route;
// Canvas.SetLeft(head, route.To.X);
// Canvas.SetTop(head, route.To.Y);
// // this.LineTailDiagnostics(head, route, associate);
// });
//head.Loaded += (s, e) => relocateHeadArrow();
//associate.Moved += (s, e) => Dispatcher.BeginInvoke(relocateHeadArrow);
//this.subjectMetadata.Moved += (s, e) => Dispatcher.BeginInvoke(relocateHeadArrow);
}
private void AddAssociatesToDiagram(VisualisableTypeSubject dataContext)
{
if (dataContext.Parent != null)
{
CreateAssociate(dataContext.Parent);
}
foreach (ParentAssociation implementedInterface in dataContext.ThisTypeImplements)
{
CreateAssociate(implementedInterface);
}
foreach (FieldAssociation associate in dataContext.FilteredAssociations)
{
CreateAssociate(associate);
}
// this.DiagnosticsDrawAssociateCircle();
}
private byte AddByteValue(byte value, int addend)
{
var add = (byte)addend;
var result = (byte)(value + add);
if (result > 255)
{
result = 255;
}
return result;
}
private void ClearDiagram()
{
// Clear diagram except main subject
//Trace.WriteLine("ClearDiagram:");
//this.pauseRearrangeEvents = true;
//this.allVisualisedTypes = new Dictionary<string, VisualisedTypeViewMetadata>();
//var copyOfChildren = new object[this.DiagramSpace.Children.Count];
//this.DiagramSpace.Children.CopyTo(copyOfChildren, 0);
//int clearCount = 0;
//foreach (object drawingItem in copyOfChildren)
//{
// var uiElement = drawingItem as UIElement;
// if (uiElement != null && uiElement != this.Subject)
// {
// this.DiagramSpace.Children.Remove(uiElement);
// clearCount++;
// } else
// {
// Trace.WriteLine(" Not clearing: " + drawingItem);
// }
//}
//Trace.WriteLine(" Cleared " + clearCount);
//this.pauseRearrangeEvents = false;
}
private void CreateAssociate(Association associate)
{
//var control = new ContentPresenter
// {
// DataContext = associate.AssociatedTo,
// Content = associate.AssociatedTo,
// Tag = VisualisedTypeViewMetadata.AssociateIdentifier + Guid.NewGuid()
// // To distinguish this content presenter from other usages
// };
//this.DiagramSpace.Children.Add(control);
//var metadata = new VisualisedTypeViewMetadata(control, associate);
//this.allVisualisedTypes.Add(control.Tag.ToString(), metadata);
//control.Loaded += (s, e) => OnAssociateControlLoaded(metadata);
}
private void DrawLine(VisualisedTypeViewMetadata associate)
{
//UserControl head = associate.DataContext.CreateLineHead();
//AddArrowHeadToDiagramSpace(associate, head);
//// UserControl tail = this.AddLineTail(head, associate);
//var line = new Line { SnapsToDevicePixels = true, DataContext = associate.DataContext, };
//associate.DataContext.StyleLine(line);
//this.DiagramSpace.Children.Add(line);
//var visibilityBinding = new Binding { Path = new PropertyPath("Show"), Converter = new BooleanToVisibilityConverter() };
//BindingOperations.SetBinding(line, VisibilityProperty, visibilityBinding);
//var relocateLine = new Action(() =>
// {
// if (this.pauseRearrangeEvents)
// {
// return;
// }
// ConnectionRoute route = associate.LineRoute; // Set by adding the arrow head.
// Point position = route.To.Clone();
// Canvas.SetLeft(line, position.X);
// Canvas.SetTop(line, position.Y);
// // var endPoint = new Point(Canvas.GetLeft(tail), Canvas.GetTop(tail));
// Point endPoint = route.From.Clone();
// line.X2 = position.X > endPoint.X ? -(position.X - endPoint.X) : endPoint.X - position.X;
// line.Y2 = position.Y > endPoint.Y ? -(position.Y - endPoint.Y) : endPoint.Y - position.Y;
// });
//line.Loaded += (s, e) => relocateLine();
//line.MouseLeftButtonDown += OnLineClicked;
//line.MouseEnter += OnMouseOverLine;
//line.MouseLeave += OnMouseLeaveLine;
//associate.Moved += (s, e) => Dispatcher.BeginInvoke(relocateLine);
//this.subjectMetadata.Moved += (s, e) => Dispatcher.BeginInvoke(relocateLine);
}
/// <summary>
/// Determines whether the given area is overlapping with other areas occupied by controls.
/// </summary>
/// <param name="proposedArea">The proposed area to compare with all others.</param>
/// <returns>A result object indicating if an overlap exists or the closest object and distance to it.</returns>
private ProximityTestResult IsOverlappingWithOtherControls(Area proposedArea)
{
//IEnumerable<ProximityTestResult> proximities = this.allVisualisedTypes.Values.Select(knownAssociation => knownAssociation.Area.OverlapsWith(proposedArea)).ToList();
//bool overlapsWith = proximities.Any(x => x.Proximity == Proximity.Overlapping);
//if (overlapsWith)
//{
// return new ProximityTestResult(Proximity.Overlapping);
//}
//IOrderedEnumerable<ProximityTestResult> veryClose = proximities.Where(x => x.Proximity == Proximity.VeryClose).OrderBy(x => x.DistanceToClosestObject);
//if (veryClose.Any())
//{
// return veryClose.First();
//}
//return new ProximityTestResult(Proximity.NotOverlapping);
return null;
}
private void OnAssociateControlLoaded(VisualisedTypeViewMetadata control)
{
PositionTheAssociateControl(control.Container, control.DataContext);
control.Area.Update(control.Container);
DrawLine(control);
}
private void OnConnectorLineFixTimerElapsed(object sender, ElapsedEventArgs e)
{
//// This fixes the connector lines being drawn out of co-ord 0,0 of subject. Caused by the actual width and height not being available soon enough.
//this.connectorLineFixTimer.Elapsed -= OnConnectorLineFixTimerElapsed;
//this.connectorLineFixTimer.Stop();
//this.connectorLineFixTimer.Dispose();
//this.connectorLineFixTimer = null;
//// TODO hack to fix line connectors by moving the subject a fraction has been removed.
//// Dispatcher.BeginInvoke(() => OnSubjectDragDelta(this, new DragDeltaEventArgs(0.01, 0.01) { Source = this.Subject }), DispatcherPriority.Normal);
//Dispatcher.BeginInvoke(() => Controller.ViewReady(), DispatcherPriority.Normal);
}
private void OnLineClicked(object sender, MouseButtonEventArgs e)
{
var association = ((Line)sender).DataContext as FieldAssociation;
if (association != null)
{
new UsageDialog().ShowDialog(Properties.Resources.ApplicationName, this.subjectDataContext.Name, this.subjectDataContext.Modifiers.TypeTextName, association);
e.Handled = true;
}
}
private void OnMainPresenterDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
//if (e.NewValue == null)
//{
// return;
//}
//Dispatcher.BeginInvoke(new Action(() =>
// {
// if (Controller.Subject != null)
// {
// this.Subject.DataContext = Controller.Subject;
// OnSubjectLoaded(null, null);
// }
// }));
}
private void OnMouseLeaveLine(object sender, MouseEventArgs e)
{
var line = e.OriginalSource as Line;
if (line == null)
{
return;
}
var brush = (Brush)line.Tag;
line.Tag = line.Stroke;
line.Stroke = brush;
}
private void OnMouseOverLine(object sender, MouseEventArgs e)
{
var line = e.OriginalSource as Line;
if (line == null)
{
return;
}
SolidColorBrush highlightBrush;
if (line.Tag == null)
{
const byte Highlight = 60;
var brush = line.Stroke as SolidColorBrush;
line.Tag = brush;
if (brush == null)
{
throw new NotSupportedException("Line stroke brush must be a Solid Color Brush.");
}
var highlightColor = new Color { A = 255, R = AddByteValue(brush.Color.R, Highlight), G = AddByteValue(brush.Color.G, Highlight), B = AddByteValue(brush.Color.B, Highlight) };
highlightBrush = new SolidColorBrush(highlightColor);
} else
{
highlightBrush = (SolidColorBrush)line.Tag;
}
line.Tag = line.Stroke;
line.Stroke = highlightBrush;
}
private void OnSubjectLoaded(object sender, RoutedEventArgs e)
{
//if (this.Subject.DataContext == null)
//{
// // DataContext of subject hasn't been set yet.
// return;
//}
//if (this.allVisualisedTypes.Any())
//{
// // Already loaded. Diagram is immutable, create a new tab. Add to stop reloading on tab change.
// return;
//}
//this.Subject.Tag = VisualisedTypeViewMetadata.SubjectIdentifier;
//// Identify this usage of the Data Template / Content Presenter as the main subject.
//this.subjectMetadata = new VisualisedTypeViewMetadata(this.Subject, Association.Subject);
//if (this.subjectMetadata.Area.Height < 1)
//{
// UpdateLayout(); // I know this is not a good idea to overuse, however its necessary here to ensure the layout system has calculated the actual width and height.
// this.subjectMetadata = new VisualisedTypeViewMetadata(this.Subject, Association.Subject);
//}
//this.allVisualisedTypes.Add(VisualisedTypeViewMetadata.SubjectIdentifier, this.subjectMetadata);
//this.subjectDataContext = this.Subject.DataContext as VisualisableTypeSubject;
//if (this.subjectDataContext == null)
//{
// throw new InvalidCastException("Subject is not a " + typeof(VisualisableTypeSubject).Name);
//}
//// new ViewportDiagnostics().SubjectDiagnostics(this.Subject);
//AddAssociatesToDiagram(this.subjectDataContext);
//// To fix the connector lines problem a timer is used to cause a drag event on the subject which then redraws the lines.
//// Tried queueing a job on the dispatcher to wait for actual width and height to be updated from 0, but it doesnt update until all drawing is finished.
//// Also tried changing the onloaded event from the subject content presenter to the canvas with no effect.
//this.connectorLineFixTimer = new Timer(500);
//this.connectorLineFixTimer.Elapsed += OnConnectorLineFixTimerElapsed;
//this.connectorLineFixTimer.Start();
}
private void PositionTheAssociateControl(FrameworkElement control, Association associate)
{
Area proposedArea = associate.ProposePosition(control.ActualWidth, control.ActualHeight, this.subjectMetadata.Area, IsOverlappingWithOtherControls);
Canvas.SetLeft(control, proposedArea.TopLeft.X);
Canvas.SetTop(control, proposedArea.TopLeft.Y);
}
}
}
| |
// Copyright 2015, Catlike Coding, http://catlikecoding.com
using UnityEngine;
namespace CatlikeCoding.Noise {
/// <summary>A collection of methods to sample Value Noise.</summary>
/// <description>
/// All noise methods instead produce values from 0 to 1.
///
/// Tiled versions have offsets used for moving the tiling area to another spot in the noise domain. For the tiling dimensions,
/// the integer parts are used to offset the cells, while the fractional parts are used to offset sampling within the tile.
/// Animating these offsets will result in popping when they cross integer boundaries as the sampling switches to another tile.
/// Frequency and lacunarity are integers for the tiled versions because they must be aligned with cell boundaries.
/// </description>
public static class ValueNoise {
/// <summary>Sample 2D Value noise.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 2D.</param>
/// <param name="frequency">Frequency of the noise.</param>
public static float Sample2D (Vector2 point, float frequency) {
point.x *= frequency;
point.y *= frequency;
int ix0 = NoiseMath.FloorToInt(point.x);
int iy0 = NoiseMath.FloorToInt(point.y);
float tx = point.x - ix0;
float ty = point.y - iy0;
ix0 &= NoiseMath.hashMask;
iy0 &= NoiseMath.hashMask;
int ix1 = ix0 + 1;
int iy1 = iy0 + 1;
int h0 = NoiseMath.hash[ix0];
int h1 = NoiseMath.hash[ix1];
int h00 = NoiseMath.hash[h0 + iy0];
int h10 = NoiseMath.hash[h1 + iy0];
int h01 = NoiseMath.hash[h0 + iy1];
int h11 = NoiseMath.hash[h1 + iy1];
float a = h00;
float b = h10 - h00;
float c = h01 - h00;
float d = h11 - h01 - h10 + h00;
tx = NoiseMath.Smooth(tx);
ty = NoiseMath.Smooth(ty);
return (a + b * tx + (c + d * tx) * ty) * (1f / NoiseMath.hashMask);
}
/// <summary>Sample multi-frequency 2D Value noise.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 2D.</param>
/// <param name="frequency">Base frequency.</param>
/// <param name="octaves">Amount of octaves.</param>
/// <param name="lacunarity">Frequency multiplier for successive octaves.</param>
/// <param name="persistence">Amplitude multiplier for succesive octaves.</param>
public static float Sample2D (
Vector2 point, float frequency, int octaves, float lacunarity, float persistence
) {
float amplitude = 1f, range = 1f, sum = Sample2D(point, frequency);
while (--octaves > 0) {
frequency *= lacunarity;
amplitude *= persistence;
range += amplitude;
sum += Sample2D(point, frequency) * amplitude;
}
return sum * (1f / range);
}
/// <summary>Sample 2D Value noise, tiled in the X dimension.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 2D.</param>
/// <param name="xOffset">X offset of the tiling domain.</param>
/// <param name="frequency">Frequency of the noise.</param>
public static float Sample2DTiledX (Vector2 point, int xOffset, int frequency) {
if (frequency == 0) {
return 0f;
}
point.x *= frequency;
point.y *= frequency;
int ix0 = NoiseMath.FloorToInt(point.x);
int iy0 = NoiseMath.FloorToInt(point.y);
float tx = point.x - ix0;
float ty = point.y - iy0;
ix0 %= frequency;
if (ix0 < 0) {
ix0 += frequency;
}
iy0 &= NoiseMath.hashMask;
int ix1 = ((ix0 + 1) % frequency + xOffset) & NoiseMath.hashMask;
int iy1 = iy0 + 1;
ix0 = (ix0 + xOffset) & NoiseMath.hashMask;
int h0 = NoiseMath.hash[ix0];
int h1 = NoiseMath.hash[ix1];
int h00 = NoiseMath.hash[h0 + iy0];
int h10 = NoiseMath.hash[h1 + iy0];
int h01 = NoiseMath.hash[h0 + iy1];
int h11 = NoiseMath.hash[h1 + iy1];
float a = h00;
float b = h10 - h00;
float c = h01 - h00;
float d = h11 - h01 - h10 + h00;
tx = NoiseMath.Smooth(tx);
ty = NoiseMath.Smooth(ty);
return (a + b * tx + (c + d * tx) * ty) * (1f / NoiseMath.hashMask);
}
/// <summary>Sample multi-frequency 2D Value noise, tiled in the X dimension.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 2D.</param>
/// <param name="offset">Offset of the tiling domain.</param>
/// <param name="frequency">Base frequency.</param>
/// <param name="octaves">Amount of octaves.</param>
/// <param name="lacunarity">Frequency multiplier for successive octaves.</param>
/// <param name="persistence">Amplitude multiplier for succesive octaves.</param>
public static float Sample2DTiledX (
Vector2 point, Vector2 offset, int frequency, int octaves, int lacunarity, float persistence
) {
int xOffset = NoiseMath.FloorToInt(offset.x);
point.x += offset.x - xOffset;
point.y += offset.y;
float amplitude = 1f, range = 1f, sum = Sample2DTiledX(point, xOffset, frequency);
while (--octaves > 0) {
frequency *= lacunarity;
amplitude *= persistence;
range += amplitude;
sum += Sample2DTiledX(point, xOffset, frequency) * amplitude;
}
return sum * (1f / range);
}
/// <summary>Sample 2D Value noise, tiled in both dimensions.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 2D.</param>
/// <param name="xOffset">X offset of the tiling domain.</param>
/// <param name="yOffset">Y offset of the tiling domain.</param>
/// <param name="frequency">Frequency of the noise.</param>
public static float Sample2DTiledXY (Vector2 point, int xOffset, int yOffset, int frequency) {
if (frequency == 0) {
return 0f;
}
point.x *= frequency;
point.y *= frequency;
int ix0 = NoiseMath.FloorToInt(point.x);
int iy0 = NoiseMath.FloorToInt(point.y);
float tx = point.x - ix0;
float ty = point.y - iy0;
ix0 %= frequency;
if (ix0 < 0) {
ix0 += frequency;
}
iy0 %= frequency;
if (iy0 < 0) {
iy0 += frequency;
}
int ix1 = ((ix0 + 1) % frequency + xOffset) & NoiseMath.hashMask;
int iy1 = ((iy0 + 1) % frequency + yOffset) & NoiseMath.hashMask;
ix0 = (ix0 + xOffset) & NoiseMath.hashMask;
iy0 = (iy0 + yOffset) & NoiseMath.hashMask;
int h0 = NoiseMath.hash[ix0];
int h1 = NoiseMath.hash[ix1];
int h00 = NoiseMath.hash[h0 + iy0];
int h10 = NoiseMath.hash[h1 + iy0];
int h01 = NoiseMath.hash[h0 + iy1];
int h11 = NoiseMath.hash[h1 + iy1];
float a = h00;
float b = h10 - h00;
float c = h01 - h00;
float d = h11 - h01 - h10 + h00;
tx = NoiseMath.Smooth(tx);
ty = NoiseMath.Smooth(ty);
return (a + b * tx + (c + d * tx) * ty) * (1f / NoiseMath.hashMask);
}
/// <summary>Sample multi-frequency 2D Value noise, tiled in both dimensions.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 2D.</param>
/// <param name="offset">Offset of the tiling domain.</param>
/// <param name="frequency">Base frequency.</param>
/// <param name="octaves">Amount of octaves.</param>
/// <param name="lacunarity">Frequency multiplier for successive octaves.</param>
/// <param name="persistence">Amplitude multiplier for succesive octaves.</param>
public static float Sample2DTiledXY (
Vector2 point, Vector2 offset, int frequency, int octaves, int lacunarity, float persistence
) {
int xOffset = NoiseMath.FloorToInt(offset.x), yOffset = NoiseMath.FloorToInt(offset.y);
point.x += offset.x - xOffset;
point.y += offset.y - yOffset;
float amplitude = 1f, range = 1f, sum = Sample2DTiledXY(point, xOffset, yOffset, frequency);
while (--octaves > 0) {
frequency *= lacunarity;
amplitude *= persistence;
range += amplitude;
sum += Sample2DTiledXY(point, xOffset, yOffset, frequency) * amplitude;
}
return sum * (1f / range);
}
/// <summary>Sample 3D Value noise.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 3D.</param>
/// <param name="frequency">Frequency of the noise.</param>
public static float Sample3D (Vector3 point, float frequency) {
point.x *= frequency;
point.y *= frequency;
point.z *= frequency;
int ix0 = NoiseMath.FloorToInt(point.x);
int iy0 = NoiseMath.FloorToInt(point.y);
int iz0 = NoiseMath.FloorToInt(point.z);
float tx = point.x - ix0;
float ty = point.y - iy0;
float tz = point.z - iz0;
ix0 &= NoiseMath.hashMask;
iy0 &= NoiseMath.hashMask;
iz0 &= NoiseMath.hashMask;
int ix1 = ix0 + 1;
int iy1 = iy0 + 1;
int iz1 = iz0 + 1;
int h0 = NoiseMath.hash[ix0];
int h1 = NoiseMath.hash[ix1];
int h00 = NoiseMath.hash[h0 + iy0];
int h10 = NoiseMath.hash[h1 + iy0];
int h01 = NoiseMath.hash[h0 + iy1];
int h11 = NoiseMath.hash[h1 + iy1];
int h000 = NoiseMath.hash[h00 + iz0];
int h100 = NoiseMath.hash[h10 + iz0];
int h010 = NoiseMath.hash[h01 + iz0];
int h110 = NoiseMath.hash[h11 + iz0];
int h001 = NoiseMath.hash[h00 + iz1];
int h101 = NoiseMath.hash[h10 + iz1];
int h011 = NoiseMath.hash[h01 + iz1];
int h111 = NoiseMath.hash[h11 + iz1];
float a = h000;
float b = h100 - h000;
float c = h010 - h000;
float d = h001 - h000;
float e = h110 - h010 - h100 + h000;
float f = h101 - h001 - h100 + h000;
float g = h011 - h001 - h010 + h000;
float h = h111 - h011 - h101 + h001 - h110 + h010 + h100 - h000;
tx = NoiseMath.Smooth(tx);
ty = NoiseMath.Smooth(ty);
tz = NoiseMath.Smooth(tz);
return
(a + b * tx + (c + e * tx) * ty + (d + f * tx + (g + h * tx) * ty) * tz) * (1f / NoiseMath.hashMask);
}
/// <summary>Sample multi-frequency 3D Value noise.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 3D.</param>
/// <param name="frequency">Base frequency.</param>
/// <param name="octaves">Amount of octaves.</param>
/// <param name="lacunarity">Frequency multiplier for successive octaves.</param>
/// <param name="persistence">Amplitude multiplier for succesive octaves.</param>
public static float Sample3D (
Vector3 point, float frequency, int octaves, float lacunarity, float persistence
) {
float amplitude = 1f, range = 1f, sum = Sample3D(point, frequency);
while (--octaves > 0) {
frequency *= lacunarity;
amplitude *= persistence;
range += amplitude;
sum += Sample3D(point, frequency) * amplitude;
}
return sum * (1f / range);
}
/// <summary>Sample 3D Value noise, tiled in the X dimension.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 3D.</param>
/// <param name="xOffset">X offset of the tiling domain.</param>
/// <param name="frequency">Frequency of the noise.</param>
public static float Sample3DTiledX (Vector3 point, int xOffset, int frequency) {
if (frequency == 0) {
return 0f;
}
point.x *= frequency;
point.y *= frequency;
point.z *= frequency;
int ix0 = NoiseMath.FloorToInt(point.x);
int iy0 = NoiseMath.FloorToInt(point.y);
int iz0 = NoiseMath.FloorToInt(point.z);
float tx = point.x - ix0;
float ty = point.y - iy0;
float tz = point.z - iz0;
ix0 %= frequency;
if (ix0 < 0) {
ix0 += frequency;
}
iy0 &= NoiseMath.hashMask;
iz0 &= NoiseMath.hashMask;
int ix1 = ((ix0 + 1) % frequency + xOffset) & NoiseMath.hashMask;
int iy1 = iy0 + 1;
int iz1 = iz0 + 1;
ix0 = (ix0 + xOffset) & NoiseMath.hashMask;
int h0 = NoiseMath.hash[ix0];
int h1 = NoiseMath.hash[ix1];
int h00 = NoiseMath.hash[h0 + iy0];
int h10 = NoiseMath.hash[h1 + iy0];
int h01 = NoiseMath.hash[h0 + iy1];
int h11 = NoiseMath.hash[h1 + iy1];
int h000 = NoiseMath.hash[h00 + iz0];
int h100 = NoiseMath.hash[h10 + iz0];
int h010 = NoiseMath.hash[h01 + iz0];
int h110 = NoiseMath.hash[h11 + iz0];
int h001 = NoiseMath.hash[h00 + iz1];
int h101 = NoiseMath.hash[h10 + iz1];
int h011 = NoiseMath.hash[h01 + iz1];
int h111 = NoiseMath.hash[h11 + iz1];
float a = h000;
float b = h100 - h000;
float c = h010 - h000;
float d = h001 - h000;
float e = h110 - h010 - h100 + h000;
float f = h101 - h001 - h100 + h000;
float g = h011 - h001 - h010 + h000;
float h = h111 - h011 - h101 + h001 - h110 + h010 + h100 - h000;
tx = NoiseMath.Smooth(tx);
ty = NoiseMath.Smooth(ty);
tz = NoiseMath.Smooth(tz);
return
(a + b * tx + (c + e * tx) * ty + (d + f * tx + (g + h * tx) * ty) * tz) * (1f / NoiseMath.hashMask);
}
/// <summary>Sample multi-frequency 3D Value noise, tiled in the X dimension.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 3D.</param>
/// <param name="offset">Offset of the tiling domain.</param>
/// <param name="frequency">Base frequency.</param>
/// <param name="octaves">Amount of octaves.</param>
/// <param name="lacunarity">Frequency multiplier for successive octaves.</param>
/// <param name="persistence">Amplitude multiplier for succesive octaves.</param>
public static float Sample3DTiledX (
Vector3 point, Vector3 offset, int frequency, int octaves, int lacunarity, float persistence
) {
int xOffset = NoiseMath.FloorToInt(offset.x);
point.x += offset.x - xOffset;
point.y += offset.y;
point.z += offset.z;
float amplitude = 1f, range = 1f, sum = Sample3DTiledX(point, xOffset, frequency);
while (--octaves > 0) {
frequency *= lacunarity;
amplitude *= persistence;
range += amplitude;
sum += Sample3DTiledX(point, xOffset, frequency) * amplitude;
}
return sum * (1f / range);
}
/// <summary>Sample 3D Value noise, tiled in the X and Y dimensions.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 3D.</param>
/// <param name="xOffset">X offset of the tiling domain.</param>
/// <param name="yOffset">Y offset of the tiling domain.</param>
/// <param name="frequency">Frequency of the noise.</param>
public static float Sample3DTiledXY (Vector3 point, int xOffset, int yOffset, int frequency) {
if (frequency == 0) {
return 0f;
}
point.x *= frequency;
point.y *= frequency;
point.z *= frequency;
int ix0 = NoiseMath.FloorToInt(point.x);
int iy0 = NoiseMath.FloorToInt(point.y);
int iz0 = NoiseMath.FloorToInt(point.z);
float tx = point.x - ix0;
float ty = point.y - iy0;
float tz = point.z - iz0;
ix0 %= frequency;
if (ix0 < 0) {
ix0 += frequency;
}
iy0 %= frequency;
if (iy0 < 0) {
iy0 += frequency;
}
iz0 &= NoiseMath.hashMask;
int ix1 = ((ix0 + 1) % frequency + xOffset) & NoiseMath.hashMask;
int iy1 = ((iy0 + 1) % frequency + yOffset) & NoiseMath.hashMask;
int iz1 = iz0 + 1;
ix0 = (ix0 + xOffset) & NoiseMath.hashMask;
iy0 = (iy0 + yOffset) & NoiseMath.hashMask;
int h0 = NoiseMath.hash[ix0];
int h1 = NoiseMath.hash[ix1];
int h00 = NoiseMath.hash[h0 + iy0];
int h10 = NoiseMath.hash[h1 + iy0];
int h01 = NoiseMath.hash[h0 + iy1];
int h11 = NoiseMath.hash[h1 + iy1];
int h000 = NoiseMath.hash[h00 + iz0];
int h100 = NoiseMath.hash[h10 + iz0];
int h010 = NoiseMath.hash[h01 + iz0];
int h110 = NoiseMath.hash[h11 + iz0];
int h001 = NoiseMath.hash[h00 + iz1];
int h101 = NoiseMath.hash[h10 + iz1];
int h011 = NoiseMath.hash[h01 + iz1];
int h111 = NoiseMath.hash[h11 + iz1];
float a = h000;
float b = h100 - h000;
float c = h010 - h000;
float d = h001 - h000;
float e = h110 - h010 - h100 + h000;
float f = h101 - h001 - h100 + h000;
float g = h011 - h001 - h010 + h000;
float h = h111 - h011 - h101 + h001 - h110 + h010 + h100 - h000;
tx = NoiseMath.Smooth(tx);
ty = NoiseMath.Smooth(ty);
tz = NoiseMath.Smooth(tz);
return
(a + b * tx + (c + e * tx) * ty + (d + f * tx + (g + h * tx) * ty) * tz) * (1f / NoiseMath.hashMask);
}
/// <summary>Sample multi-frequency 3D Value noise, tiled in the X and Y dimensions.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 3D.</param>
/// <param name="offset">Offset of the tiling domain.</param>
/// <param name="frequency">Base frequency.</param>
/// <param name="octaves">Amount of octaves.</param>
/// <param name="lacunarity">Frequency multiplier for successive octaves.</param>
/// <param name="persistence">Amplitude multiplier for succesive octaves.</param>
public static float Sample3DTiledXY (
Vector3 point, Vector3 offset, int frequency, int octaves, int lacunarity, float persistence
) {
int xOffset = NoiseMath.FloorToInt(offset.x), yOffset = NoiseMath.FloorToInt(offset.y);
point.x += offset.x - xOffset;
point.y += offset.y - yOffset;
point.z += offset.z;
float amplitude = 1f, range = 1f, sum = Sample3DTiledXY(point, xOffset, yOffset, frequency);
while (--octaves > 0) {
frequency *= lacunarity;
amplitude *= persistence;
range += amplitude;
sum += Sample3DTiledXY(point, xOffset, yOffset, frequency) * amplitude;
}
return sum * (1f / range);
}
/// <summary>Sample 3D Value noise, tiled in all three dimensions.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 3D.</param>
/// <param name="xOffset">X offset of the tiling domain.</param>
/// <param name="yOffset">Y offset of the tiling domain.</param>
/// <param name="zOffset">Z offset of the tiling domain.</param>
/// <param name="frequency">Frequency of the noise.</param>
public static float Sample3DTiledXYZ (Vector3 point, int xOffset, int zOffset, int yOffset, int frequency) {
if (frequency == 0) {
return 0f;
}
point.x *= frequency;
point.y *= frequency;
point.z *= frequency;
int ix0 = NoiseMath.FloorToInt(point.x);
int iy0 = NoiseMath.FloorToInt(point.y);
int iz0 = NoiseMath.FloorToInt(point.z);
float tx = point.x - ix0;
float ty = point.y - iy0;
float tz = point.z - iz0;
ix0 %= frequency;
if (ix0 < 0) {
ix0 += frequency;
}
iy0 %= frequency;
if (iy0 < 0) {
iy0 += frequency;
}
iz0 %= frequency;
if (iz0 < 0) {
iz0 += frequency;
}
int ix1 = ((ix0 + 1) % frequency + xOffset) & NoiseMath.hashMask;
int iy1 = ((iy0 + 1) % frequency + yOffset) & NoiseMath.hashMask;
int iz1 = ((iz0 + 1) % frequency + zOffset) & NoiseMath.hashMask;
ix0 = (ix0 + xOffset) & NoiseMath.hashMask;
iy0 = (iy0 + yOffset) & NoiseMath.hashMask;
iz0 = (iz0 + zOffset) & NoiseMath.hashMask;
int h0 = NoiseMath.hash[ix0];
int h1 = NoiseMath.hash[ix1];
int h00 = NoiseMath.hash[h0 + iy0];
int h10 = NoiseMath.hash[h1 + iy0];
int h01 = NoiseMath.hash[h0 + iy1];
int h11 = NoiseMath.hash[h1 + iy1];
int h000 = NoiseMath.hash[h00 + iz0];
int h100 = NoiseMath.hash[h10 + iz0];
int h010 = NoiseMath.hash[h01 + iz0];
int h110 = NoiseMath.hash[h11 + iz0];
int h001 = NoiseMath.hash[h00 + iz1];
int h101 = NoiseMath.hash[h10 + iz1];
int h011 = NoiseMath.hash[h01 + iz1];
int h111 = NoiseMath.hash[h11 + iz1];
float a = h000;
float b = h100 - h000;
float c = h010 - h000;
float d = h001 - h000;
float e = h110 - h010 - h100 + h000;
float f = h101 - h001 - h100 + h000;
float g = h011 - h001 - h010 + h000;
float h = h111 - h011 - h101 + h001 - h110 + h010 + h100 - h000;
tx = NoiseMath.Smooth(tx);
ty = NoiseMath.Smooth(ty);
tz = NoiseMath.Smooth(tz);
return
(a + b * tx + (c + e * tx) * ty + (d + f * tx + (g + h * tx) * ty) * tz) * (1f / NoiseMath.hashMask);
}
/// <summary>Sample multi-frequency 3D Value noise, tiled in all three dimensions.</summary>
/// <returns>The noise value.</returns>
/// <param name="point">Sample point in 3D.</param>
/// <param name="offset">Offset of the tiling domain.</param>
/// <param name="frequency">Base frequency.</param>
/// <param name="octaves">Amount of octaves.</param>
/// <param name="lacunarity">Frequency multiplier for successive octaves.</param>
/// <param name="persistence">Amplitude multiplier for succesive octaves.</param>
public static float Sample3DTiledXYZ (
Vector3 point, Vector3 offset, int frequency, int octaves, int lacunarity, float persistence
) {
int
xOffset = NoiseMath.FloorToInt(offset.x),
yOffset = NoiseMath.FloorToInt(offset.y),
zOffset = NoiseMath.FloorToInt(offset.z);
point.x += offset.x - xOffset;
point.y += offset.y - yOffset;
point.z += offset.z - zOffset;
float amplitude = 1f, range = 1f, sum = Sample3DTiledXYZ(point, xOffset, yOffset, zOffset, frequency);
while (--octaves > 0) {
frequency *= lacunarity;
amplitude *= persistence;
range += amplitude;
sum += Sample3DTiledXYZ(point, xOffset, yOffset, zOffset, frequency) * amplitude;
}
return sum * (1f / range);
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Description: FamilyCollection font cache element class is responsible for
// storing the mapping between a folder and font families in it.
//
// History:
// 07/23/2003 : mleonov - Big rewrite to change cache structure.
// 03/04/2004 : mleonov - Cache layout and interface changes for font enumeration.
// 11/04/2005 : mleonov - Refactoring to support font disambiguation.
// 08/08/2008 : [....] - Integrating with DWrite.
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows;
using System.Windows.Markup; // for XmlLanguage
using System.Windows.Media;
using MS.Win32;
using MS.Utility;
using MS.Internal;
using MS.Internal.FontFace;
using MS.Internal.PresentationCore;
using MS.Internal.Shaping;
// Since we disable PreSharp warnings in this file, we first need to disable warnings about unknown message numbers and unknown pragmas.
#pragma warning disable 1634, 1691
namespace MS.Internal.FontCache
{
/// <summary>
/// FamilyCollection font cache element class is responsible for
/// storing the mapping between a folder and font families in it
/// </summary>
[FriendAccessAllowed]
internal class FamilyCollection
{
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private Text.TextInterface.FontCollection _fontCollection;
private Uri _folderUri;
private List<CompositeFontFamily> _userCompositeFonts;
private const string _sxsFontsRelativeLocation = @"WPF\Fonts\";
private static object _staticLock = new object();
/// <SecurityNote>
/// Critical : contains the location of the .Net framework installation.
/// </SecurityNote>
[SecurityCritical]
private static string _sxsFontsLocation;
#endregion Private Fields
/// <SecurityNote>
/// Critical : exposes security critical _sxsFontsLocation and calls into
/// security critical method GetSystemSxSFontsLocation.
/// </SecurityNote>
internal static string SxSFontsLocation
{
[SecurityCritical]
get
{
if (_sxsFontsLocation == String.Empty)
{
lock (_staticLock)
{
if (_sxsFontsLocation == String.Empty)
{
_sxsFontsLocation = GetSystemSxSFontsLocation();
}
}
}
return _sxsFontsLocation;
}
}
/// <SecurityNote>
/// Critical : Reads the registry and asserts permissions.
/// </SecurityNote>
[SecurityCritical]
private static string GetSystemSxSFontsLocation()
{
RegistryPermission registryPermission = new RegistryPermission(
RegistryPermissionAccess.Read,
RegistryKeys.FRAMEWORK_RegKey_FullPath);
registryPermission.Assert(); // BlessedAssert
try
{
using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(MS.Internal.RegistryKeys.FRAMEWORK_RegKey))
{
// The registry key should be present on a valid WPF installation.
Invariant.Assert(key != null);
string frameworkInstallPath = key.GetValue(RegistryKeys.FRAMEWORK_InstallPath_RegValue) as string;
CheckFrameworkInstallPath(frameworkInstallPath);
return System.IO.Path.Combine(frameworkInstallPath, _sxsFontsRelativeLocation);
}
}
finally
{
CodeAccessPermission.RevertAssert();
}
}
private static void CheckFrameworkInstallPath(string frameworkInstallPath)
{
if (frameworkInstallPath == null)
{
throw new ArgumentNullException("frameworkInstallPath", SR.Get(SRID.FamilyCollection_CannotFindCompositeFontsLocation));
}
}
/// <SecurityNote>
/// Critical : Accesses the Security Critical FontSource.GetStream().
/// TreatAsSafe : Does not expose this stream publicly.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private static List<CompositeFontFamily> GetCompositeFontList(FontSourceCollection fontSourceCollection)
{
List<CompositeFontFamily> compositeFonts = new List<CompositeFontFamily>();
foreach (FontSource fontSource in fontSourceCollection)
{
if (fontSource.IsComposite)
{
CompositeFontInfo fontInfo = CompositeFontParser.LoadXml(fontSource.GetStream());
CompositeFontFamily compositeFamily = new CompositeFontFamily(fontInfo);
compositeFonts.Add(compositeFamily);
}
}
return compositeFonts;
}
/// <SecurityNote>
/// Critical : Access the security critical DWriteFactory.SystemFontCollection.
/// TreatAsSafe : Does not modify it.
/// </SecurityNote>
private bool UseSystemFonts
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
return (_fontCollection == DWriteFactory.SystemFontCollection);
}
}
/// <SecurityNote>
/// Critical : Contructs security critical FontSourceCollection.
/// TreatAsSafe : Does not expose critical info from this object publicly.
/// </SecurityNote>
private IList<CompositeFontFamily> UserCompositeFonts
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
if (_userCompositeFonts == null)
{
_userCompositeFonts = GetCompositeFontList(new FontSourceCollection(_folderUri, false, true));
}
return _userCompositeFonts;
}
}
private static class LegacyArabicFonts
{
private static bool _usePrivateFontCollectionIsInitialized = false;
private static object _staticLock = new object();
private static bool _usePrivateFontCollectionForLegacyArabicFonts;
private static readonly string[] _legacyArabicFonts;
private static Text.TextInterface.FontCollection _legacyArabicFontCollection;
static LegacyArabicFonts()
{
_legacyArabicFonts = new string[] { "Traditional Arabic",
"Andalus",
"Simplified Arabic",
"Simplified Arabic Fixed" };
}
/// <SecurityNote>
/// Critical : Accesses FamilyCollection.SxSFontsLocation security critical.
/// : Asserts to get a FontCollection by full path
/// TreatAsSafe : Does not expose security critical data.
/// </SecurityNote>
internal static Text.TextInterface.FontCollection LegacyArabicFontCollection
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
if (_legacyArabicFontCollection == null)
{
lock (_staticLock)
{
if (_legacyArabicFontCollection == null)
{
Uri criticalSxSFontsLocation = new Uri(FamilyCollection.SxSFontsLocation);
SecurityHelper.CreateUriDiscoveryPermission(criticalSxSFontsLocation).Assert();
try
{
_legacyArabicFontCollection = DWriteFactory.GetFontCollectionFromFolder(criticalSxSFontsLocation);
}
finally
{
CodeAccessPermission.RevertAssert();
}
}
}
}
return _legacyArabicFontCollection;
}
}
/// <summary>
/// Checks if a given family name is one of the legacy Arabic fonts.
/// </summary>
/// <param name="familyName">The family name without any face info.</param>
internal static bool IsLegacyArabicFont(string familyName)
{
for (int i = 0; i < _legacyArabicFonts.Length; ++i)
{
if (String.Compare(familyName, _legacyArabicFonts[i], StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
}
return false;
}
/// <summary>
/// We will use the private font collection to load some Arabic fonts
/// only on OSes lower than Win7, since the fonts on these OSes are legacy fonts
/// and the shaping engines that DWrite uses does not handle them properly.
/// </summary>
internal static bool UsePrivateFontCollectionForLegacyArabicFonts
{
get
{
if (!_usePrivateFontCollectionIsInitialized)
{
lock (_staticLock)
{
if (!_usePrivateFontCollectionIsInitialized)
{
try
{
OperatingSystem osInfo = Environment.OSVersion;
// The version of Win7 is 6.1
_usePrivateFontCollectionForLegacyArabicFonts = (osInfo.Version.Major < 6)
|| (osInfo.Version.Major == 6
&&
osInfo.Version.Minor == 0);
}
//Environment.OSVersion was unable to obtain the system version.
//-or-
//The obtained platform identifier is not a member of PlatformID.
catch (InvalidOperationException)
{
// We do not want to bubble this exception up to the user since the user
// has nothing to do about it.
// Instead we will silently fallback to using the private fonts collection
// so that we guarantee that the text shows properly.
_usePrivateFontCollectionForLegacyArabicFonts = true;
}
_usePrivateFontCollectionIsInitialized = true;
}
}
}
return _usePrivateFontCollectionForLegacyArabicFonts;
}
}
}
/// <summary>
/// This class encapsulates the 4 system composite fonts.
/// </summary>
/// <remarks>
/// This class has direct knowledge about the 4 composite fonts that ship with WPF.
/// </remarks>
private static class SystemCompositeFonts
{
/// The number of the system composite fonts that ship with WPF is 4.
internal const int NumOfSystemCompositeFonts = 4;
private static object _systemCompositeFontsLock = new object();
private static readonly string[] _systemCompositeFontsNames;
private static readonly string[] _systemCompositeFontsFileNames;
private static CompositeFontFamily[] _systemCompositeFonts;
static SystemCompositeFonts()
{
_systemCompositeFontsNames = new string[] { "Global User Interface", "Global Monospace", "Global Sans Serif", "Global Serif" };
_systemCompositeFontsFileNames = new string[] { "GlobalUserInterface", "GlobalMonospace", "GlobalSansSerif", "GlobalSerif" };
_systemCompositeFonts = new CompositeFontFamily[NumOfSystemCompositeFonts];
}
/// <summary>
/// Returns the composite font to be used to fallback to a different font
/// if one of the legacy Arabic fonts is specifed.
/// </summary>
internal static CompositeFontFamily GetFallbackFontForArabicLegacyFonts()
{
return GetCompositeFontFamilyAtIndex(1);
}
/// <summary>
/// This method returns the composite font family (or null if not found) given its name
/// </summary>
internal static CompositeFontFamily FindFamily(string familyName)
{
int index = GetIndexOfFamily(familyName);
if (index >= 0)
{
return GetCompositeFontFamilyAtIndex(index);
}
return null;
}
/// <summary>
/// This method returns the composite font with the given index after
/// lazily allocating it if it has not been already allocated.
/// </summary>
/// <SecurityNote>
/// Critical : Creates a Security Critical FontSource object while skipping
/// the demand for read permission and accesses
/// FamilyCollection.SxSFontsLocation security critical.
/// TreatAsSafe : Does not expose security critical data.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal static CompositeFontFamily GetCompositeFontFamilyAtIndex(int index)
{
if (_systemCompositeFonts[index] == null)
{
lock (_systemCompositeFontsLock)
{
if (_systemCompositeFonts[index] == null)
{
FontSource fontSource = new FontSource(new Uri(FamilyCollection.SxSFontsLocation + _systemCompositeFontsFileNames[index] + Util.CompositeFontExtension, UriKind.Absolute),
true, //skipDemand.
//We skip demand here since this class should cache
//all system composite fonts for the current process
//Demanding read permissions should be done by FamilyCollection.cs
true //isComposite
);
CompositeFontInfo fontInfo = CompositeFontParser.LoadXml(fontSource.GetStream());
_systemCompositeFonts[index] = new CompositeFontFamily(fontInfo);
}
}
}
return _systemCompositeFonts[index];
}
/// <summary>
/// This method returns the index of the system composite font in _systemCompositeFontsNames.
/// </summary>
private static int GetIndexOfFamily(string familyName)
{
for (int i = 0; i < _systemCompositeFontsNames.Length; ++i)
{
if (String.Compare(_systemCompositeFontsNames[i], familyName, StringComparison.OrdinalIgnoreCase) == 0)
{
return i;
}
}
return -1;
}
}
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Creates a font family collection cache element from a canonical font family reference.
/// </summary>
/// <param name="folderUri">Absolute Uri of a folder</param>
/// <param name="fontCollection">Collection of fonts loaded from the folderUri location</param>
/// <SecurityNote>
/// Critical - The ability to control the place fonts are loaded from is critical.
///
/// The folderUri parameter is critical as it may contain privileged information
/// (i.e., the location of Windows Fonts);
/// </SecurityNote>
[SecurityCritical]
private FamilyCollection(Uri folderUri, MS.Internal.Text.TextInterface.FontCollection fontCollection)
{
_folderUri = folderUri;
_fontCollection = fontCollection;
}
/// <summary>
/// Creates a font family collection cache element from a canonical font family reference.
/// </summary>
/// <param name="folderUri">Absolute Uri of a folder</param>
/// <SecurityNote>
/// Critical - Calls critical constructors to initialize the returned FamilyCollection
/// The folderUri parameter is critical as it may contain privileged information
/// (i.e., the location of Windows Fonts); it is passed to the FontSourceCollection
/// constructor which is declared critical and guarantees not to disclose the URI.
/// TreatAsSafe - Demands Uri Read permissions for the uri passed to constructors
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal static FamilyCollection FromUri(Uri folderUri)
{
SecurityHelper.DemandUriReadPermission(folderUri);
return new FamilyCollection(folderUri, DWriteFactory.GetFontCollectionFromFolder(folderUri));
}
/// <summary>
/// Creates a font family collection cache element from a canonical font family reference.
/// </summary>
/// <param name="folderUri">Absolute Uri to the Windows Fonts folder or a file in the Windows Fonts folder.</param>
/// <SecurityNote>
/// Critical - calls critical constructors to initialize the returned FamilyCollection
///
/// Callers should only call this method if the URI comes from internal
/// WPF code, NOT if it comes from the client. E.g., we want FontFamily="Arial" and
/// FontFamily="arial.ttf#Arial" to work in partial trust.
/// But FontFamily="file:///c:/windows/fonts/#Arial" should NOT work in partial trust
/// (even -- or especially -- if the URI is right), as this would enable partial trust
/// clients to guess the location of Windows Fonts through trial and error.
/// </SecurityNote>
[SecurityCritical]
internal static FamilyCollection FromWindowsFonts(Uri folderUri)
{
return new FamilyCollection(folderUri, DWriteFactory.SystemFontCollection);
}
/// <SecurityNote>
/// Critical - Initializes security critical _sxsFontsLocation.
/// TreatAsSafe - Always initialzes _sxsFontsLocation to String.Empty.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
static FamilyCollection()
{
_sxsFontsLocation = String.Empty;
}
#endregion Constructors
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal methods
/// <summary>
/// This method looks up a certain family in this collection given its name.
/// If the name was for a specific font face then this method will return its
/// style, weight and stretch information.
/// </summary>
/// <param name="familyName">The name of the family to look for.</param>
/// <param name="fontStyle">The style if the font face in case family name contained style info.</param>
/// <param name="fontWeight">The weight if the font face in case family name contained style info.</param>
/// <param name="fontStretch">The stretch if the font face in case family name contained style info.</param>
/// <returns>The font family if found.</returns>
/// <SecurityNote>
/// Critical - calls into critical GetFontFromFamily
/// </SecurityNote>
[SecurityCritical]
internal IFontFamily LookupFamily(
string familyName,
ref FontStyle fontStyle,
ref FontWeight fontWeight,
ref FontStretch fontStretch
)
{
if (familyName == null || familyName.Length == 0)
return null;
familyName = familyName.Trim();
// If we are referencing fonts from the system fonts, then it is cheap to lookup the 4 composite fonts
// that ship with WPF. Also, it happens often that familyName is "Global User Interface".
// So in this case we preceed looking into SystemComposite Fonts.
if (UseSystemFonts)
{
CompositeFontFamily compositeFamily = SystemCompositeFonts.FindFamily(familyName);
if (compositeFamily != null)
{
return compositeFamily;
}
}
Text.TextInterface.FontFamily fontFamilyDWrite = _fontCollection[familyName];
// A font family was not found in DWrite's font collection.
if (fontFamilyDWrite == null)
{
// Having user defined composite fonts is not very common. So we defer looking into them to looking DWrite
// (which is opposite to what we do for system fonts).
if (!UseSystemFonts)
{
// The family name was not found in DWrite's font collection. It may possibly be the name of a composite font
// since DWrite does not recognize composite fonts.
CompositeFontFamily compositeFamily = LookUpUserCompositeFamily(familyName);
if (compositeFamily != null)
{
return compositeFamily;
}
}
// The family name cannot be found. This may possibly be because the family name contains styling info.
// For example, "Arial Bold"
// We will strip off the styling info (one word at a time from the end) and try to find the family name.
int indexOfSpace = -1;
System.Text.StringBuilder potentialFaceName = new System.Text.StringBuilder();
// Start removing off strings from the end hoping they are
// style info so as to get down to the family name.
do
{
indexOfSpace = familyName.LastIndexOf(' ');
if (indexOfSpace < 0)
{
break;
}
else
{
// store the stripped off style names to look for the specific face later.
potentialFaceName.Insert(0, familyName.Substring(indexOfSpace));
familyName = familyName.Substring(0, indexOfSpace);
}
fontFamilyDWrite = _fontCollection[familyName];
} while (fontFamilyDWrite == null);
if (fontFamilyDWrite == null)
{
return null;
}
// If there was styling information.
if (potentialFaceName.Length > 0)
{
// The first character in the potentialFaceName will be a space so we need to strip it off.
Text.TextInterface.Font font = GetFontFromFamily(fontFamilyDWrite, potentialFaceName.ToString(1, potentialFaceName.Length - 1));
if (font != null)
{
fontStyle = new FontStyle((int)font.Style);
fontWeight = new FontWeight((int)font.Weight);
fontStretch = new FontStretch((int)font.Stretch);
}
}
}
if (UseSystemFonts
&& LegacyArabicFonts.UsePrivateFontCollectionForLegacyArabicFonts
// familyName will hold the family name without any face info.
&& LegacyArabicFonts.IsLegacyArabicFont(familyName))
{
fontFamilyDWrite = LegacyArabicFonts.LegacyArabicFontCollection[familyName];
if (fontFamilyDWrite == null)
{
return SystemCompositeFonts.GetFallbackFontForArabicLegacyFonts();
}
}
return new PhysicalFontFamily(fontFamilyDWrite);
}
private CompositeFontFamily LookUpUserCompositeFamily(string familyName)
{
if (UserCompositeFonts != null)
{
foreach (CompositeFontFamily compositeFamily in UserCompositeFonts)
{
foreach (KeyValuePair<XmlLanguage, string> localizedFamilyName in compositeFamily.FamilyNames)
{
if (String.Compare(localizedFamilyName.Value, familyName, StringComparison.OrdinalIgnoreCase) == 0)
{
return compositeFamily;
}
}
}
}
return null;
}
/// <summary>
/// Given a DWrite font family, look into it for the given face.
/// </summary>
/// <param name="fontFamily">The font family to look in.</param>
/// <param name="faceName">The face to look for.</param>
/// <returns>The font face if found and null if nothing was found.</returns>
/// <SecurityNote>
/// Critical - calls into critical Text.TextInterface.Font.FaceNames
/// </SecurityNote>
[SecurityCritical]
private static Text.TextInterface.Font GetFontFromFamily(Text.TextInterface.FontFamily fontFamily, string faceName)
{
faceName = faceName.ToUpper(CultureInfo.InvariantCulture);
// The search that DWrite supports is a linear search.
// Look at every font face.
foreach (Text.TextInterface.Font font in fontFamily)
{
// and at every locale name this font face has.
foreach (KeyValuePair<CultureInfo, string> name in font.FaceNames)
{
string currentFontName = name.Value.ToUpper(CultureInfo.InvariantCulture);
if (currentFontName == faceName)
{
return font;
}
}
}
// This dictionary is used to store the faces (indexed by their names).
// This dictionary will be used in case the exact string "faceName" was not found,
// thus we will start again removing words (separated by ' ') from its end and looking
// for the resulting faceName in that dictionary. So this dictionary is
// used to speed the search.
Dictionary<string, Text.TextInterface.Font> faces = new Dictionary<string, Text.TextInterface.Font>();
//We could have merged this loop with the one above. However this will degrade the performance
//of the scenario where the user entered a correct face name (which is the common scenario).
//Thus we adopt a pay for play approach, meaning that only whenever the face name does not
//exactly correspond to an actual face name we will incure this overhead.
foreach (Text.TextInterface.Font font in fontFamily)
{
foreach (KeyValuePair<CultureInfo, string> name in font.FaceNames)
{
string currentFontName = name.Value.ToUpper(CultureInfo.InvariantCulture);
if (!faces.ContainsKey(currentFontName))
{
faces.Add(currentFontName, font);
}
}
}
// An exact match was not found and so we will start looking for the best match.
Text.TextInterface.Font matchingFont = null;
int indexOfSpace = faceName.LastIndexOf(' ');
while (indexOfSpace > 0)
{
faceName = faceName.Substring(0, indexOfSpace);
if (faces.TryGetValue(faceName, out matchingFont))
{
return matchingFont;
}
indexOfSpace = faceName.LastIndexOf(' ');
}
// No match was found.
return null;
}
private struct FamilyEnumerator : IEnumerator<Text.TextInterface.FontFamily>, IEnumerable<Text.TextInterface.FontFamily>
{
private uint _familyCount;
private Text.TextInterface.FontCollection _fontCollection;
private bool _firstEnumeration;
private uint _currentFamily;
internal FamilyEnumerator(Text.TextInterface.FontCollection fontCollection)
{
_fontCollection = fontCollection;
_currentFamily = 0;
_firstEnumeration = true;
_familyCount = fontCollection.FamilyCount;
}
#region IEnumerator<Text.TextInterface.FontFamily> Members
public bool MoveNext()
{
if (_firstEnumeration)
{
_firstEnumeration = false;
}
else
{
++_currentFamily;
}
if (_currentFamily >= _familyCount)
{
// prevent cycling
_currentFamily = _familyCount;
return false;
}
return true;
}
/// <SecurityNote>
/// Critical - calls into critical Text.TextInterface.FontCollection
/// TreatAsSafe - safe to return a Text.TextInterface.FontFamily object, all access to it is critical
/// </SecurityNote>
Text.TextInterface.FontFamily IEnumerator<Text.TextInterface.FontFamily>.Current
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
if (_currentFamily < 0 || _currentFamily >= _familyCount)
{
throw new InvalidOperationException();
}
return _fontCollection[_currentFamily];
}
}
#endregion
#region IEnumerator Members
object IEnumerator.Current
{
get
{
return ((IEnumerator<Text.TextInterface.FontFamily>)this).Current;
}
}
public void Reset()
{
_currentFamily = 0;
_firstEnumeration = true;
}
#endregion
#region IDisposable Members
public void Dispose() { }
#endregion
#region IEnumerable<Text.TextInterface.FontFamily> Members
IEnumerator<Text.TextInterface.FontFamily> IEnumerable<Text.TextInterface.FontFamily>.GetEnumerator()
{
return this as IEnumerator<Text.TextInterface.FontFamily>;
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<Text.TextInterface.FontFamily>)this).GetEnumerator();
}
#endregion
}
private IEnumerable<Text.TextInterface.FontFamily> GetPhysicalFontFamilies()
{
return new FamilyEnumerator(this._fontCollection);
}
internal FontFamily[] GetFontFamilies(Uri fontFamilyBaseUri, string fontFamilyLocationReference)
{
FontFamily[] fontFamilyList = new FontFamily[FamilyCount];
int i = 0;
foreach (MS.Internal.Text.TextInterface.FontFamily family in GetPhysicalFontFamilies())
{
string fontFamilyReference = Util.ConvertFamilyNameAndLocationToFontFamilyReference(
family.OrdinalName,
fontFamilyLocationReference
);
string friendlyName = Util.ConvertFontFamilyReferenceToFriendlyName(fontFamilyReference);
fontFamilyList[i++] = new FontFamily(fontFamilyBaseUri, friendlyName);
}
FontFamily fontFamily;
if (UseSystemFonts)
{
for (int j = 0; j < SystemCompositeFonts.NumOfSystemCompositeFonts; ++j)
{
fontFamily = CreateFontFamily(SystemCompositeFonts.GetCompositeFontFamilyAtIndex(j), fontFamilyBaseUri, fontFamilyLocationReference);
if (fontFamily != null)
{
fontFamilyList[i++] = fontFamily;
}
}
}
else
{
foreach (CompositeFontFamily compositeFontFamily in UserCompositeFonts)
{
fontFamily = CreateFontFamily(compositeFontFamily, fontFamilyBaseUri, fontFamilyLocationReference);
if (fontFamily != null)
{
fontFamilyList[i++] = fontFamily;
}
}
}
Debug.Assert(i == FamilyCount);
return fontFamilyList;
}
private FontFamily CreateFontFamily(CompositeFontFamily compositeFontFamily, Uri fontFamilyBaseUri, string fontFamilyLocationReference)
{
IFontFamily fontFamily = (IFontFamily)compositeFontFamily;
IEnumerator<string> familyNames = fontFamily.Names.Values.GetEnumerator();
if (familyNames.MoveNext())
{
string ordinalName = familyNames.Current;
string fontFamilyReference = Util.ConvertFamilyNameAndLocationToFontFamilyReference(
ordinalName,
fontFamilyLocationReference
);
string friendlyName = Util.ConvertFontFamilyReferenceToFriendlyName(fontFamilyReference);
return new FontFamily(fontFamilyBaseUri, friendlyName);
}
return null;
}
/// <SecurityNote>
/// Critical: Calls critical Text.TextInterface.FontCollection FamilyCount
/// SecurityTreatAsSafe: Safe to expose the number of font families in a folder.
/// </SecurityNote>
internal uint FamilyCount
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
return _fontCollection.FamilyCount + (UseSystemFonts ? SystemCompositeFonts.NumOfSystemCompositeFonts : checked((uint)UserCompositeFonts.Count));
}
}
#endregion Internal methods
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ElementProxy.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: UIAutomation/Visual bridge
//
// History:
// 07/15/2003 : BrendanM Ported to WCP
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using System.Windows.Automation.Peers;
using System.Diagnostics;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using System.Security;
using System.Security.Permissions;
using MS.Internal.PresentationCore;
using MS.Win32;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace MS.Internal.Automation
{
// Automation Proxy for WCP elements - exposes WCP tree
// and properties to Automation.
//
// Currently builds tree based on Visual tree; many later incorporate
// parts of logical tree.
//
// Currently exposes just BoundingRectangle, ClassName, IsEnabled
// and IsKeyboardFocused properties.
internal class ElementProxy: IRawElementProviderFragmentRoot, IRawElementProviderAdviseEvents
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// private ctor - the Wrap() pseudo-ctor is used instead.
private ElementProxy(AutomationPeer peer)
{
if ((AutomationInteropReferenceType == ReferenceType.Weak) &&
(peer is UIElementAutomationPeer || peer is ContentElementAutomationPeer || peer is UIElement3DAutomationPeer))
{
_peer = new WeakReference(peer);
}
else
{
_peer = peer;
}
}
#endregion Constructors
//------------------------------------------------------
//
// Interface IRawElementProviderFragmentRoot
//
//------------ ------------------------------------------
#region Interface IRawElementProviderFragmentRoot
// Implementation of the interface that exposes this
// to UIAutomation.
//
// Interface IRawElementProviderFragmentRoot 'derives' from
// IRawElementProviderSimple and IRawElementProviderFragment,
// methods from those appear first below.
//
// Most of the interface methods on this interface need
// to get onto the Visual's context before they can access it,
// so use Dispatcher.Invoke to call a private method (in the
// private methods section of this class) that does the real work.
// IRawElementProviderSimple methods...
public object GetPatternProvider ( int pattern )
{
AutomationPeer peer = Peer;
if (peer == null)
{
throw new ElementNotAvailableException();
}
return ElementUtil.Invoke(peer, new DispatcherOperationCallback( InContextGetPatternProvider ), pattern);
}
public object GetPropertyValue(int property)
{
AutomationPeer peer = Peer;
if (peer == null)
{
throw new ElementNotAvailableException();
}
return ElementUtil.Invoke(peer, new DispatcherOperationCallback(InContextGetPropertyValue), property);
}
public ProviderOptions ProviderOptions
{
get
{
AutomationPeer peer = Peer;
if (peer == null)
{
return ProviderOptions.ServerSideProvider;
}
return (ProviderOptions)ElementUtil.Invoke(peer, new DispatcherOperationCallback( InContextGetProviderOptions ), null);
}
}
public IRawElementProviderSimple HostRawElementProvider
{
get
{
IRawElementProviderSimple host = null;
HostedWindowWrapper hwndWrapper = null;
AutomationPeer peer = Peer;
if (peer == null)
{
return null;
}
hwndWrapper = (HostedWindowWrapper)ElementUtil.Invoke(
peer,
new DispatcherOperationCallback(InContextGetHostRawElementProvider),
null);
if(hwndWrapper != null)
host = GetHostHelper(hwndWrapper);
return host;
}
}
/// <SecurityNote>
/// Critical - Calls critical HostedWindowWrapper.Handle.
/// TreatAsSafe - Critical data is used internally and not explosed
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private IRawElementProviderSimple GetHostHelper(HostedWindowWrapper hwndWrapper)
{
return AutomationInteropProvider.HostProviderFromHandle(hwndWrapper.Handle);
}
// IRawElementProviderFragment methods...
public IRawElementProviderFragment Navigate( NavigateDirection direction )
{
AutomationPeer peer = Peer;
if (peer == null)
{
return null;
}
return (IRawElementProviderFragment)ElementUtil.Invoke(peer, new DispatcherOperationCallback(InContextNavigate), direction);
}
public int [ ] GetRuntimeId()
{
AutomationPeer peer = Peer;
if (peer == null)
{
throw new ElementNotAvailableException();
}
return (int []) ElementUtil.Invoke( peer, new DispatcherOperationCallback( InContextGetRuntimeId ), null );
}
public Rect BoundingRectangle
{
get
{
AutomationPeer peer = Peer;
if (peer == null)
{
throw new ElementNotAvailableException();
}
return (Rect)ElementUtil.Invoke(peer, new DispatcherOperationCallback(InContextBoundingRectangle), null);
}
}
public IRawElementProviderSimple [] GetEmbeddedFragmentRoots()
{
return null;
}
public void SetFocus()
{
AutomationPeer peer = Peer;
if (peer == null)
{
throw new ElementNotAvailableException();
}
ElementUtil.Invoke(peer, new DispatcherOperationCallback( InContextSetFocus ), null);
}
public IRawElementProviderFragmentRoot FragmentRoot
{
get
{
AutomationPeer peer = Peer;
if (peer == null)
{
return null;
}
return (IRawElementProviderFragmentRoot) ElementUtil.Invoke( peer, new DispatcherOperationCallback( InContextFragmentRoot ), null );
}
}
// IRawElementProviderFragmentRoot methods..
public IRawElementProviderFragment ElementProviderFromPoint( double x, double y )
{
AutomationPeer peer = Peer;
if (peer == null)
{
return null;
}
return (IRawElementProviderFragment) ElementUtil.Invoke( peer, new DispatcherOperationCallback( InContextElementProviderFromPoint ), new Point( x, y ) );
}
public IRawElementProviderFragment GetFocus()
{
AutomationPeer peer = Peer;
if (peer == null)
{
return null;
}
return (IRawElementProviderFragment) ElementUtil.Invoke( peer, new DispatcherOperationCallback( InContextGetFocus ), null );
}
// Event support: EventMap is a static class and access is synchronized, so no need to access it in UI thread context.
// Directly add or remove the requested EventId from the EventMap from here.
// Note: We update the EventMap even if peer is not available that's because we still have to keep track of number of
// subscribers for the given event.
public void AdviseEventAdded(int eventID, int[] properties)
{
EventMap.AddEvent(eventID);
}
public void AdviseEventRemoved(int eventID, int[] properties)
{
EventMap.RemoveEvent(eventID);
}
#endregion Interface IRawElementProviderFragmentRoot
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
// Wrap the found peer before shipping it over process boundary - static version for use outside ElementProxy.
internal static ElementProxy StaticWrap(AutomationPeer peer, AutomationPeer referencePeer)
{
ElementProxy result = null;
if (peer != null)
{
//referencePeer is well-connected, since UIA is asking us using it.
//However we are trying to return the peer that is possibly just created on some
//element in the middle of un-walked tree and we need to make sure it is fully
//"connected" or initialized before we return it to UIA.
//This method ensures it has the right _parent and other hookup.
peer = peer.ValidateConnected(referencePeer);
if (peer != null)
{
// Use the already created Wrapper proxy for peer if it is still alive
if(peer.ElementProxyWeakReference != null)
{
result = peer.ElementProxyWeakReference.Target as ElementProxy;
}
if(result == null)
{
result = new ElementProxy(peer);
peer.ElementProxyWeakReference = new WeakReference(result);
}
// If the peer corresponds to DataItem notify peer to add to storage to
// keep reference of peers going to the UIA Client
if(result != null)
{
if(peer.IsDataItemAutomationPeer())
{
peer.AddToParentProxyWeakRefCache();
}
}
}
}
return result;
}
// Needed to enable access from AutomationPeer.PeerFromProvider
internal AutomationPeer Peer
{
get
{
if (_peer is WeakReference)
{
AutomationPeer peer = (AutomationPeer)((WeakReference)_peer).Target;
return peer;
}
else
{
return (AutomationPeer)_peer;
}
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
// The signature of most of the folling methods is "object func( object arg )",
// since that's what the Conmtext.Invoke delegate requires.
// Return the element at specified coords.
private object InContextElementProviderFromPoint( object arg )
{
Point point = (Point)arg;
AutomationPeer peer = Peer;
if (peer == null)
{
return null;
}
AutomationPeer peerFromPoint = peer.GetPeerFromPoint(point);
return StaticWrap(peerFromPoint, peer);
}
// Return proxy representing currently focused element (if any)
private object InContextGetFocus( object unused )
{
//
AutomationPeer peer = Peer;
if (peer == null)
{
return null;
}
AutomationPeer focusedPeer = AutomationPeer.AutomationPeerFromInputElement(Keyboard.FocusedElement);
return StaticWrap(focusedPeer, peer);
}
// redirect to AutomationPeer
private object InContextGetPatternProvider(object arg)
{
AutomationPeer peer = Peer;
if (peer == null)
{
throw new ElementNotAvailableException();
}
return peer.GetWrappedPattern((int)arg);
}
// Return proxy representing element in specified direction (parent/next/firstchild/etc.)
private object InContextNavigate( object arg )
{
NavigateDirection direction = (NavigateDirection) arg;
AutomationPeer dest;
AutomationPeer peer = Peer;
if (peer == null)
{
return null;
}
switch( direction )
{
case NavigateDirection.Parent:
dest = peer.GetParent();
break;
case NavigateDirection.FirstChild:
if (!peer.IsInteropPeer)
{
dest = peer.GetFirstChild();
}
else
{
return peer.GetInteropChild();
}
break;
case NavigateDirection.LastChild:
if (!peer.IsInteropPeer)
{
dest = peer.GetLastChild();
}
else
{
return peer.GetInteropChild();
}
break;
case NavigateDirection.NextSibling:
dest = peer.GetNextSibling();
break;
case NavigateDirection.PreviousSibling:
dest = peer.GetPreviousSibling();
break;
default:
dest = null;
break;
}
return StaticWrap(dest, peer);
}
// Return value for specified property; or null if not supported
private object InContextGetProviderOptions( object arg )
{
ProviderOptions options = ProviderOptions.ServerSideProvider;
AutomationPeer peer = Peer;
if (peer == null)
{
return options;
}
if (peer.IsHwndHost)
options |= ProviderOptions.OverrideProvider;
return options;
}
// Return value for specified property; or null if not supported
private object InContextGetPropertyValue ( object arg )
{
AutomationPeer peer = Peer;
if (peer == null)
{
throw new ElementNotAvailableException();
}
return peer.GetPropertyValue((int)arg);
}
/// Returns whether this is the Root of the WCP tree or not
private object InContextGetHostRawElementProvider( object unused )
{
AutomationPeer peer = Peer;
if (peer == null)
{
return null;
}
return peer.GetHostRawElementProvider();
}
// Return unique ID for this element...
private object InContextGetRuntimeId( object unused )
{
AutomationPeer peer = Peer;
if (peer == null)
{
throw new ElementNotAvailableException();
}
return peer.GetRuntimeId();
}
// Return bounding rectangle (screen coords) for this element...
private object InContextBoundingRectangle(object unused)
{
AutomationPeer peer = Peer;
if (peer == null)
{
throw new ElementNotAvailableException();
}
return peer.GetBoundingRectangle();
}
// Set focus to this element...
private object InContextSetFocus( object unused )
{
AutomationPeer peer = Peer;
if (peer == null)
{
throw new ElementNotAvailableException();
}
peer.SetFocus();
return null;
}
// Return proxy representing the root of this WCP tree...
private object InContextFragmentRoot( object unused )
{
AutomationPeer peer = Peer;
AutomationPeer root = peer;
if (root == null)
{
return null;
}
while(true)
{
AutomationPeer parent = root.GetParent();
if(parent == null) break;
root = parent;
}
return StaticWrap(root, peer);
}
#region disable switch for ElementProxy weak reference fix
internal enum ReferenceType
{
Strong,
Weak
}
// Returns RefrenceType.Strong if key AutomationWeakReferenceDisallow under
// "HKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramework\Windows Presentation Foundation\Features"
// is set to 1 else returns ReferenceType.Weak. The registry key will be read only once.
///<SecurityNote>
/// Critical: Uses the critical RegistryKeys.ReadLocalMachineBool() to access the registry.
/// Safe: This flag is not a secret and used internally
///</SecurityNote>
internal static ReferenceType AutomationInteropReferenceType
{
[SecurityCritical, SecurityTreatAsSafe]
get
{
if (_shouldCheckInTheRegistry)
{
if (RegistryKeys.ReadLocalMachineBool(RegistryKeys.WPF_Features, RegistryKeys.value_AutomationWeakReferenceDisallow))
{
_automationInteropReferenceType = ReferenceType.Strong;
}
_shouldCheckInTheRegistry = false;
}
return _automationInteropReferenceType;
}
}
private static ReferenceType _automationInteropReferenceType = ReferenceType.Weak;
private static bool _shouldCheckInTheRegistry = true;
#endregion
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private readonly object _peer;
#endregion Private Fields
}
}
| |
// jQueryAjaxOptions.cs
// Script#/Libraries/jQuery/Core
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;
namespace jQueryApi {
/// <summary>
/// Represents Ajax request settings or options.
/// </summary>
[Imported]
[Serializable]
public sealed class jQueryAjaxOptions {
/// <summary>
/// Initializes an empty instance of a jQueryAjaxOptions object.
/// </summary>
public jQueryAjaxOptions() {
}
/// <summary>
/// Gets or sets whether the request is async.
/// </summary>
public bool Async {
get {
return false;
}
set {
}
}
/// <summary>
/// Gets or sets the callback to invoke before the request is sent.
/// </summary>
public AjaxSendingCallback BeforeSend {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets whether the request can be cached.
/// </summary>
public bool Cache {
get {
return false;
}
set {
}
}
/// <summary>
/// Gets or sets the callback invoked after the request is completed
/// and success or error callbacks have been invoked.
/// </summary>
public AjaxCompletedCallback Complete {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the content type of the data sent to the server.
/// </summary>
public string ContentType {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the element that will be the context for the request.
/// </summary>
public object Context {
get {
return null;
}
set {
}
}
/// <summary>
/// A map of dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response.
/// </summary>
public JsDictionary<string, Func<string, object>> Converters {
get;
set;
}
/// <summary>
/// Gets or sets the data to be sent to the server.
/// </summary>
public TypeOption<JsDictionary<string, object>, Array, string> Data {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the data type expected in response from the server.
/// </summary>
public string DataType {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the callback to be invoked if the request fails.
/// </summary>
public AjaxErrorCallback Error {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the function to be used to handle the raw response data of XMLHttpRequest.
/// </summary>
public AjaxDataFilterCallback DataFilter {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets whether to trigger global event handlers for this Ajax request.
/// </summary>
public bool Global {
get {
return false;
}
set {
}
}
/// <summary>
/// Gets or sets whether the request is successful only if its been modified since
/// the last request.
/// </summary>
public bool IfModified {
get {
return false;
}
set {
}
}
/// <summary>
/// Gets or sets whether the current environment should be treated as a local
/// environment (eg. when the page is loaded using file://).
/// </summary>
public bool IsLocal {
get {
return false;
}
set {
}
}
/// <summary>
/// Gets or sets the callback parameter name to use for JSONP requests.
/// </summary>
public string Jsonp {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the callback name to use for JSONP requests.
/// </summary>
public string JsonpCallback {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the mime type of the request.
/// </summary>
public string MimeType {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the password to be used for an HTTP authentication request.
/// </summary>
public string Password {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets whether the data passed in will be processed.
/// </summary>
public bool ProcessData {
get {
return false;
}
set {
}
}
/// <summary>
/// Gets or sets how to handle character sets for script and JSONP requests.
/// </summary>
public string ScriptCharset {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the function to invoke upon successful completion of the request.
/// </summary>
public AjaxRequestCallback Success {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the timeout in milliseconds for the request.
/// </summary>
public int Timeout {
get {
return 0;
}
set {
}
}
/// <summary>
/// Gets or sets if you want to use traditional parameter serialization.
/// </summary>
public bool Traditional {
get {
return false;
}
set {
}
}
/// <summary>
/// Gets or sets the type or HTTP verb associated with the request.
/// </summary>
public string Type {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the URL to be requested.
/// </summary>
public string Url {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the name of the user to use in a HTTP authentication request.
/// </summary>
public string Username {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets the function creating the XmlHttpRequest instance.
/// </summary>
[ScriptName("xhr")]
public XmlHttpRequestCreator XmlHttpRequestCreator {
get {
return null;
}
set {
}
}
/// <summary>
/// Gets or sets a set of additional name/value pairs set of the XmlHttpRequest
/// object.
/// </summary>
public JsDictionary<string, object> XhrFields {
get {
return null;
}
set {
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using com.calitha.goldparser;
namespace Epi.Core.AnalysisInterpreter.Rules
{
public partial class Rule_CompareExp : AnalysisRule
{
//AnalysisRule ConcatExp = null;
string op = null;
//AnalysisRule CompareExp = null;
private List<AnalysisRule> ParameterList = new List<AnalysisRule>();
string STRING = null;
public Rule_CompareExp(Rule_Context pContext, NonterminalToken pToken) : base(pContext)
{
// <Concat Exp> LIKE String
// <Concat Exp> '=' <Compare Exp>
// <Concat Exp> '<>' <Compare Exp>
// <Concat Exp> '>' <Compare Exp>
// <Concat Exp> '>=' <Compare Exp>
// <Concat Exp> '<' <Compare Exp>
// <Concat Exp> '<=' <Compare Exp>
// <Concat Exp>
//this.ConcatExp = new Rule_ConcatExp(pContext, (NonterminalToken)pToken.Tokens[0]);
this.ParameterList.Add(AnalysisRule.BuildStatments(pContext, pToken.Tokens[0]));
if (pToken.Tokens.Length > 1)
{
op = pToken.Tokens[1].ToString();
if (pToken.Tokens[1].ToString().Equals("LIKE", StringComparison.OrdinalIgnoreCase))
{
this.STRING = pToken.Tokens[2].ToString().Trim(new char[] {'"'});
}
else
{
//this.CompareExp = new Rule_CompareExp(pContext, (NonterminalToken)pToken.Tokens[2]);
this.ParameterList.Add(AnalysisRule.BuildStatments(pContext, pToken.Tokens[2]));
}
}
}
/// <summary>
/// perfoms comparison operations on expression ie (=, <=, >=, Like, >, <, and <)) returns a boolean
/// </summary>
/// <returns>object</returns>
public override object Execute()
{
object result = null;
if (op == null)
{
//result = this.ConcatExp.Execute();
result = this.ParameterList[0].Execute();
}
else
{
object LHSO = this.ParameterList[0].Execute(); // this.ConcatExp.Execute();
object RHSO;
double TryValue = 0.0;
int i;
if (this.ParameterList.Count > 1)
{
RHSO = this.ParameterList[1].Execute(); // this.CompareExp.Execute();
}
else
{
RHSO = this.STRING;
}
if (Util.IsEmpty(LHSO) && Util.IsEmpty(RHSO) && op.Equals("="))
{
result = true;
}
else if (Util.IsEmpty(LHSO) && Util.IsEmpty(RHSO) && op.Equals("<>"))
{
return false;
}
else if ((Util.IsEmpty(LHSO) || Util.IsEmpty(RHSO)))
{
if(op.Equals("<>"))
{
return ! (Util.IsEmpty(LHSO) && Util.IsEmpty(RHSO));
}
else
{
result = false;
}
}
else if (op.Equals("LIKE", StringComparison.OrdinalIgnoreCase))
{
//string testValue = "^" + RHSO.ToString().Replace("*", "(\\s|\\w)*") + "$";
string testValue = "^" + RHSO.ToString().Replace("*", ".*") + "$";
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(testValue, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (re.IsMatch(LHSO.ToString()))
{
result = true;
}
else
{
result = false;
}
}
else
{
if (this.NumericTypeList.Contains(LHSO.GetType().Name.ToUpperInvariant()) && this.NumericTypeList.Contains(RHSO.GetType().Name.ToUpperInvariant()))
{
LHSO = Convert.ToDouble(LHSO);
RHSO = Convert.ToDouble(RHSO);
}
if (!LHSO.GetType().Equals(RHSO.GetType()))
{
if (RHSO is Boolean && op.Equals(StringLiterals.EQUAL))
{
if (LHSO is double || LHSO is int || LHSO is byte || LHSO is decimal || LHSO is float || LHSO is long)
{
LHSO = Convert.ToDouble(LHSO);
if ((double)LHSO == 0)
{
result = RHSO.Equals(false);
}
else
{
result = (RHSO.Equals(!Util.IsEmpty(LHSO)));
}
}
else
{
result = (RHSO.Equals(!Util.IsEmpty(LHSO)));
}
}
else if (LHSO is string && this.NumericTypeList.Contains(RHSO.GetType().Name.ToUpperInvariant()) && double.TryParse(LHSO.ToString(), out TryValue))
{
i = TryValue.CompareTo(RHSO);
switch (op)
{
case "=":
result = (i == 0);
break;
case "<>":
result = (i != 0);
break;
case "<":
result = (i < 0);
break;
case ">":
result = (i > 0);
break;
case ">=":
result = (i >= 0);
break;
case "<=":
result = (i <= 0);
break;
}
}
else if (RHSO is string && this.NumericTypeList.Contains(LHSO.GetType().Name.ToUpperInvariant()) && double.TryParse(RHSO.ToString(), out TryValue))
{
i = TryValue.CompareTo(LHSO);
switch (op)
{
case "=":
result = (i == 0);
break;
case "<>":
result = (i != 0);
break;
case "<":
result = (i < 0);
break;
case ">":
result = (i > 0);
break;
case ">=":
result = (i >= 0);
break;
case "<=":
result = (i <= 0);
break;
}
}
else if (op.Equals(StringLiterals.EQUAL) && (LHSO is Boolean || RHSO is Boolean))
{
if (LHSO is Boolean && RHSO is Boolean)
{
result = LHSO == RHSO;
}
else if (LHSO is Boolean)
{
result = (Boolean)LHSO == (Boolean)this.ConvertStringToBoolean(RHSO.ToString());
}
else
{
result = (Boolean)this.ConvertStringToBoolean(LHSO.ToString()) == (Boolean)RHSO;
}
}
else
{
i = StringComparer.CurrentCultureIgnoreCase.Compare(LHSO.ToString(), RHSO.ToString());
switch (op)
{
case "=":
result = (i == 0);
break;
case "<>":
result = (i != 0);
break;
case "<":
result = (i < 0);
break;
case ">":
result = (i > 0);
break;
case ">=":
result = (i >= 0);
break;
case "<=":
result = (i <= 0);
break;
}
}
}
else
{
i = 0;
if (LHSO.GetType().Name.ToUpperInvariant() == "STRING" && RHSO.GetType().Name.ToUpperInvariant() == "STRING")
{
i = StringComparer.CurrentCulture.Compare(LHSO.ToString().Trim(), RHSO.ToString().Trim());
}
else if (LHSO is IComparable && RHSO is IComparable)
{
i = ((IComparable)LHSO).CompareTo((IComparable)RHSO);
}
switch (op)
{
case "=":
result = (i == 0);
break;
case "<>":
result = (i != 0);
break;
case "<":
result = (i < 0);
break;
case ">":
result = (i > 0);
break;
case ">=":
result = (i >= 0);
break;
case "<=":
result = (i <= 0);
break;
}
}
}
}
return result;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.