context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Reflection;
using FluentNHibernate.Mapping.Providers;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.Identity;
using System.Diagnostics;
namespace FluentNHibernate.Mapping
{
public class IdentityPart : IIdentityMappingProvider
{
private readonly AttributeStore<ColumnMapping> columnAttributes = new AttributeStore<ColumnMapping>();
private readonly IList<string> columns = new List<string>();
private readonly PropertyInfo property;
private readonly Type entityType;
private readonly AccessStrategyBuilder<IdentityPart> access;
private readonly AttributeStore<IdMapping> attributes = new AttributeStore<IdMapping>();
private readonly Type identityType;
private bool nextBool = true;
private readonly string columnName;
public IdentityPart(Type entity, PropertyInfo property)
{
this.property = property;
entityType = entity;
this.identityType = property.PropertyType;
this.columnName = property.Name;
access = new AccessStrategyBuilder<IdentityPart>(this, value => attributes.Set(x => x.Access, value));
GeneratedBy = new IdentityGenerationStrategyBuilder<IdentityPart>(this, property.PropertyType, entity);
SetDefaultGenerator();
}
public IdentityPart(Type entity, Type identityType, string columnName)
{
this.property = null;
this.entityType = entity;
this.identityType = identityType;
this.columnName = columnName;
access = new AccessStrategyBuilder<IdentityPart>(this, value => attributes.Set(x => x.Access, value));
GeneratedBy = new IdentityGenerationStrategyBuilder<IdentityPart>(this, this.identityType, entity);
SetDefaultGenerator();
}
private void SetDefaultGenerator()
{
var generatorMapping = new GeneratorMapping();
var defaultGenerator = new GeneratorBuilder(generatorMapping, identityType);
if (identityType == typeof(Guid))
defaultGenerator.GuidComb();
else if (identityType == typeof(int) || identityType == typeof(long))
defaultGenerator.Identity();
else
defaultGenerator.Assigned();
attributes.SetDefault(x => x.Generator, generatorMapping);
}
IdMapping IIdentityMappingProvider.GetIdentityMapping()
{
var mapping = new IdMapping(attributes.CloneInner())
{
ContainingEntityType = entityType
};
if (columns.Count > 0)
{
foreach (var column in columns)
mapping.AddColumn(new ColumnMapping(columnAttributes.CloneInner()) { Name = column });
}
else
mapping.AddDefaultColumn(new ColumnMapping(columnAttributes.CloneInner()) { Name = columnName });
if (property != null)
{
mapping.Name = columnName;
}
mapping.SetDefaultValue("Type", new TypeReference(identityType));
if (GeneratedBy.IsDirty)
mapping.Generator = GeneratedBy.GetGeneratorMapping();
return mapping;
}
public IdentityGenerationStrategyBuilder<IdentityPart> GeneratedBy { get; private set; }
/// <summary>
/// Set the access and naming strategy for this identity.
/// </summary>
public AccessStrategyBuilder<IdentityPart> Access
{
get { return access; }
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public IdentityPart Not
{
get
{
nextBool = !nextBool;
return this;
}
}
/// <summary>
/// Sets the unsaved-value of the identity.
/// </summary>
/// <param name="unsavedValue">Value that represents an unsaved value.</param>
public IdentityPart UnsavedValue(object unsavedValue)
{
attributes.Set(x => x.UnsavedValue, (unsavedValue ?? "null").ToString());
return this;
}
/// <summary>
/// Sets the column name for the identity field.
/// </summary>
/// <param name="columnName">Column name</param>
public IdentityPart Column(string columnName)
{
columns.Clear(); // only currently support one column for ids
columns.Add(columnName);
return this;
}
public IdentityPart Length(int length)
{
columnAttributes.Set(x => x.Length, length);
return this;
}
public IdentityPart Precision(int precision)
{
columnAttributes.Set(x => x.Precision, precision);
return this;
}
public IdentityPart Scale(int scale)
{
columnAttributes.Set(x => x.Scale, scale);
return this;
}
public IdentityPart Nullable()
{
columnAttributes.Set(x => x.NotNull, !nextBool);
nextBool = true;
return this;
}
public IdentityPart Unique()
{
columnAttributes.Set(x => x.Unique, nextBool);
nextBool = true;
return this;
}
public IdentityPart UniqueKey(string keyColumns)
{
columnAttributes.Set(x => x.UniqueKey, keyColumns);
return this;
}
public IdentityPart CustomSqlType(string sqlType)
{
columnAttributes.Set(x => x.SqlType, sqlType);
return this;
}
public IdentityPart Index(string key)
{
columnAttributes.Set(x => x.Index, key);
return this;
}
public IdentityPart Check(string constraint)
{
columnAttributes.Set(x => x.Check, constraint);
return this;
}
public IdentityPart Default(object value)
{
columnAttributes.Set(x => x.Default, value.ToString());
return this;
}
public IdentityPart CustomType<T>()
{
attributes.Set(x => x.Type, new TypeReference(typeof(T)));
return this;
}
public IdentityPart CustomType(Type type)
{
attributes.Set(x => x.Type, new TypeReference(type));
return this;
}
public IdentityPart CustomType(string type)
{
attributes.Set(x => x.Type, new TypeReference(type));
return this;
}
}
}
| |
//
// System.Xml.Serialization.TypeData
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Lluis Sanchez Gual (lluis@ximian.com)
//
// (C) 2002 Ximian, Inc (http://www.ximian.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Reflection;
namespace System.Xml.Serialization
{
internal class TypeData
{
Type type;
string elementName;
SchemaTypes sType;
Type listItemType;
string typeName;
string fullTypeName;
TypeData listItemTypeData;
TypeData listTypeData;
public TypeData (Type type, string elementName, bool isPrimitive)
{
this.type = type;
this.elementName = elementName;
this.typeName = type.Name;
this.fullTypeName = type.FullName.Replace ('+', '.');
if (isPrimitive)
sType = SchemaTypes.Primitive;
else
{
if (type.IsEnum)
sType = SchemaTypes.Enum;
else if (typeof(IXmlSerializable).IsAssignableFrom (type))
sType = SchemaTypes.XmlSerializable;
else if (typeof (System.Xml.XmlNode).IsAssignableFrom (type))
sType = SchemaTypes.XmlNode;
else if (type.IsArray || typeof(IEnumerable).IsAssignableFrom (type))
sType = SchemaTypes.Array;
else
sType = SchemaTypes.Class;
}
}
internal TypeData (string typeName, string fullTypeName, string xmlType, SchemaTypes schemaType, TypeData listItemTypeData)
{
this.elementName = xmlType;
this.typeName = typeName;
this.fullTypeName = fullTypeName.Replace ('+', '.');
this.listItemTypeData = listItemTypeData;
this.sType = schemaType;
}
public string TypeName
{
get {
return typeName;
}
}
public string XmlType
{
get {
return elementName;
}
}
public Type Type
{
get {
return type;
}
}
public string FullTypeName
{
get {
return fullTypeName;
}
}
public SchemaTypes SchemaType
{
get {
return sType;
}
}
public bool IsListType
{
get { return SchemaType == SchemaTypes.Array; }
}
public bool IsComplexType
{
get
{
return (SchemaType == SchemaTypes.Class ||
SchemaType == SchemaTypes.Array ||
SchemaType == SchemaTypes.Enum ||
SchemaType == SchemaTypes.XmlNode ||
SchemaType == SchemaTypes.XmlSerializable );
}
}
public bool IsValueType
{
get
{
if (type != null) return type.IsValueType;
else return (sType == SchemaTypes.Primitive || sType == SchemaTypes.Enum);
}
}
public TypeData ListItemTypeData
{
get
{
if (listItemTypeData == null && type != null)
listItemTypeData = TypeTranslator.GetTypeData (ListItemType);
return listItemTypeData;
}
}
public Type ListItemType
{
get
{
if (type == null)
throw new InvalidOperationException ("Property ListItemType is not supported for custom types");
if (listItemType != null) return listItemType;
if (SchemaType != SchemaTypes.Array)
throw new InvalidOperationException (Type.FullName + " is not a collection");
else if (type.IsArray)
listItemType = type.GetElementType ();
else if (typeof(ICollection).IsAssignableFrom (type))
{
PropertyInfo prop = GetIndexerProperty (type);
if (prop == null)
throw new InvalidOperationException ("You must implement a default accessor on " + type.FullName + " because it inherits from ICollection");
return prop.PropertyType;
}
else
{
MethodInfo met = type.GetMethod ("Add");
if (met == null)
throw new InvalidOperationException ("The collection " + type.FullName + " must implement an Add method");
ParameterInfo[] pars = met.GetParameters();
if (pars.Length != 1)
throw new InvalidOperationException ("The Add method of the collection " + type.FullName + " must have only one parameter");
return pars[0].ParameterType;
}
return listItemType;
}
}
public TypeData ListTypeData
{
get
{
if (listTypeData != null) return listTypeData;
listTypeData = new TypeData (TypeName + "[]",
FullTypeName + "[]",
TypeTranslator.GetArrayName(XmlType),
SchemaTypes.Array, this);
return listTypeData;
}
}
public static PropertyInfo GetIndexerProperty (Type collectionType)
{
PropertyInfo[] props = collectionType.GetProperties (BindingFlags.Instance | BindingFlags.Public);
foreach (PropertyInfo prop in props)
{
ParameterInfo[] pi = prop.GetIndexParameters ();
if (pi != null && pi.Length == 1 && pi[0].ParameterType == typeof(int))
return prop;
}
return null;
}
}
}
| |
namespace SideBySide;
public class StoredProcedureTests : IClassFixture<StoredProcedureFixture>
{
public StoredProcedureTests(StoredProcedureFixture database)
{
m_database = database;
}
[Theory]
[InlineData("FUNCTION", "NonQuery", false)]
[InlineData("FUNCTION", "Scalar", false)]
[InlineData("FUNCTION", "Reader", false)]
[InlineData("PROCEDURE", "NonQuery", true)]
[InlineData("PROCEDURE", "NonQuery", false)]
[InlineData("PROCEDURE", "Scalar", true)]
[InlineData("PROCEDURE", "Scalar", false)]
[InlineData("PROCEDURE", "Reader", true)]
[InlineData("PROCEDURE", "Reader", false)]
public async Task StoredProcedureEcho(string procedureType, string executorType, bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "echo" + (procedureType == "FUNCTION" ? "f" : "p");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new()
{
ParameterName = "@name",
DbType = DbType.String,
Direction = ParameterDirection.Input,
Value = "hello",
});
// we make the assumption that Stored Procedures with ParameterDirection.ReturnValue are functions
if (procedureType == "FUNCTION")
{
cmd.Parameters.Add(new()
{
ParameterName = "@result",
DbType = DbType.String,
Direction = ParameterDirection.ReturnValue,
});
}
if (prepare)
await cmd.PrepareAsync();
var result = await ExecuteCommandAsync(cmd, executorType);
if (procedureType == "PROCEDURE" && executorType != "NonQuery")
Assert.Equal(cmd.Parameters["@name"].Value, result);
if (procedureType == "FUNCTION")
Assert.Equal(cmd.Parameters["@name"].Value, cmd.Parameters["@result"].Value);
}
[Fact]
public void CallFailingFunction()
{
using var command = m_database.Connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "failing_function";
var returnParameter = command.CreateParameter();
returnParameter.DbType = DbType.Int32;
returnParameter.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnParameter);
Assert.Throws<MySqlException>(() => command.ExecuteNonQuery());
}
[Fact]
public void CallFailingFunctionInTransaction()
{
using var transaction = m_database.Connection.BeginTransaction();
using var command = m_database.Connection.CreateCommand();
command.Transaction = transaction;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "failing_function";
var returnParameter = command.CreateParameter();
returnParameter.DbType = DbType.Int32;
returnParameter.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnParameter);
Assert.Throws<MySqlException>(() => command.ExecuteNonQuery());
transaction.Commit();
}
[SkippableTheory(ServerFeatures.StoredProcedures)]
[InlineData("FUNCTION", false)]
[InlineData("PROCEDURE", true)]
[InlineData("PROCEDURE", false)]
public async Task StoredProcedureEchoException(string procedureType, bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "echo" + (procedureType == "FUNCTION" ? "f" : "p");
cmd.CommandType = CommandType.StoredProcedure;
if (prepare)
{
#if BASELINE
await Assert.ThrowsAsync<ArgumentException>(async () => await cmd.PrepareAsync());
#else
await cmd.PrepareAsync();
#endif
}
if (procedureType == "FUNCTION")
await Assert.ThrowsAsync<InvalidOperationException>(async () => await cmd.ExecuteNonQueryAsync());
else
await Assert.ThrowsAsync<ArgumentException>(async () => await cmd.ExecuteNonQueryAsync());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task StoredProcedureNoResultSet(bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "out_string";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new()
{
ParameterName = "@value",
DbType = DbType.String,
Direction = ParameterDirection.Output,
});
if (prepare)
await cmd.PrepareAsync();
using (var reader = await cmd.ExecuteReaderAsync())
{
Assert.False(await reader.ReadAsync());
Assert.False(await reader.NextResultAsync());
}
Assert.Equal("test value", cmd.Parameters[0].Value);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task FieldCountForNoResultSet(bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "out_string";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new()
{
ParameterName = "@value",
DbType = DbType.String,
Direction = ParameterDirection.Output,
});
if (prepare)
await cmd.PrepareAsync();
using (var reader = await cmd.ExecuteReaderAsync())
{
Assert.Equal(0, reader.FieldCount);
Assert.False(reader.HasRows);
Assert.False(await reader.ReadAsync());
Assert.Equal(0, reader.FieldCount);
Assert.False(reader.HasRows);
}
Assert.Equal("test value", cmd.Parameters[0].Value);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task GetSchemaTableForNoResultSet(bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "out_string";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new()
{
ParameterName = "@value",
DbType = DbType.String,
Direction = ParameterDirection.Output,
});
if (prepare)
await cmd.PrepareAsync();
using var reader = await cmd.ExecuteReaderAsync();
Assert.False(await reader.ReadAsync());
var table = reader.GetSchemaTable();
Assert.Null(table);
Assert.False(await reader.NextResultAsync());
}
#if !BASELINE
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task GetColumnSchemaForNoResultSet(bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "out_string";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new()
{
ParameterName = "@value",
DbType = DbType.String,
Direction = ParameterDirection.Output,
});
if (prepare)
await cmd.PrepareAsync();
using var reader = await cmd.ExecuteReaderAsync();
Assert.False(await reader.ReadAsync());
Assert.Empty(reader.GetColumnSchema());
Assert.False(await reader.NextResultAsync());
}
#endif
[SkippableTheory(Baseline = "https://bugs.mysql.com/bug.php?id=102303")]
[InlineData(true)]
[InlineData(false)]
public async Task StoredProcedureOutIncorrectType(bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "out_string";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new()
{
ParameterName = "@value",
DbType = DbType.Double,
Direction = ParameterDirection.Output,
});
if (prepare)
await cmd.PrepareAsync();
await Assert.ThrowsAsync<FormatException>(async () => await cmd.ExecuteNonQueryAsync());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task StoredProcedureReturnsNull(bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "out_null";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new()
{
ParameterName = "@string_value",
DbType = DbType.String,
Direction = ParameterDirection.Output,
IsNullable = true,
Value = "non null",
});
cmd.Parameters.Add(new()
{
ParameterName = "@int_value",
DbType = DbType.Int32,
Direction = ParameterDirection.Output,
IsNullable = true,
Value = "123",
});
if (prepare)
await cmd.PrepareAsync();
await cmd.ExecuteNonQueryAsync();
Assert.Equal(DBNull.Value, cmd.Parameters["@string_value"].Value);
Assert.Equal(DBNull.Value, cmd.Parameters["@int_value"].Value);
}
[Theory]
[InlineData("NonQuery", true)]
[InlineData("NonQuery", false)]
[InlineData("Scalar", true)]
[InlineData("Scalar", false)]
[InlineData("Reader", true)]
[InlineData("Reader", false)]
public async Task StoredProcedureCircle(string executorType, bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "circle";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new()
{
ParameterName = "@radius",
DbType = DbType.Double,
Direction = ParameterDirection.Input,
Value = 1.0,
});
cmd.Parameters.Add(new()
{
ParameterName = "@height",
DbType = DbType.Double,
Direction = ParameterDirection.Input,
Value = 2.0,
});
cmd.Parameters.Add(new()
{
ParameterName = "@name",
DbType = DbType.String,
Direction = ParameterDirection.Input,
Value = "awesome",
});
cmd.Parameters.Add(new()
{
ParameterName = "@diameter",
DbType = DbType.Double,
Direction = ParameterDirection.Output,
});
cmd.Parameters.Add(new()
{
ParameterName = "@circumference",
DbType = DbType.Double,
Direction = ParameterDirection.Output,
});
cmd.Parameters.Add(new()
{
ParameterName = "@area",
DbType = DbType.Double,
Direction = ParameterDirection.Output,
});
cmd.Parameters.Add(new()
{
ParameterName = "@volume",
DbType = DbType.Double,
Direction = ParameterDirection.Output,
});
cmd.Parameters.Add(new()
{
ParameterName = "@shape",
DbType = DbType.String,
Direction = ParameterDirection.Output,
});
if (prepare)
await cmd.PrepareAsync();
await CircleAssertions(cmd, executorType);
}
[SkippableTheory(ServerFeatures.StoredProcedures)]
[InlineData("NonQuery", true)]
[InlineData("NonQuery", false)]
[InlineData("Scalar", true)]
[InlineData("Scalar", false)]
[InlineData("Reader", true)]
[InlineData("Reader", false)]
public async Task StoredProcedureCircleCached(string executorType, bool prepare)
{
// reorder parameters
// remove return types
// remove directions (MySqlConnector only, MySql.Data does not fix these up)
// CachedProcedure class should fix everything up based on parameter names
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "circle";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new()
{
ParameterName = "@name",
Value = "awesome",
#if BASELINE
Direction = ParameterDirection.Input,
#endif
});
cmd.Parameters.Add(new()
{
ParameterName = "@radius",
Value = 1.5,
#if BASELINE
Direction = ParameterDirection.Input,
#endif
});
cmd.Parameters.Add(new()
{
ParameterName = "@shape",
#if BASELINE
Direction = ParameterDirection.Output,
#endif
});
cmd.Parameters.Add(new()
{
ParameterName = "@height",
Value = 2.0,
#if BASELINE
Direction = ParameterDirection.Input,
#endif
});
cmd.Parameters.Add(new()
{
ParameterName = "@diameter",
#if BASELINE
Direction = ParameterDirection.Output,
#endif
});
cmd.Parameters.Add(new()
{
ParameterName = "@area",
#if BASELINE
Direction = ParameterDirection.Output,
#endif
});
cmd.Parameters.Add(new()
{
ParameterName = "@volume",
#if BASELINE
Direction = ParameterDirection.Output,
#endif
});
cmd.Parameters.Add(new()
{
ParameterName = "@circumference",
#if BASELINE
Direction = ParameterDirection.Output,
#endif
});
if (prepare)
await cmd.PrepareAsync();
await CircleAssertions(cmd, executorType);
}
private async Task CircleAssertions(DbCommand cmd, string executorType)
{
var result = await ExecuteCommandAsync(cmd, executorType);
if (executorType != "NonQuery")
Assert.Equal((string) cmd.Parameters["@name"].Value + (string) cmd.Parameters["@shape"].Value, result);
Assert.Equal(2 * (double) cmd.Parameters["@radius"].Value, cmd.Parameters["@diameter"].Value);
Assert.Equal(2.0 * Math.PI * (double) cmd.Parameters["@radius"].Value, cmd.Parameters["@circumference"].Value);
Assert.Equal(Math.PI * Math.Pow((double) cmd.Parameters["@radius"].Value, 2), cmd.Parameters["@area"].Value);
Assert.Equal((double) cmd.Parameters["@area"].Value * (double) cmd.Parameters["@height"].Value, cmd.Parameters["@volume"].Value);
}
private async Task<object> ExecuteCommandAsync(DbCommand cmd, string executorType)
{
switch (executorType)
{
case "NonQuery":
await cmd.ExecuteNonQueryAsync();
return null;
case "Scalar":
return await cmd.ExecuteScalarAsync();
default:
using (var reader = await cmd.ExecuteReaderAsync())
{
if (await reader.ReadAsync())
return reader.GetValue(0);
return null;
}
}
}
[Theory]
[InlineData("factor", true)]
[InlineData("factor", false)]
[InlineData("@factor", true)]
[InlineData("@factor", false)]
[InlineData("?factor", true)]
[InlineData("?factor", false)]
public async Task MultipleRows(string paramaterName, bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "number_multiples";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new() { ParameterName = paramaterName, Value = 3 });
if (prepare)
await cmd.PrepareAsync();
using var reader = await cmd.ExecuteReaderAsync();
Assert.True(await reader.ReadAsync());
Assert.Equal("six", reader.GetString(0));
Assert.True(await reader.ReadAsync());
Assert.Equal("three", reader.GetString(0));
Assert.False(await reader.ReadAsync());
Assert.False(await reader.NextResultAsync());
}
[Theory]
[InlineData(1, new string[0], new[] { "eight", "five", "four", "seven", "six", "three", "two" }, true)]
[InlineData(1, new string[0], new[] { "eight", "five", "four", "seven", "six", "three", "two" }, false)]
[InlineData(4, new[] { "one", "three", "two" }, new[] { "eight", "five", "seven", "six" }, true)]
[InlineData(4, new[] { "one", "three", "two" }, new[] { "eight", "five", "seven", "six" }, false)]
[InlineData(8, new[] { "five", "four", "one", "seven", "six", "three", "two" }, new string[0], true)]
[InlineData(8, new[] { "five", "four", "one", "seven", "six", "three", "two" }, new string[0], false)]
public async Task MultipleResultSets(int pivot, string[] firstResultSet, string[] secondResultSet, bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = "multiple_result_sets";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new() { ParameterName = "@pivot", Value = pivot });
if (prepare)
await cmd.PrepareAsync();
using var reader = await cmd.ExecuteReaderAsync();
foreach (var result in firstResultSet)
{
Assert.True(await reader.ReadAsync());
Assert.Equal(result, reader.GetString(0));
}
Assert.False(await reader.ReadAsync());
Assert.True(await reader.NextResultAsync());
foreach (var result in secondResultSet)
{
Assert.True(await reader.ReadAsync());
Assert.Equal(result, reader.GetString(0));
}
Assert.False(await reader.ReadAsync());
Assert.False(await reader.NextResultAsync());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task InOut(bool prepare)
{
using var connection = CreateOpenConnection();
var parameter = new MySqlParameter
{
ParameterName = "high",
DbType = DbType.Int32,
Direction = ParameterDirection.InputOutput,
Value = 1
};
while ((int) parameter.Value < 8)
{
using var cmd = connection.CreateCommand();
var nextValue = (int) parameter.Value + 1;
cmd.CommandText = "number_lister";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(parameter);
if (prepare)
await cmd.PrepareAsync();
using (var reader = await cmd.ExecuteReaderAsync())
{
for (var i = 0; i < (int) parameter.Value; i++)
{
Assert.True(await reader.ReadAsync());
Assert.Equal(i + 1, reader.GetInt32(0));
Assert.True(reader.GetString(1).Length > 0);
}
await reader.NextResultAsync();
}
Assert.Equal(nextValue, parameter.Value);
}
}
[Theory]
[InlineData(false, true)]
[InlineData(false, false)]
[InlineData(true, true)]
[InlineData(true, false)]
public async Task DottedName(bool useDatabaseName, bool prepare)
{
using var connection = CreateOpenConnection();
using var cmd = connection.CreateCommand();
cmd.CommandText = (useDatabaseName ? $"{connection.Database}." : "") + "`dotted.name`";
cmd.CommandType = CommandType.StoredProcedure;
if (prepare)
await cmd.PrepareAsync();
using var reader = await cmd.ExecuteReaderAsync();
Assert.True(await reader.ReadAsync());
Assert.Equal(1, reader.GetInt32(0));
Assert.Equal(2, reader.GetInt32(1));
Assert.Equal(3, reader.GetInt32(2));
Assert.False(await reader.ReadAsync());
Assert.False(await reader.NextResultAsync());
}
[Fact]
public void DeriveParametersCircle()
{
using var cmd = new MySqlCommand("circle", m_database.Connection);
cmd.CommandType = CommandType.StoredProcedure;
MySqlCommandBuilder.DeriveParameters(cmd);
Assert.Collection(cmd.Parameters.Cast<MySqlParameter>(),
AssertParameter("@radius", ParameterDirection.Input, MySqlDbType.Double),
AssertParameter("@height", ParameterDirection.Input, MySqlDbType.Double),
AssertParameter("@name", ParameterDirection.Input, MySqlDbType.VarChar),
AssertParameter("@diameter", ParameterDirection.Output, MySqlDbType.Double),
AssertParameter("@circumference", ParameterDirection.Output, MySqlDbType.Double),
AssertParameter("@area", ParameterDirection.Output, MySqlDbType.Double),
AssertParameter("@volume", ParameterDirection.Output, MySqlDbType.Double),
AssertParameter("@shape", ParameterDirection.Output, MySqlDbType.VarChar));
}
[Fact]
public void DeriveParametersNumberLister()
{
using var cmd = new MySqlCommand("number_lister", m_database.Connection);
cmd.CommandType = CommandType.StoredProcedure;
MySqlCommandBuilder.DeriveParameters(cmd);
Assert.Collection(cmd.Parameters.Cast<MySqlParameter>(),
AssertParameter("@high", ParameterDirection.InputOutput, MySqlDbType.Int32));
}
[Fact]
public void DeriveParametersRemovesExisting()
{
using var cmd = new MySqlCommand("number_lister", m_database.Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("test1", 1);
cmd.Parameters.AddWithValue("test2", 2);
cmd.Parameters.AddWithValue("test3", 3);
MySqlCommandBuilder.DeriveParameters(cmd);
Assert.Collection(cmd.Parameters.Cast<MySqlParameter>(),
AssertParameter("@high", ParameterDirection.InputOutput, MySqlDbType.Int32));
}
[Fact]
public void DeriveParametersDoesNotExist()
{
using var cmd = new MySqlCommand("xx_does_not_exist", m_database.Connection);
cmd.CommandType = CommandType.StoredProcedure;
Assert.Throws<MySqlException>(() => MySqlCommandBuilder.DeriveParameters(cmd));
}
[Fact]
public void DeriveParametersDoesNotExistThenIsCreated()
{
using (var cmd = new MySqlCommand("drop procedure if exists xx_does_not_exist_2;", m_database.Connection))
cmd.ExecuteNonQuery();
using (var cmd = new MySqlCommand("xx_does_not_exist_2", m_database.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
Assert.Throws<MySqlException>(() => MySqlCommandBuilder.DeriveParameters(cmd));
}
using (var cmd = new MySqlCommand(@"create procedure xx_does_not_exist_2(
IN param1 INT,
OUT param2 VARCHAR(100))
BEGIN
SELECT 'test' INTO param2;
END", m_database.Connection))
{
cmd.ExecuteNonQuery();
}
using (var cmd = new MySqlCommand("xx_does_not_exist_2", m_database.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
MySqlCommandBuilder.DeriveParameters(cmd);
Assert.Collection(cmd.Parameters.Cast<MySqlParameter>(),
AssertParameter("@param1", ParameterDirection.Input, MySqlDbType.Int32),
AssertParameter("@param2", ParameterDirection.Output, MySqlDbType.VarChar));
}
}
[Theory]
[InlineData("bit(1)", 1)]
[InlineData("bit(10)", 10)]
#if !BASELINE
[InlineData("bool", 1)]
[InlineData("tinyint(1)", 1)]
#endif
[InlineData("char(30)", 30)]
[InlineData("mediumtext", 0)]
[InlineData("varchar(50)", 50)]
// These return nonzero sizes for some versions of MySQL Server 8.0
// [InlineData("bit", 0)]
// [InlineData("tinyint", 0)]
// [InlineData("bigint", 0)]
// [InlineData("bigint unsigned", 0)]
public void DeriveParametersParameterSize(string parameterType, int expectedSize)
{
var csb = AppConfig.CreateConnectionStringBuilder();
csb.Pooling = false;
using var connection = new MySqlConnection(csb.ConnectionString);
connection.Open();
using (var cmd = new MySqlCommand($"drop procedure if exists parameter_size; create procedure parameter_size(in param1 {parameterType}) begin end;", connection))
cmd.ExecuteNonQuery();
using (var cmd = new MySqlCommand("parameter_size", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
MySqlCommandBuilder.DeriveParameters(cmd);
var parameter = (MySqlParameter) Assert.Single(cmd.Parameters);
Assert.Equal(expectedSize, parameter.Size);
}
}
[Theory]
[InlineData("bit", MySqlDbType.Bit)]
[InlineData("bit(1)", MySqlDbType.Bit)]
#if BASELINE
[InlineData("bool", MySqlDbType.Byte)]
[InlineData("tinyint(1)", MySqlDbType.Byte)]
#else
[InlineData("bool", MySqlDbType.Bool)]
[InlineData("tinyint(1)", MySqlDbType.Bool)]
#endif
[InlineData("tinyint", MySqlDbType.Byte)]
[InlineData("bigint", MySqlDbType.Int64)]
[InlineData("bigint unsigned", MySqlDbType.UInt64)]
[InlineData("char(30)", MySqlDbType.String)]
[InlineData("mediumtext", MySqlDbType.MediumText)]
[InlineData("varchar(50)", MySqlDbType.VarChar)]
public void DeriveParametersParameterType(string parameterType, MySqlDbType expectedType)
{
var csb = AppConfig.CreateConnectionStringBuilder();
csb.Pooling = false;
using var connection = new MySqlConnection(csb.ConnectionString);
connection.Open();
using (var cmd = new MySqlCommand($"drop procedure if exists parameter_size; create procedure parameter_size(in param1 {parameterType}) begin end;", connection))
cmd.ExecuteNonQuery();
using (var cmd = new MySqlCommand("parameter_size", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
MySqlCommandBuilder.DeriveParameters(cmd);
var parameter = (MySqlParameter) Assert.Single(cmd.Parameters);
Assert.Equal(expectedType, parameter.MySqlDbType);
}
}
[SkippableFact(ServerFeatures.Json, Baseline = "https://bugs.mysql.com/bug.php?id=89335")]
public void DeriveParametersSetJson()
{
using var cmd = new MySqlCommand("SetJson", m_database.Connection);
cmd.CommandType = CommandType.StoredProcedure;
MySqlCommandBuilder.DeriveParameters(cmd);
Assert.Collection(cmd.Parameters.Cast<MySqlParameter>(),
AssertParameter("@vJson", ParameterDirection.Input, MySqlDbType.JSON));
}
[SkippableFact(ServerFeatures.Json, Baseline = "https://bugs.mysql.com/bug.php?id=101485")]
public void PassJsonParameter()
{
using var cmd = new MySqlCommand("SetJson", m_database.Connection);
cmd.CommandType = CommandType.StoredProcedure;
var json = "{\"prop\":[null]}";
cmd.Parameters.AddWithValue("@vJson", json).MySqlDbType = MySqlDbType.JSON;
using var reader = cmd.ExecuteReader();
Assert.True(reader.Read());
Assert.Equal(json, reader.GetString(0).Replace(" ", ""));
Assert.False(reader.Read());
}
private static Action<MySqlParameter> AssertParameter(string name, ParameterDirection direction, MySqlDbType mySqlDbType)
{
return x =>
{
Assert.Equal(name, x.ParameterName);
Assert.Equal(direction, x.Direction);
Assert.Equal(mySqlDbType, x.MySqlDbType);
};
}
[Theory]
[InlineData("echof", "FUNCTION", "varchar(63)", "BEGIN RETURN name; END", "NO", "CONTAINS SQL")]
[InlineData("echop", "PROCEDURE", null, "BEGIN SELECT name; END", "NO", "CONTAINS SQL")]
[InlineData("failing_function", "FUNCTION", "decimal(10,5)", "BEGIN DECLARE v1 DECIMAL(10,5); SELECT c1 FROM table_that_does_not_exist INTO v1; RETURN v1; END", "NO", "CONTAINS SQL")]
public void ProceduresSchema(string procedureName, string procedureType, string dtdIdentifier, string routineDefinition, string isDeterministic, string dataAccess)
{
var dataTable = m_database.Connection.GetSchema("Procedures");
var schema = m_database.Connection.Database;
var row = dataTable.Rows.Cast<DataRow>().Single(x => schema.Equals(x["ROUTINE_SCHEMA"]) && procedureName.Equals(x["ROUTINE_NAME"]));
Assert.Equal(procedureName, row["SPECIFIC_NAME"]);
Assert.Equal(procedureType, row["ROUTINE_TYPE"]);
if (dtdIdentifier is null)
Assert.Equal(DBNull.Value, row["DTD_IDENTIFIER"]);
else
Assert.Equal(dtdIdentifier, ((string) row["DTD_IDENTIFIER"]).Split(' ')[0]);
Assert.Equal(routineDefinition, NormalizeSpaces((string) row["ROUTINE_DEFINITION"]));
Assert.Equal(isDeterministic, row["IS_DETERMINISTIC"]);
Assert.Equal(dataAccess, ((string) row["SQL_DATA_ACCESS"]).Replace('_', ' '));
}
[Fact]
public void CallNonExistentStoredProcedure()
{
using var command = new MySqlCommand("NonExistentStoredProcedure", m_database.Connection);
command.CommandType = CommandType.StoredProcedure;
Assert.Throws<MySqlException>(() => command.ExecuteNonQuery());
}
[Fact]
public void PrepareNonExistentStoredProcedure()
{
using var connection = CreateOpenConnection();
using var command = new MySqlCommand("NonExistentStoredProcedure", connection);
command.CommandType = CommandType.StoredProcedure;
Assert.Throws<MySqlException>(command.Prepare);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void OutputTimeParameter(bool prepare)
{
using var connection = CreateOpenConnection();
using var command = new MySqlCommand("GetTime", connection);
command.CommandType = CommandType.StoredProcedure;
var parameter = command.CreateParameter();
parameter.ParameterName = "OutTime";
parameter.Direction = ParameterDirection.Output;
command.Parameters.Add(parameter);
if (prepare)
command.Prepare();
command.ExecuteNonQuery();
Assert.IsType<TimeSpan>(parameter.Value);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void EnumProcedure(bool prepare)
{
using var connection = CreateOpenConnection();
using var command = new MySqlCommand("EnumProcedure", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@input", "One");
if (prepare)
command.Prepare();
using var reader = command.ExecuteReader();
Assert.True(reader.Read());
Assert.Equal("One", reader.GetString(0));
Assert.False(reader.Read());
}
[SkippableTheory(Baseline = "https://bugs.mysql.com/bug.php?id=104913")]
[InlineData("`a b`")]
[InlineData("`a.b`")]
[InlineData("`a``b`")]
[InlineData("`a b.c ``d`")]
public void SprocNameSpecialCharacters(string sprocName)
{
using var connection = CreateOpenConnection();
using (var command = new MySqlCommand($@"DROP PROCEDURE IF EXISTS {sprocName};
CREATE PROCEDURE {sprocName} ()
BEGIN
SELECT 'test' AS Result;
END;", connection))
{
command.ExecuteNonQuery();
}
using (var command = new MySqlCommand(sprocName, connection))
{
command.CommandType = CommandType.StoredProcedure;
using var reader = command.ExecuteReader();
Assert.True(reader.Read());
Assert.Equal("test", reader.GetString(0));
Assert.False(reader.Read());
}
}
private static string NormalizeSpaces(string input)
{
input = input.Replace('\r', ' ');
input = input.Replace('\n', ' ');
input = input.Replace('\t', ' ');
int startingLength;
do
{
startingLength = input.Length;
input = input.Replace(" ", " ");
} while (input.Length != startingLength);
return input;
}
private static MySqlConnection CreateOpenConnection()
{
var connection = new MySqlConnection(AppConfig.ConnectionString);
connection.Open();
return connection;
}
readonly DatabaseFixture m_database;
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Category
{
using System;
using System.Linq;
using System.Collections.Generic;
using Adxstudio.Xrm.Services;
using ContentAccess;
using Security;
using Services.Query;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
/// <summary>
/// Category Data Adapter
/// </summary>
public class CategoryDataAdapter : CategoryAccessProvider, ICategoryDataAdapter
{
/// <summary>
/// Initializes a new instance of the <see cref="CategoryDataAdapter"/> class.
/// </summary>
/// <param name="category">The category to get and set data for</param>
/// <param name="portalName">The configured name of the portal to get and set data for.</param>
public CategoryDataAdapter(EntityReference category, string portalName = null)
: this(category, new KnowledgeArticles.PortalConfigurationDataAdapterDependencies(portalName))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CategoryDataAdapter"/> class.
/// </summary>
/// <param name="category">The category to get and set data for</param>
/// <param name="portalName">The configured name of the portal to get and set data for</param>
public CategoryDataAdapter(Entity category, string portalName = null)
: this(category.ToEntityReference(), portalName)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CategoryDataAdapter"/> class.
/// </summary>
/// <param name="category">Category Entity Reference</param>
/// <param name="dependencies">Data Adapter Dependencies</param>
public CategoryDataAdapter(EntityReference category, KnowledgeArticles.IDataAdapterDependencies dependencies)
{
category.ThrowOnNull("article");
category.AssertLogicalName("knowledgearticle");
dependencies.ThrowOnNull("dependencies");
this.Category = category;
this.Dependencies = dependencies;
}
/// <summary>
/// Gets the Current Category
/// </summary>
/// <returns>Category Interface reference</returns>
public virtual ICategory Select()
{
var category = this.GetCategoryEntity(this.Dependencies.GetServiceContext());
return category == null
? null
: new CategoryFactory(this.Dependencies).Create(new[] { category }).FirstOrDefault();
}
/// <summary>
/// Gets the Category Entity using the Category Id from Service Context
/// </summary>
/// <param name="serviceContext">Organization Service Context</param>
/// <returns>Category as an Entity</returns>
private Entity GetCategoryEntity(OrganizationServiceContext serviceContext)
{
var category = serviceContext.RetrieveSingle("category", "categoryid", this.Category.Id, FetchAttribute.All);
return category;
}
/// <summary>
/// Data Adapter Dependencies
/// </summary>
protected KnowledgeArticles.IDataAdapterDependencies Dependencies { get; set; }
/// <summary>
/// Category Entity Reference
/// </summary>
protected EntityReference Category { get; set; }
/// <summary>
/// Gets Related Articles of a Category
/// </summary>
/// <returns>IEnumerable of Related Article</returns>
public IEnumerable<RelatedArticle> SelectRelatedArticles()
{
var category = this.Select();
var relatedArticlesFetch = new Fetch
{
Distinct = true,
Entity = new FetchEntity
{
Name = "knowledgearticle",
Attributes = new List<FetchAttribute>()
{
new FetchAttribute("articlepublicnumber"),
new FetchAttribute("knowledgearticleid"),
new FetchAttribute("title"),
new FetchAttribute("keywords"),
new FetchAttribute("createdon"),
new FetchAttribute("statecode"),
new FetchAttribute("statuscode"),
new FetchAttribute("isrootarticle"),
new FetchAttribute("islatestversion"),
new FetchAttribute("isprimary"),
new FetchAttribute("knowledgearticleviews")
},
Filters = new List<Filter>()
{
new Filter
{
Type = LogicalOperator.And,
Conditions = new List<Condition>()
{
new Condition("isrootarticle", ConditionOperator.Equal, 0),
new Condition("statecode", ConditionOperator.Equal, 3),
new Condition("isinternal", ConditionOperator.Equal, 0)
}
},
},
Links = new List<Link>()
{
new Link
{
Name = "knowledgearticlescategories",
FromAttribute = "knowledgearticleid",
ToAttribute = "knowledgearticleid",
Intersect = true,
Visible = false,
Filters = new List<Filter>()
{
new Filter
{
Type = LogicalOperator.And,
Conditions = new List<Condition>()
{
new Condition("categoryid", ConditionOperator.Equal, category.Id)
}
}
}
}
}
}
};
var relatedArticles = Enumerable.Empty<RelatedArticle>();
var serviceContext = this.Dependencies.GetServiceContext();
var securityProvider = this.Dependencies.GetSecurityProvider();
var urlProvider = this.Dependencies.GetUrlProvider();
// Apply Content Access Level filtering
var contentAccessProvider = new ContentAccessLevelProvider();
contentAccessProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, relatedArticlesFetch);
// Apply Product filtering
var productAccessProvider = new ProductAccessProvider();
productAccessProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, relatedArticlesFetch);
var relatedArticlesEntityCollection = relatedArticlesFetch.Execute(serviceContext as IOrganizationService);
if (relatedArticlesEntityCollection != null && relatedArticlesEntityCollection.Entities != null && relatedArticlesEntityCollection.Entities.Any())
{
relatedArticles =
relatedArticlesEntityCollection.Entities.Where(e => securityProvider.TryAssert(serviceContext, e, CrmEntityRight.Read))
.Select(e => new { Title = e.GetAttributeValue<string>("title"), Url = urlProvider.GetUrl(serviceContext, e) })
.Where(e => !(string.IsNullOrEmpty(e.Title) || string.IsNullOrEmpty(e.Url)))
.Select(e => new RelatedArticle(e.Title, e.Url))
.OrderBy(e => e.Title);
}
return relatedArticles;
}
/// <summary>
/// Gets Child Categories of a Category
/// </summary>
/// <returns>IEnumerable of Child Category</returns>
public virtual IEnumerable<ChildCategory> SelectChildCategories()
{
var childCategories = Enumerable.Empty<ChildCategory>();
var serviceContext = this.Dependencies.GetServiceContext();
var urlProvider = this.Dependencies.GetUrlProvider();
var category = this.Select();
var categoryFetch = GetCategoryFetchUnderParent(category.Id, null);
var childCategoriesEntityCollection = categoryFetch.Execute(serviceContext as IOrganizationService);
if (childCategoriesEntityCollection != null && childCategoriesEntityCollection.Entities != null && childCategoriesEntityCollection.Entities.Any())
{
childCategories =
childCategoriesEntityCollection.Entities
.Select(e => new { Title = e.GetAttributeValue<string>("title"), Url = urlProvider.GetUrl(serviceContext, e) })
.Where(e => !string.IsNullOrEmpty(e.Title))
.Select(e => new ChildCategory(e.Title, e.Url))
.OrderBy(e => e.Title);
}
return childCategories;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
public class TextOutputFormatterTests
{
public static IEnumerable<object[]> SelectResponseCharacterEncodingData
{
get
{
// string acceptEncodings, string requestEncoding, string[] supportedEncodings, string expectedEncoding
yield return new object[] { "", new string[] { "utf-8", "utf-16" }, "utf-8" };
yield return new object[] { "utf-8", new string[] { "utf-8", "utf-16" }, "utf-8" };
yield return new object[] { "utf-16", new string[] { "utf-8", "utf-16" }, "utf-16" };
yield return new object[] { "utf-16; q=0.5", new string[] { "utf-8", "utf-16" }, "utf-16" };
yield return new object[] { "utf-8; q=0.0", new string[] { "utf-8", "utf-16" }, "utf-8" };
yield return new object[] { "utf-8; q=0.0, utf-16; q=0.0", new string[] { "utf-8", "utf-16" }, "utf-8" };
yield return new object[] { "*; q=0.0", new string[] { "utf-8", "utf-16" }, "utf-8" };
}
}
[Theory]
[MemberData(nameof(SelectResponseCharacterEncodingData))]
public void SelectResponseCharacterEncoding_SelectsEncoding(
string acceptCharsetHeaders,
string[] supportedEncodings,
string expectedEncoding)
{
// Arrange
var httpContext = new Mock<HttpContext>();
var httpRequest = new DefaultHttpContext().Request;
httpRequest.Headers.AcceptCharset = acceptCharsetHeaders;
httpRequest.Headers.Accept = "application/acceptCharset";
httpContext.SetupGet(o => o.Request).Returns(httpRequest);
var formatter = new TestOutputFormatter();
foreach (string supportedEncoding in supportedEncodings)
{
formatter.SupportedEncodings.Add(Encoding.GetEncoding(supportedEncoding));
}
var context = new OutputFormatterWriteContext(
httpContext.Object,
new TestHttpResponseStreamWriterFactory().CreateWriter,
typeof(string),
"someValue")
{
ContentType = new StringSegment(httpRequest.Headers.Accept),
};
// Act
var actualEncoding = formatter.SelectCharacterEncoding(context);
// Assert
Assert.Equal(Encoding.GetEncoding(expectedEncoding), actualEncoding);
}
[Theory]
[InlineData("application/json; charset=utf-16", "application/json; charset=utf-32")]
[InlineData("application/json; charset=utf-16; format=indent", "application/json; charset=utf-32; format=indent")]
public void WriteResponse_OverridesCharset_IfDifferentFromContentTypeCharset(
string contentType,
string expectedContentType)
{
// Arrange
var formatter = new OverrideEncodingFormatter(Encoding.UTF32);
var formatterContext = new OutputFormatterWriteContext(
new DefaultHttpContext(),
new TestHttpResponseStreamWriterFactory().CreateWriter,
objectType: null,
@object: null)
{
ContentType = new StringSegment(contentType),
};
// Act
formatter.WriteAsync(formatterContext);
// Assert
Assert.Equal(new StringSegment(expectedContentType), formatterContext.ContentType);
}
[Fact]
public void WriteResponse_GetMediaTypeWithCharsetReturnsMediaTypeFromCache_IfEncodingIsUtf8()
{
// Arrange
var formatter = new TestOutputFormatter();
var formatterContext = new OutputFormatterWriteContext(
new DefaultHttpContext(),
new TestHttpResponseStreamWriterFactory().CreateWriter,
objectType: null,
@object: null)
{
ContentType = new StringSegment("application/json"),
};
formatter.SupportedMediaTypes.Add("application/json");
formatter.SupportedEncodings.Add(Encoding.UTF8);
// Act
formatter.WriteAsync(formatterContext);
var firstContentType = formatterContext.ContentType;
formatterContext.ContentType = new StringSegment("application/json");
formatter.WriteAsync(formatterContext);
var secondContentType = formatterContext.ContentType;
// Assert
Assert.Same(firstContentType.Buffer, secondContentType.Buffer);
}
[Fact]
public void WriteResponse_GetMediaTypeWithCharsetReplacesCharset_IfDifferentThanEncoding()
{
// Arrange
var formatter = new TestOutputFormatter();
var formatterContext = new OutputFormatterWriteContext(
new DefaultHttpContext(),
new TestHttpResponseStreamWriterFactory().CreateWriter,
objectType: null,
@object: null)
{
ContentType = new StringSegment("application/json; charset=utf-7"),
};
formatter.SupportedMediaTypes.Add("application/json");
formatter.SupportedEncodings.Add(Encoding.UTF8);
// Act
formatter.WriteAsync(formatterContext);
// Assert
Assert.Equal(new StringSegment("application/json; charset=utf-8"), formatterContext.ContentType);
}
[Fact]
public void WriteResponse_GetMediaTypeWithCharsetReturnsSameString_IfCharsetEqualToEncoding()
{
// Arrange
var formatter = new TestOutputFormatter();
var contentType = "application/json; charset=utf-16";
var formatterContext = new OutputFormatterWriteContext(
new DefaultHttpContext(),
new TestHttpResponseStreamWriterFactory().CreateWriter,
objectType: null,
@object: null)
{
ContentType = new StringSegment(contentType),
};
formatter.SupportedMediaTypes.Add("application/json");
formatter.SupportedEncodings.Add(Encoding.Unicode);
// Act
formatter.WriteAsync(formatterContext);
// Assert
Assert.Same(contentType, formatterContext.ContentType.Buffer);
}
[Fact]
public void WriteResponseContentHeaders_NoSupportedEncodings_NoEncodingIsSet()
{
// Arrange
var formatter = new TestOutputFormatter();
var testContentType = new StringSegment("text/json");
formatter.SupportedEncodings.Clear();
formatter.SupportedMediaTypes.Clear();
formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
var context = new OutputFormatterWriteContext(
new DefaultHttpContext(),
new TestHttpResponseStreamWriterFactory().CreateWriter,
objectType: null,
@object: null)
{
ContentType = testContentType,
};
// Act
formatter.WriteResponseHeaders(context);
// Assert
Assert.Null(MediaTypeHeaderValue.Parse(context.ContentType.Value).Encoding);
Assert.Equal(testContentType, context.ContentType);
// If we had set an encoding, it would be part of the content type header
Assert.Equal(MediaTypeHeaderValue.Parse(testContentType.Value), context.HttpContext.Response.GetTypedHeaders().ContentType);
}
[Fact]
public async Task WriteAsync_ReturnsNotAcceptable_IfSelectCharacterEncodingReturnsNull()
{
// Arrange
var formatter = new OverrideEncodingFormatter(encoding: null);
var testContentType = new StringSegment("text/json");
formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
var context = new OutputFormatterWriteContext(
new DefaultHttpContext(),
new TestHttpResponseStreamWriterFactory().CreateWriter,
objectType: null,
@object: null)
{
ContentType = testContentType,
};
// Act
await formatter.WriteAsync(context);
// Assert
Assert.Equal(StatusCodes.Status406NotAcceptable, context.HttpContext.Response.StatusCode);
}
[Fact]
public void GetAcceptCharsetHeaderValues_ReadsHeaderAndParsesValues()
{
// Arrange
const string expectedValue = "expected";
var formatter = new OverrideEncodingFormatter(encoding: null);
var context = new DefaultHttpContext();
context.Request.Headers.AcceptCharset = expectedValue;
var writerContext = new OutputFormatterWriteContext(
context,
new TestHttpResponseStreamWriterFactory().CreateWriter,
objectType: null,
@object: null);
// Act
var result = TextOutputFormatter.GetAcceptCharsetHeaderValues(writerContext);
//Assert
Assert.Equal(expectedValue, Assert.Single(result).Value.Value);
}
private class TestOutputFormatter : TextOutputFormatter
{
public TestOutputFormatter()
{
SupportedMediaTypes.Add("application/acceptCharset");
}
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
return Task.FromResult(true);
}
}
private class OverrideEncodingFormatter : TextOutputFormatter
{
private readonly Encoding _encoding;
public OverrideEncodingFormatter(Encoding encoding)
{
_encoding = encoding;
}
public override Encoding SelectCharacterEncoding(OutputFormatterWriteContext context)
{
return _encoding;
}
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
return Task.FromResult(true);
}
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Nima Ara
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.
https://github.com/NimaAra
*/
namespace commercetools.Common
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// An abstraction over <see cref="HttpClient"/> to address the following issues:
/// <para><see href="http://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/"/></para>
/// <para><see href="http://byterot.blogspot.co.uk/2016/07/singleton-httpclient-dns.html"/></para>
/// <para><see href="http://naeem.khedarun.co.uk/blog/2016/11/30/httpclient-dns-settings-for-azure-cloud-services-and-traffic-manager-1480285049222/"/></para>
/// </summary>
public sealed class RestClient
{
public HttpClient Client { get { return _client; } }
private readonly HttpClient _client;
private readonly HashSet<Uri> _endpoints;
private readonly TimeSpan _connectionCloseTimeoutPeriod;
static RestClient() => ConfigureServicePointManager();
/// <summary>
/// Creates an instance of the <see cref="RestClient"/>.
/// </summary>
public RestClient(
HttpClient httpClient = null,
IDictionary<string, string> defaultRequestHeaders = null,
TimeSpan? timeout = null,
ulong? maxResponseContentBufferSize = null)
{
if (httpClient == null)
{
httpClient = new HttpClient(new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
});
httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
}
_client = httpClient;
AddDefaultHeaders(defaultRequestHeaders);
AddRequestTimeout(timeout);
AddMaxResponseBufferSize(maxResponseContentBufferSize);
_endpoints = new HashSet<Uri>();
_connectionCloseTimeoutPeriod = TimeSpan.FromMinutes(1);
}
/// <summary>
/// Gets the headers which should be sent with each request.
/// </summary>
public IDictionary<string, string> DefaultRequestHeaders
=> _client.DefaultRequestHeaders.ToDictionary(x => x.Key, x => x.Value.First());
/// <summary>
/// Gets the time to wait before the request times out.
/// </summary>
public TimeSpan Timeout => _client.Timeout;
/// <summary>
/// Gets the maximum number of bytes to buffer when reading the response content.
/// </summary>
public uint MaxResponseContentBufferSize => (uint)_client.MaxResponseContentBufferSize;
/// <summary>
/// Gets all of the endpoints which this instance has sent a request to.
/// </summary>
public Uri[] Endpoints
{
get { lock (_endpoints) { return _endpoints.ToArray(); } }
}
/// <summary>
/// Sends the given <paramref name="request"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
=> SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
/// <summary>
/// Sends the given <paramref name="request"/> with the given <paramref name="cToken"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cToken)
=> SendAsync(request, HttpCompletionOption.ResponseContentRead, cToken);
/// <summary>
/// Sends the given <paramref name="request"/> with the given <paramref name="option"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption option)
=> SendAsync(request, option, CancellationToken.None);
/// <summary>
/// Sends the given <paramref name="request"/> with the given <paramref name="option"/> and <paramref name="cToken"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption option, CancellationToken cToken)
{
AddConnectionLeaseTimeout(request.RequestUri);
return _client.SendAsync(request, option, cToken);
}
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/>.
/// </summary>
/// <exception cref="UriFormatException"/>
/// <exception cref="ArgumentException"/>
public Task<HttpResponseMessage> GetAsync(string uri)
=> SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> GetAsync(Uri uri)
=> SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/> with the given <paramref name="cToken"/>.
/// </summary>
/// <exception cref="UriFormatException"/>
/// <exception cref="ArgumentException"/>
public Task<HttpResponseMessage> GetAsync(string uri, CancellationToken cToken)
=> SendAsync(new HttpRequestMessage(HttpMethod.Get, uri), cToken);
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/> with the given <paramref name="cToken"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> GetAsync(Uri uri, CancellationToken cToken)
=> SendAsync(new HttpRequestMessage(HttpMethod.Get, uri), cToken);
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/> with the given <paramref name="option"/>.
/// </summary>
/// <exception cref="UriFormatException"/>
/// <exception cref="ArgumentException"/>
public Task<HttpResponseMessage> GetAsync(string uri, HttpCompletionOption option)
=> SendAsync(new HttpRequestMessage(HttpMethod.Get, uri), option);
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/> with the given <paramref name="option"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> GetAsync(Uri uri, HttpCompletionOption option)
=> SendAsync(new HttpRequestMessage(HttpMethod.Get, uri), option);
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/> with the given <paramref name="option"/> and <paramref name="cToken"/>.
/// </summary>
/// <exception cref="UriFormatException"/>
/// <exception cref="ArgumentException"/>
public Task<HttpResponseMessage> GetAsync(string uri, HttpCompletionOption option, CancellationToken cToken)
=> SendAsync(new HttpRequestMessage(HttpMethod.Get, uri), option, cToken);
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/> with the given <paramref name="option"/> and <paramref name="cToken"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> GetAsync(Uri uri, HttpCompletionOption option, CancellationToken cToken)
=> SendAsync(new HttpRequestMessage(HttpMethod.Get, uri), option, cToken);
/// <summary>
/// Sends a <c>PUT</c> request with the given <paramref name="content"/> to the specified <paramref name="uri"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="UriFormatException"/>
public Task<HttpResponseMessage> PutAsync(string uri, HttpContent content)
=> SendAsync(new HttpRequestMessage(HttpMethod.Put, uri) { Content = content });
/// <summary>
/// Sends a <c>PUT</c> request with the given <paramref name="content"/> to the specified <paramref name="uri"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> PutAsync(Uri uri, HttpContent content)
=> SendAsync(new HttpRequestMessage(HttpMethod.Put, uri) { Content = content });
/// <summary>
/// Sends a <c>PUT</c> request with the given <paramref name="content"/> to the specified <paramref name="uri"/>
/// with the given <paramref name="cToken"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> PutAsync(Uri uri, HttpContent content, CancellationToken cToken)
=> SendAsync(new HttpRequestMessage(HttpMethod.Put, uri) { Content = content }, cToken);
/// <summary>
/// Sends a <c>PUT</c> request with the given <paramref name="content"/> to the specified <paramref name="uri"/>
/// with the given <paramref name="cToken"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="UriFormatException"/>
public Task<HttpResponseMessage> PutAsync(string uri, HttpContent content, CancellationToken cToken)
=> SendAsync(new HttpRequestMessage(HttpMethod.Put, uri) { Content = content }, cToken);
/// <summary>
/// Sends a <c>POST</c> request with the given <paramref name="content"/> to the specified <paramref name="uri"/>.
/// </summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="UriFormatException"/>
public Task<HttpResponseMessage> PostAsync(string uri, HttpContent content)
=> SendAsync(new HttpRequestMessage(HttpMethod.Post, uri) { Content = content });
/// <summary>
/// Sends a <c>POST</c> request with the given <paramref name="content"/> to the specified <paramref name="uri"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> PostAsync(Uri uri, HttpContent content)
=> SendAsync(new HttpRequestMessage(HttpMethod.Post, uri) { Content = content });
/// <summary>
/// Sends a <c>POST</c> request with the given <paramref name="content"/> to the specified <paramref name="uri"/>
/// with the given <paramref name="cToken"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
public Task<HttpResponseMessage> PostAsync(Uri uri, HttpContent content, CancellationToken cToken)
=> SendAsync(new HttpRequestMessage(HttpMethod.Post, uri) { Content = content }, cToken);
/// <summary>
/// Sends a <c>POST</c> request with the given <paramref name="content"/> to the specified <paramref name="uri"/>
/// with the given <paramref name="cToken"/>.
/// </summary>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="UriFormatException"/>
public Task<HttpResponseMessage> PostAsync(string uri, HttpContent content, CancellationToken cToken)
=> SendAsync(new HttpRequestMessage(HttpMethod.Post, uri) { Content = content }, cToken);
/// <summary>
/// Sends a <c>DELETE</c> request to the specified <paramref name="uri"/>.
/// </summary>
/// <exception cref="UriFormatException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="InvalidOperationException"/>
public Task<HttpResponseMessage> DeleteAsync(string uri)
=> SendAsync(new HttpRequestMessage(HttpMethod.Delete, uri));
/// <summary>
/// Sends a <c>DELETE</c> request to the specified <paramref name="uri"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="InvalidOperationException"/>
public Task<HttpResponseMessage> DeleteAsync(Uri uri)
=> SendAsync(new HttpRequestMessage(HttpMethod.Delete, uri));
/// <summary>
/// Sends a <c>DELETE</c> request to the specified <paramref name="uri"/> with the given <paramref name="cToken"/>.
/// </summary>
/// <exception cref="UriFormatException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="InvalidOperationException"/>
public Task<HttpResponseMessage> DeleteAsync(string uri, CancellationToken cToken)
=> SendAsync(new HttpRequestMessage(HttpMethod.Delete, uri), cToken);
/// <summary>
/// Sends a <c>DELETE</c> request to the specified <paramref name="uri"/> with the given <paramref name="cToken"/>.
/// </summary>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="InvalidOperationException"/>
public Task<HttpResponseMessage> DeleteAsync(Uri uri, CancellationToken cToken)
=> SendAsync(new HttpRequestMessage(HttpMethod.Delete, uri), cToken);
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/>.
/// </summary>
/// <exception cref="ArgumentException"/>
///<exception cref="UriFormatException"/>
public Task<string> GetStringAsync(string uri)
{
return GetStringAsync(new Uri(uri, UriKind.RelativeOrAbsolute));
}
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/>.
/// </summary>
///<exception cref="ArgumentNullException"/>
public Task<string> GetStringAsync(Uri uri)
{
AddConnectionLeaseTimeout(uri);
return _client.GetStringAsync(uri);
}
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/>.
/// </summary>
/// <exception cref="ArgumentException"/>
///<exception cref="UriFormatException"/>
public Task<Stream> GetStreamAsync(string uri)
{
return GetStreamAsync(new Uri(uri, UriKind.RelativeOrAbsolute));
}
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/>.
/// </summary>
///<exception cref="ArgumentNullException"/>
public Task<Stream> GetStreamAsync(Uri uri)
{
AddConnectionLeaseTimeout(uri);
return _client.GetStreamAsync(uri);
}
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/>.
/// </summary>
///<exception cref="UriFormatException"/>
/// <exception cref="ArgumentException"/>
public Task<byte[]> GetByteArrayAsync(string uri)
{
return GetByteArrayAsync(new Uri(uri, UriKind.RelativeOrAbsolute));
}
/// <summary>
/// Sends a <c>GET</c> request to the specified <paramref name="uri"/>.
/// </summary>
///<exception cref="ArgumentNullException"/>
public Task<byte[]> GetByteArrayAsync(Uri uri)
{
AddConnectionLeaseTimeout(uri);
return _client.GetByteArrayAsync(uri);
}
/// <summary>
/// Clears all of the endpoints which this instance has sent a request to.
/// </summary>
public void ClearEndpoints()
{
lock (_endpoints) { _endpoints.Clear(); }
}
/// <summary>
/// Cancels all pending requests on this instance.
/// </summary>
public void CancelPendingRequests() => _client.CancelPendingRequests();
/// <summary>
/// Releases the unmanaged resources and disposes of the managed resources used by the <see cref="HttpClient"/>.
/// </summary>
public void Dispose()
{
_client.Dispose();
lock (_endpoints) { _endpoints.Clear(); }
}
private static void ConfigureServicePointManager()
{
// Default is 2 minutes, see https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.dnsrefreshtimeout(v=vs.110).aspx
ServicePointManager.DnsRefreshTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
// Increases the concurrent outbound connections
ServicePointManager.DefaultConnectionLimit = 1024;
}
private void AddDefaultHeaders(IDictionary<string, string> headers)
{
if (headers == null) { return; }
foreach (var item in headers)
{
_client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
private void AddRequestTimeout(TimeSpan? timeout)
{
if (!timeout.HasValue) { return; }
_client.Timeout = timeout.Value;
}
private void AddMaxResponseBufferSize(ulong? size)
{
if (!size.HasValue) { return; }
_client.MaxResponseContentBufferSize = (long)size.Value;
}
private void AddConnectionLeaseTimeout(Uri endpoint)
{
lock (_endpoints)
{
if (_endpoints.Contains(endpoint)) { return; }
ServicePointManager.FindServicePoint(endpoint)
.ConnectionLeaseTimeout = (int)_connectionCloseTimeoutPeriod.TotalMilliseconds;
_endpoints.Add(endpoint);
}
}
}
}
| |
//Copyright (C) 2006 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the MaxentResolver.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using SharpEntropy.IO;
namespace OpenNLP.Tools.Coreference.Resolver
{
/// <summary>
/// Provides common functionality used by classes which implement the {@link IResolver} interface
/// and use maximum entropy models to make resolution decisions.
/// </summary>
public abstract class MaximumEntropyResolver : AbstractResolver
{
/// <summary>
/// Outcomes when two mentions are coreferent.
/// </summary>
public const string Same = "same";
/// <summary>
/// Outcome when two mentions are not coreferent.
/// </summary>
public const string Diff = "diff";
/// <summary>
/// Default feature value.
/// </summary>
public const string Default = "default";
private static readonly Regex EndsWithPeriod = new Regex("\\.$", RegexOptions.Compiled);
private const double MinimumSimilarityProbability = 0.60;
private const string SimilarityCompatible = "sim.compatible";
private const string SimilarityIncompatible = "sim.incompatible";
private const string SimilarityUnknown = "sim.unknown";
private const string NumberCompatible = "num.compatible";
private const string NumberIncompatible = "num.incompatible";
private const string NumberUnknown = "num.unknown";
private const string GenderCompatible = "gen.compatible";
private const string GenderIncompatible = "gen.incompatible";
private const string GenderUnknown = "gen.unknown";
private const bool DebugOn = false;
private readonly string _modelName;
private readonly SharpEntropy.IMaximumEntropyModel _model;
private readonly double[] _candidateProbabilities;
private readonly int _sameIndex;
private readonly ResolverMode _resolverMode;
private readonly List<SharpEntropy.TrainingEvent> _events;
private const string ModelExtension = ".nbin";
public static Similarity.ITestSimilarityModel SimilarityModel { get; set; }
/// <summary>
/// When true, this designates that the resolver should use the first referent encountered which it
/// more preferable than non-reference. When false, all non-excluded referents within this resolver's range
/// are considered.
/// </summary>
protected internal bool PreferFirstReferent { get; set; }
/// <summary>
/// When true, this designates that training should consist of a single positive and a single negative example
/// (when possible) for each mention.
/// </summary>
protected internal bool PairedSampleSelection { get; set; }
/// <summary>
/// When true, this designates that the same maximum entropy model should be used non-reference
/// events (the pairing of a mention and the "null" reference) as is used for potentially
/// referential pairs. When false a seperate model is created for these events.
/// </summary>
protected internal bool UseSameModelForNonRef { get; set; }
/// <summary>
/// The model for computing non-referential probabilities.
/// </summary>
protected internal INonReferentialResolver NonReferentialResolver { get; set; }
/// <summary>
/// Creates a maximum-entropy-based resolver which will look the specified number of entities back
/// for a referent.
/// This constructor is only used for unit testing.
/// </summary>
/// <param name="numberOfEntitiesBack">
/// </param>
/// <param name="preferFirstReferent">
/// </param>
protected MaximumEntropyResolver(int numberOfEntitiesBack, bool preferFirstReferent) : base(numberOfEntitiesBack)
{
PreferFirstReferent = preferFirstReferent;
}
/// <summary>
/// Creates a maximum-entropy-based resolver with the specified model name, using the
/// specified mode, which will look the specified number of entities back for a referent and
/// prefer the first referent if specified.
/// </summary>
/// <param name="modelDirectory">
/// The name of the directory where the resover models are stored.
/// </param>
/// <param name="name">
/// The name of the file where this model will be read or written.
/// </param>
/// <param name="mode">
/// The mode this resolver is being using in (training, testing).
/// </param>
/// <param name="numberOfEntitiesBack">
/// The number of entities back in the text that this resolver will look
/// for a referent.
/// </param>
/// <param name="preferFirstReferent">
/// Set to true if the resolver should prefer the first referent which is more
/// likly than non-reference. This only affects testing.
/// </param>
/// <param name="nonReferentialResolver">
/// Determines how likly it is that this entity is non-referential.
/// </param>
protected MaximumEntropyResolver(string modelDirectory, string name, ResolverMode mode, int numberOfEntitiesBack, bool preferFirstReferent,
INonReferentialResolver nonReferentialResolver): base(numberOfEntitiesBack)
{
PreferFirstReferent = preferFirstReferent;
NonReferentialResolver = nonReferentialResolver;
_resolverMode = mode;
_modelName = modelDirectory + "/" + name;
if (_resolverMode == ResolverMode.Test)
{
_model = new SharpEntropy.GisModel(new BinaryGisModelReader(_modelName + ModelExtension));
_sameIndex = _model.GetOutcomeIndex(Same);
}
else if (_resolverMode == ResolverMode.Train)
{
_events = new List<SharpEntropy.TrainingEvent>();
}
else
{
Console.Error.WriteLine("Unknown mode: " + _resolverMode);
}
//add one for non-referent possibility
_candidateProbabilities = new double[GetNumberEntitiesBack() + 1];
}
/// <summary>
/// Creates a maximum-entropy-based resolver with the specified model name, using the
/// specified mode, which will look the specified number of entities back for a referent.
/// </summary>
/// <param name="modelDirectory">
/// The name of the directory where the resolver models are stored.
/// </param>
/// <param name="modelName">
/// The name of the file where this model will be read or written.
/// </param>
/// <param name="mode">
/// The mode this resolver is being using in (training, testing).
/// </param>
/// <param name="numberEntitiesBack">
/// The number of entities back in the text that this resolver will look
/// for a referent.
/// </param>
protected MaximumEntropyResolver(string modelDirectory, string modelName, ResolverMode mode, int numberEntitiesBack):
this(modelDirectory, modelName, mode, numberEntitiesBack, false){}
protected MaximumEntropyResolver(string modelDirectory, string modelName, ResolverMode mode, int numberEntitiesBack, INonReferentialResolver nonReferentialResolver):
this(modelDirectory, modelName, mode, numberEntitiesBack, false, nonReferentialResolver){}
protected MaximumEntropyResolver(string modelDirectory, string modelName, ResolverMode mode, int numberEntitiesBack, bool preferFirstReferent):
this(modelDirectory, modelName, mode, numberEntitiesBack, preferFirstReferent, new DefaultNonReferentialResolver(modelDirectory, modelName, mode)){}
protected MaximumEntropyResolver(string modelDirectory, string modelName, ResolverMode mode, int numberEntitiesBack, bool preferFirstReferent, double nonReferentialProbability):
this(modelDirectory, modelName, mode, numberEntitiesBack, preferFirstReferent, new FixedNonReferentialResolver(nonReferentialProbability)){}
public override DiscourseEntity Resolve(Mention.MentionContext expression, DiscourseModel discourseModel)
{
DiscourseEntity discourseEntity;
int entityIndex = 0;
double nonReferentialProbability = NonReferentialResolver.GetNonReferentialProbability(expression);
if (DebugOn)
{
System.Console.Error.WriteLine(this.ToString() + ".resolve: " + expression.ToText() + " -> " + "null " + nonReferentialProbability);
}
for (; entityIndex < GetNumberEntitiesBack(discourseModel); entityIndex++)
{
discourseEntity = discourseModel.GetEntity(entityIndex);
if (IsOutOfRange(expression, discourseEntity))
{
break;
}
if (IsExcluded(expression, discourseEntity))
{
_candidateProbabilities[entityIndex] = 0;
if (DebugOn)
{
Console.Error.WriteLine("excluded " + this.ToString() + ".resolve: " + expression.ToText() + " -> " + discourseEntity + " " + _candidateProbabilities[entityIndex]);
}
}
else
{
string[] features = GetFeatures(expression, discourseEntity).ToArray();
try
{
_candidateProbabilities[entityIndex] = _model.Evaluate(features)[_sameIndex];
}
catch (IndexOutOfRangeException)
{
_candidateProbabilities[entityIndex] = 0;
}
if (DebugOn)
{
Console.Error.WriteLine(this + ".resolve: " + expression.ToText() + " -> " + discourseEntity + " (" + expression.GetGender() + "," + discourseEntity.Gender + ") " + _candidateProbabilities[entityIndex] + " " + string.Join(",", features)); //SupportClass.CollectionToString(lfeatures));
}
}
if (PreferFirstReferent && _candidateProbabilities[entityIndex] > nonReferentialProbability)
{
entityIndex++; //update for nonRef assignment
break;
}
}
_candidateProbabilities[entityIndex] = nonReferentialProbability;
// find max
int maximumCandidateIndex = 0;
for (int currentCandidate = 1; currentCandidate <= entityIndex; currentCandidate++)
{
if (_candidateProbabilities[currentCandidate] > _candidateProbabilities[maximumCandidateIndex])
{
maximumCandidateIndex = currentCandidate;
}
}
if (maximumCandidateIndex == entityIndex)
{
// no referent
return null;
}
else
{
discourseEntity = discourseModel.GetEntity(maximumCandidateIndex);
return discourseEntity;
}
}
/*
protected double getNonReferentialProbability(MentionContext ec) {
if (useFixedNonReferentialProbability) {
return fixedNonReferentialProbability;
}
List lfeatures = getFeatures(ec, null);
string[] features = (string[]) lfeatures.toArray(new string[lfeatures.size()]);
double[] dist = nrModel.eval(features);
return (dist[nrSameIndex]);
}
*/
/// <summary>
/// Returns whether the specified entity satisfies the criteria for being a default referent.
/// This criteria is used to perform sample selection on the training data and to select a single
/// non-referent entity. Typically the criteria is a hueristic for a likely referent.
/// </summary>
/// <param name="discourseEntity">
/// The discourse entity being considered for non-reference.
/// </param>
/// <returns>
/// True if the entity should be used as a default referent, false otherwise.
/// </returns>
protected internal virtual bool defaultReferent(DiscourseEntity discourseEntity)
{
Mention.MentionContext entityContext = discourseEntity.LastExtent;
if (entityContext.NounPhraseSentenceIndex == 0)
{
return true;
}
return false;
}
public override DiscourseEntity Retain(Mention.MentionContext mention, DiscourseModel discourseModel)
{
if (_resolverMode == ResolverMode.Train)
{
DiscourseEntity discourseEntity = null;
bool referentFound = false;
bool hasReferentialCandidate = false;
bool nonReferentFound = false;
for (int entityIndex = 0; entityIndex < GetNumberEntitiesBack(discourseModel); entityIndex++)
{
DiscourseEntity currentDiscourseEntity = discourseModel.GetEntity(entityIndex);
Mention.MentionContext entityMention = currentDiscourseEntity.LastExtent;
if (IsOutOfRange(mention, currentDiscourseEntity))
{
break;
}
if (IsExcluded(mention, currentDiscourseEntity))
{
if (ShowExclusions)
{
if (mention.Id != - 1 && entityMention.Id == mention.Id)
{
System.Console.Error.WriteLine(this + ".retain: Referent excluded: (" + mention.Id + ") " + mention.ToText() + " " + mention.IndexSpan + " -> (" + entityMention.Id + ") " + entityMention.ToText() + " " + entityMention.Span + " " + this);
}
}
}
else
{
hasReferentialCandidate = true;
bool useAsDifferentExample = defaultReferent(currentDiscourseEntity);
//if (!sampleSelection || (mention.getId() != -1 && entityMention.getId() == mention.getId()) || (!nonReferentFound && useAsDifferentExample)) {
List<string> features = GetFeatures(mention, currentDiscourseEntity);
//add Event to Model
if (DebugOn)
{
Console.Error.WriteLine(this + ".retain: " + mention.Id + " " + mention.ToText() + " -> " + entityMention.Id + " " + currentDiscourseEntity);
}
if (mention.Id != - 1 && entityMention.Id == mention.Id)
{
referentFound = true;
_events.Add(new SharpEntropy.TrainingEvent(Same, features.ToArray()));
discourseEntity = currentDiscourseEntity;
Distances.Add(entityIndex);
}
else if (!PairedSampleSelection || (!nonReferentFound && useAsDifferentExample))
{
nonReferentFound = true;
_events.Add(new SharpEntropy.TrainingEvent(Diff, features.ToArray()));
}
//}
}
if (PairedSampleSelection && referentFound && nonReferentFound)
{
break;
}
if (PreferFirstReferent && referentFound)
{
break;
}
}
// doesn't refer to anything
if (hasReferentialCandidate)
{
NonReferentialResolver.AddEvent(mention);
}
return discourseEntity;
}
else
{
return base.Retain(mention, discourseModel);
}
}
protected internal virtual string GetMentionCountFeature(DiscourseEntity discourseEntity)
{
if (discourseEntity.MentionCount >= 5)
{
return ("mc=5+");
}
else
{
return ("mc=" + discourseEntity.MentionCount);
}
}
/// <summary>
/// Returns a list of features for deciding whether the specified mention refers to the specified discourse entity.
/// </summary>
/// <param name="mention">
/// the mention being considers as possibly referential.
/// </param>
/// <param name="entity">
/// The discourse entity with which the mention is being considered referential.
/// </param>
/// <returns>
/// a list of features used to predict reference between the specified mention and entity.
/// </returns>
protected internal virtual List<string> GetFeatures(Mention.MentionContext mention, DiscourseEntity entity)
{
List<string> features = new List<string>();
features.Add(Default);
features.AddRange(GetCompatibilityFeatures(mention, entity));
return features;
}
public override void Train()
{
if (_resolverMode == ResolverMode.Train)
{
if (DebugOn)
{
System.Console.Error.WriteLine(this.ToString() + " referential");
using (var writer = new System.IO.StreamWriter(_modelName + ".events", false, System.Text.Encoding.Default))
{
foreach (SharpEntropy.TrainingEvent e in _events)
{
writer.Write(e.ToString() + "\n");
}
writer.Close();
}
}
var trainer = new SharpEntropy.GisTrainer();
trainer.TrainModel(new Util.CollectionEventReader(_events), 100, 10);
new BinaryGisModelWriter().Persist(new SharpEntropy.GisModel(trainer), _modelName + ModelExtension);
NonReferentialResolver.Train();
}
}
private string GetSemanticCompatibilityFeature(Mention.MentionContext entityContext, DiscourseEntity discourseEntity)
{
if (SimilarityModel != null)
{
double best = 0;
foreach (Mention.MentionContext checkEntityContext in discourseEntity.Mentions)
{
double sim = SimilarityModel.AreCompatible(entityContext, checkEntityContext);
if (DebugOn)
{
Console.Error.WriteLine("MaxentResolver.GetSemanticCompatibilityFeature: sem-compat " + sim + " " + entityContext.ToText() + " " + checkEntityContext.ToText());
}
if (sim > best)
{
best = sim;
}
}
if (best > MinimumSimilarityProbability)
{
return SimilarityCompatible;
}
else if (best > (1 - MinimumSimilarityProbability))
{
return SimilarityUnknown;
}
else
{
return SimilarityIncompatible;
}
}
else
{
Console.Error.WriteLine("MaxentResolver: Uninitialized Semantic Model");
return SimilarityUnknown;
}
}
private string GetGenderCompatibilityFeature(Mention.MentionContext entityContext, DiscourseEntity discourseEntity)
{
Similarity.GenderEnum entityGender = discourseEntity.Gender;
if (entityGender == Similarity.GenderEnum.Unknown || entityContext.GetGender() == Similarity.GenderEnum.Unknown)
{
return GenderUnknown;
}
else if (entityContext.GetGender() == entityGender)
{
return GenderCompatible;
}
else
{
return GenderIncompatible;
}
}
private string GetNumberCompatibilityFeature(Mention.MentionContext entityContext, DiscourseEntity discourseEntity)
{
Similarity.NumberEnum entityNumber = discourseEntity.Number;
if (entityNumber == Similarity.NumberEnum.Unknown || entityContext.GetNumber() == Similarity.NumberEnum.Unknown)
{
return NumberUnknown;
}
else if (entityContext.GetNumber() == entityNumber)
{
return NumberCompatible;
}
else
{
return NumberIncompatible;
}
}
/// <summary>
/// Returns features indicating whether the specified mention and the specified entity are compatible.
/// </summary>
/// <param name="mention">
/// The mention.
/// </param>
/// <param name="entity">
/// The entity.
/// </param>
/// <returns>
/// list of features indicating whether the specified mention and the specified entity are compatible.
/// </returns>
private IEnumerable<string> GetCompatibilityFeatures(Mention.MentionContext mention, DiscourseEntity entity)
{
var compatibilityFeatures = new List<string>();
string semanticCompatibilityFeature = GetSemanticCompatibilityFeature(mention, entity);
compatibilityFeatures.Add(semanticCompatibilityFeature);
string genderCompatibilityFeature = GetGenderCompatibilityFeature(mention, entity);
compatibilityFeatures.Add(genderCompatibilityFeature);
string numberCompatibilityFeature = GetNumberCompatibilityFeature(mention, entity);
compatibilityFeatures.Add(numberCompatibilityFeature);
if (semanticCompatibilityFeature == SimilarityCompatible && genderCompatibilityFeature == GenderCompatible && numberCompatibilityFeature == NumberCompatible)
{
compatibilityFeatures.Add("all.compatible");
}
else if (semanticCompatibilityFeature == SimilarityIncompatible || genderCompatibilityFeature == GenderIncompatible || numberCompatibilityFeature == NumberIncompatible)
{
compatibilityFeatures.Add("some.incompatible");
}
return compatibilityFeatures;
}
/// <summary>
/// Returns a list of features based on the surrounding context of the specified mention.
/// </summary>
/// <param name="mention">
/// the mention whose surround context the features model.
/// </param>
/// <returns>
/// a list of features based on the surrounding context of the specified mention
/// </returns>
public static List<string> GetContextFeatures(Mention.MentionContext mention)
{
var features = new List<string>();
if (mention.PreviousToken != null)
{
features.Add("pt=" + mention.PreviousToken.SyntacticType);
features.Add("pw=" + mention.PreviousToken);
}
else
{
features.Add("pt=BOS");
features.Add("pw=BOS");
}
if (mention.NextToken != null)
{
features.Add("nt=" + mention.NextToken.SyntacticType);
features.Add("nw=" + mention.NextToken);
}
else
{
features.Add("nt=EOS");
features.Add("nw=EOS");
}
if (mention.NextTokenBasal != null)
{
features.Add("bnt=" + mention.NextTokenBasal.SyntacticType);
features.Add("bnw=" + mention.NextTokenBasal);
}
else
{
features.Add("bnt=EOS");
features.Add("bnw=EOS");
}
return features;
}
private Util.Set<string> ConstructModifierSet(Mention.IParse[] tokens, int headIndex)
{
Util.Set<string> modifierSet = new Util.HashSet<string>();
for (int tokenIndex = 0; tokenIndex < headIndex; tokenIndex++)
{
Mention.IParse token = tokens[tokenIndex];
modifierSet.Add(token.ToString().ToLower());
}
return modifierSet;
}
/// <summary>
/// Returns whether the specified token is a definite article.</summary>
/// <param name="token">
/// The token.
/// </param>
/// <param name="tag">
/// The pos-tag for the specified token.
/// </param>
/// <returns>
/// whether the specified token is a definite article.
/// </returns>
protected internal virtual bool IsDefiniteArticle(string token, string tag)
{
token = token.ToLower();
if (token == "the" || token == "these" || token == "these" || tag == PartsOfSpeech.PossessivePronoun)
{
return true;
}
return false;
}
private bool IsSubstring(string mentionStrip, string entityMentionStrip)
{
int index = entityMentionStrip.IndexOf(mentionStrip);
if (index != - 1)
{
//check boundries
if (index != 0 && entityMentionStrip[index - 1] != ' ')
{
return false;
}
int end = index + mentionStrip.Length;
if (end != entityMentionStrip.Length && entityMentionStrip[end] != ' ')
{
return false;
}
return true;
}
return false;
}
protected internal override bool IsExcluded(Mention.MentionContext entityContext, DiscourseEntity discourseEntity)
{
if (base.IsExcluded(entityContext, discourseEntity))
{
return true;
}
return false;
/*
else {
if (GEN_INCOMPATIBLE == getGenderCompatibilityFeature(ec,de)) {
return true;
}
else if (NUM_INCOMPATIBLE == getNumberCompatibilityFeature(ec,de)) {
return true;
}
else if (SIM_INCOMPATIBLE == getSemanticCompatibilityFeature(ec,de)) {
return true;
}
return false;
}
*/
}
/// <summary>
/// Returns distance features for the specified mention and entity.
/// </summary>
/// <param name="mention">
/// The mention.
/// </param>
/// <param name="entity">
/// The entity.
/// </param>
/// <returns>
/// list of distance features for the specified mention and entity.
/// </returns>
protected internal virtual List<string> GetDistanceFeatures(Mention.MentionContext mention, DiscourseEntity entity)
{
var features = new List<string>();
Mention.MentionContext currentEntityContext = entity.LastExtent;
int entityDistance = mention.NounPhraseDocumentIndex - currentEntityContext.NounPhraseDocumentIndex;
int sentenceDistance = mention.SentenceNumber - currentEntityContext.SentenceNumber;
int hobbsEntityDistance;
if (sentenceDistance == 0)
{
hobbsEntityDistance = currentEntityContext.NounPhraseSentenceIndex;
}
else
{
//hobbsEntityDistance = entityDistance - (entities within sentence from mention to end) + (entities within sentence form start to mention)
//hobbsEntityDistance = entityDistance - (cec.maxNounLocation - cec.getNounPhraseSentenceIndex) + cec.getNounPhraseSentenceIndex;
hobbsEntityDistance = entityDistance + (2 * currentEntityContext.NounPhraseSentenceIndex) - currentEntityContext.MaxNounPhraseSentenceIndex;
}
features.Add("hd=" + hobbsEntityDistance);
features.Add("de=" + entityDistance);
features.Add("ds=" + sentenceDistance);
//features.add("ds=" + sdist + pronoun);
//features.add("dn=" + cec.sentenceNumber);
//features.add("ep=" + cec.nounLocation);
return features;
}
private Dictionary<string, string> GetPronounFeatureMap(string pronoun)
{
var pronounMap = new Dictionary<string, string>();
if (Linker.MalePronounPattern.IsMatch(pronoun))
{
pronounMap["gender"] = "male";
}
else if (Linker.FemalePronounPattern.IsMatch(pronoun))
{
pronounMap["gender"] = "female";
}
else if (Linker.NeuterPronounPattern.IsMatch(pronoun))
{
pronounMap["gender"] = "neuter";
}
if (Linker.SingularPronounPattern.IsMatch(pronoun))
{
pronounMap["number"] = "singular";
}
else if (Linker.PluralPronounPattern.IsMatch(pronoun))
{
pronounMap["number"] = "plural";
}
/*
if (Linker.firstPersonPronounPattern.matcher(pronoun).matches()) {
pronounMap.put("person","first");
}
else if (Linker.secondPersonPronounPattern.matcher(pronoun).matches()) {
pronounMap.put("person","second");
}
else if (Linker.thirdPersonPronounPattern.matcher(pronoun).matches()) {
pronounMap.put("person","third");
}
*/
return pronounMap;
}
/// <summary>
/// Returns features indicating whether the specified mention is compatible with the pronouns
/// of the specified entity.
/// </summary>
/// <param name="mention">
/// The mention.
/// </param>
/// <param name="entity">
/// The entity.
/// </param>
/// <returns>
/// list of features indicating whether the specified mention is compatible with the pronouns
/// of the specified entity.
/// </returns>
protected internal virtual List<string> GetPronounMatchFeatures(Mention.MentionContext mention, DiscourseEntity entity)
{
bool foundCompatiblePronoun = false;
bool foundIncompatiblePronoun = false;
if (PartsOfSpeech.IsPersOrPossPronoun(mention.HeadTokenTag))
{
Dictionary<string, string> pronounMap = GetPronounFeatureMap(mention.HeadTokenText);
foreach (Mention.MentionContext candidateMention in entity.Mentions)
{
if (PartsOfSpeech.IsPersOrPossPronoun(candidateMention.HeadTokenTag))
{
if (mention.HeadTokenText.ToUpper() == candidateMention.HeadTokenText.ToUpper())
{
foundCompatiblePronoun = true;
break;
}
else
{
Dictionary<string, string> candidatePronounMap = GetPronounFeatureMap(candidateMention.HeadTokenText);
bool allKeysMatch = true;
foreach (string key in pronounMap.Keys)
{
if (candidatePronounMap.ContainsKey(key))
{
if (pronounMap[key] != candidatePronounMap[key])
{
foundIncompatiblePronoun = true;
allKeysMatch = false;
}
}
else
{
allKeysMatch = false;
}
}
if (allKeysMatch)
{
foundCompatiblePronoun = true;
}
}
}
}
}
var pronounFeatures = new List<string>();
if (foundCompatiblePronoun)
{
pronounFeatures.Add("compatiblePronoun");
}
if (foundIncompatiblePronoun)
{
pronounFeatures.Add("incompatiblePronoun");
}
return pronounFeatures;
}
/// <summary>
/// Returns string-match features for the the specified mention and entity.</summary>
/// <param name="mention">
/// The mention.
/// </param>
/// <param name="entity">
/// The entity.
/// </param>
/// <returns>
/// list of string-match features for the the specified mention and entity.
/// </returns>
protected internal virtual List<string> GetStringMatchFeatures(Mention.MentionContext mention, DiscourseEntity entity)
{
bool sameHead = false;
bool modifersMatch = false;
bool titleMatch = false;
bool noTheModifiersMatch = false;
var features = new List<string>();
Mention.IParse[] mentionTokens = mention.TokenParses;
var entityContextModifierSet = ConstructModifierSet(mentionTokens, mention.HeadTokenIndex);
string mentionHeadString = mention.HeadTokenText.ToLower();
Util.Set<string> featureSet = new Util.HashSet<string>();
foreach (Mention.MentionContext entityMention in entity.Mentions)
{
string exactMatchFeature = GetExactMatchFeature(entityMention, mention);
if (exactMatchFeature != null)
{
featureSet.Add(exactMatchFeature);
}
else if (entityMention.Parse.IsCoordinatedNounPhrase && !mention.Parse.IsCoordinatedNounPhrase)
{
featureSet.Add("cmix");
}
else
{
string mentionStrip = StripNounPhrase(mention);
string entityMentionStrip = StripNounPhrase(entityMention);
if (mentionStrip != null && entityMentionStrip != null)
{
if (IsSubstring(mentionStrip, entityMentionStrip))
{
featureSet.Add("substring");
}
}
}
Mention.IParse[] entityMentionTokens = entityMention.TokenParses;
int headIndex = entityMention.HeadTokenIndex;
//if (!mention.getHeadTokenTag().equals(entityMention.getHeadTokenTag())) {
// continue;
//} want to match NN NNP
string entityMentionHeadString = entityMention.HeadTokenText.ToLower();
// model lexical similarity
if (mentionHeadString == entityMentionHeadString)
{
sameHead = true;
featureSet.Add("hds=" + mentionHeadString);
if (!modifersMatch || !noTheModifiersMatch)
{
//only check if we haven't already found one which is the same
modifersMatch = true;
noTheModifiersMatch = true;
Util.Set<string> entityMentionModifierSet = ConstructModifierSet(entityMentionTokens, headIndex);
foreach (string modifierWord in entityContextModifierSet)
{
if (!entityMentionModifierSet.Contains(modifierWord))
{
modifersMatch = false;
if (modifierWord != "the")
{
noTheModifiersMatch = false;
featureSet.Add("mmw=" + modifierWord);
}
}
}
}
}
Util.Set<string> descriptorModifierSet = ConstructModifierSet(entityMentionTokens, entityMention.NonDescriptorStart);
if (descriptorModifierSet.Contains(mentionHeadString))
{
titleMatch = true;
}
}
if (featureSet.Count != 0)
{
features.AddRange(featureSet);
}
if (sameHead)
{
features.Add("sameHead");
if (modifersMatch)
{
features.Add("modsMatch");
}
else if (noTheModifiersMatch)
{
features.Add("nonTheModsMatch");
}
else
{
features.Add("modsMisMatch");
}
}
if (titleMatch)
{
features.Add("titleMatch");
}
return features;
}
private string MentionString(Mention.MentionContext entityContext)
{
var output = new StringBuilder();
object[] mentionTokens = entityContext.Tokens;
output.Append(mentionTokens[0].ToString());
for (int tokenIndex = 1; tokenIndex < mentionTokens.Length; tokenIndex++)
{
string token = mentionTokens[tokenIndex].ToString();
output.Append(" ").Append(token);
}
return output.ToString();
}
private string ExcludedTheMentionString(Mention.MentionContext entityContext)
{
var output = new StringBuilder();
bool first = true;
object[] mentionTokens = entityContext.Tokens;
foreach (object tokenObj in mentionTokens)
{
string token = tokenObj.ToString();
if (token != "the" && token != "The" && token != "THE")
{
if (!first)
{
output.Append(" ");
}
output.Append(token);
first = false;
}
}
return output.ToString();
}
private string ExcludedHonorificMentionString(Mention.MentionContext entityContext)
{
var output = new System.Text.StringBuilder();
bool first = true;
object[] mentionTokens = entityContext.Tokens;
for (int tokenIndex = 0; tokenIndex < mentionTokens.Length; tokenIndex++)
{
string token = mentionTokens[tokenIndex].ToString();
if (Linker.HonorificsPattern.Match(token).Value != token)
{
if (!first)
{
output.Append(" ");
}
output.Append(token);
first = false;
}
}
return output.ToString();
}
private string ExcludedDeterminerMentionString(Mention.MentionContext entityContext)
{
var output = new StringBuilder();
bool first = true;
Mention.IParse[] mentionTokenParses = entityContext.TokenParses;
for (int tokenIndex = 0; tokenIndex < mentionTokenParses.Length; tokenIndex++)
{
Mention.IParse token = mentionTokenParses[tokenIndex];
string tag = token.SyntacticType;
if (tag != PartsOfSpeech.Determiner)
{
if (!first)
{
output.Append(" ");
}
output.Append(token.ToString());
first = false;
}
}
return output.ToString();
}
private string GetExactMatchFeature(Mention.MentionContext entityContext, Mention.MentionContext compareContext)
{
if (MentionString(entityContext).Equals(MentionString(compareContext)))
{
return "exactMatch";
}
else if (ExcludedHonorificMentionString(entityContext).Equals(ExcludedHonorificMentionString(compareContext)))
{
return "exactMatchNoHonor";
}
else if (ExcludedTheMentionString(entityContext).Equals(ExcludedTheMentionString(compareContext)))
{
return "exactMatchNoThe";
}
else if (ExcludedDeterminerMentionString(entityContext).Equals(ExcludedDeterminerMentionString(compareContext)))
{
return "exactMatchNoDT";
}
return null;
}
/// <summary>
/// Returns a list of word features for the specified tokens.
/// </summary>
/// <param name="token">
/// The token for which features are to be computed.
/// </param>
/// <returns>
/// a list of word features for the specified tokens.
/// </returns>
public static List<string> GetWordFeatures(Mention.IParse token)
{
var wordFeatures = new List<string>();
string word = token.ToString().ToLower();
string wordFeature = string.Empty;
if (EndsWithPeriod.IsMatch(word))
{
wordFeature = @",endWithPeriod";
}
string tokenTag = token.SyntacticType;
wordFeatures.Add("w=" + word + ",t=" + tokenTag + wordFeature);
wordFeatures.Add("t=" + tokenTag + wordFeature);
return wordFeatures;
}
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;
public class DebugConsole : MonoBehaviour
{
private static Color backgroundColor = new Color(50f/255f, 50f/255f, 50f/255f, 100f/255f);
public static int maxNumberOfMessages = 50;
private static DebugConsole m_instance;
private GameObject canvas;
private GameObject scrollView;
private GameObject scrollViewContent;
private RectTransform scrollViewContentRectTransform;
public delegate void ButtonDelegate();
public ButtonDelegate ScreenshotButtonCallback;
public ButtonDelegate SaveLogButtonCallback;
public ButtonDelegate ClearLogButtonCallback;
public static DebugConsole instance
{
get
{
if (m_instance == null)
{
GameObject go = new GameObject("DebugConsole");
DontDestroyOnLoad(go);
m_instance = go.AddComponent<DebugConsole>();
m_instance.InitGui();
}
return m_instance;
}
}
void Awake()
{
if (m_instance == null)
{
m_instance = this;
}
else
{
DebugConsole[] consoles = GameObject.FindObjectsOfType<DebugConsole>();
for (int i = 0; i < consoles.Length; i++)
{
if (consoles[i] != m_instance)
Destroy(consoles[i].gameObject);
}
}
}
void InitGui()
{
CreateEventSystem();
CreateGUI();
MakeButtons();
DebugConsole.instance.isVisible = false;
}
void CreateEventSystem()
{
EventSystem eventSystem = GameObject.FindObjectOfType<EventSystem>();
if (eventSystem == null)
{
GameObject go = new GameObject("EventSystem");
DontDestroyOnLoad(go);
go.AddComponent<EventSystem>();
go.AddComponent<StandaloneInputModule>();
}
}
void CreateGUI()
{
//make canvas
canvas = new GameObject("DebugConsoleCanvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
Canvas c = canvas.GetComponent<Canvas>();
c.renderMode = RenderMode.ScreenSpaceOverlay;
CanvasScaler scaler = canvas.GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.Shrink;
canvas.transform.SetParent(gameObject.transform);
//make scroll view and necessary children
scrollView = new GameObject("Scroll View", typeof(CanvasRenderer), typeof(Image), typeof(ScrollRect));
Image image = scrollView.GetComponent<Image>();
image.color = backgroundColor;
scrollView.transform.SetParent(canvas.transform);
RectTransform rt = scrollView.GetComponent<RectTransform>();
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.offsetMin = Vector2.zero;
rt.offsetMax = Vector2.zero;
//viewport
GameObject viewPort = new GameObject("Viewport", typeof(Mask), typeof(CanvasRenderer), typeof(Image));
viewPort.transform.SetParent(scrollView.transform);
RectTransform vpRt = viewPort.GetComponent<RectTransform>();
vpRt.pivot = Vector2.up;
vpRt.anchorMin = Vector2.zero;
vpRt.anchorMax = Vector2.one;
vpRt.anchoredPosition = Vector2.up;
vpRt.offsetMin = Vector2.zero;
vpRt.offsetMax = Vector2.zero;
Mask mask = viewPort.GetComponent<Mask>();
mask.showMaskGraphic = false;
//content
scrollViewContent = new GameObject("Content", typeof(VerticalLayoutGroup), typeof(ContentSizeFitter));
scrollViewContent.transform.SetParent(viewPort.transform);
scrollViewContentRectTransform = scrollViewContent.GetComponent<RectTransform>();
scrollViewContentRectTransform.offsetMin = Vector2.zero;
scrollViewContentRectTransform.offsetMax = new Vector2(0f, 100f);
scrollViewContentRectTransform.anchorMin = Vector2.up;
scrollViewContentRectTransform.anchorMax = Vector2.one;
scrollViewContentRectTransform.pivot = Vector2.up;
VerticalLayoutGroup vlg = scrollViewContent.GetComponent<VerticalLayoutGroup>();
vlg.padding = new RectOffset(10, 0, 10, 0);
vlg.spacing = 10;
vlg.childAlignment = TextAnchor.UpperLeft;
vlg.childForceExpandHeight = false;
vlg.childForceExpandWidth = true;
ContentSizeFitter cssf = scrollViewContent.GetComponent<ContentSizeFitter>();
cssf.horizontalFit = ContentSizeFitter.FitMode.Unconstrained;
cssf.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
//set scroll rect settings
ScrollRect scrollRect = scrollView.GetComponent<ScrollRect>();
scrollRect.content = scrollViewContentRectTransform;
scrollRect.horizontal = false;
scrollRect.vertical = true;
scrollRect.movementType = ScrollRect.MovementType.Elastic;
scrollRect.elasticity = 0.1f;
scrollRect.inertia = true;
scrollRect.decelerationRate = 0.135f;
scrollRect.scrollSensitivity = 1f;
scrollRect.viewport = vpRt;
}
private List<GameObject> textGameObjects = new List<GameObject>();
public void AddMessage(string message, LogType logType)
{
int lastNum = textGameObjects.Count;
if (textGameObjects.Count > maxNumberOfMessages)
{
for (int i = 0; i < textGameObjects.Count; i++)
{
if (textGameObjects[i].name == "0")
Destroy(textGameObjects[i]);
else
{
//move all the numbers names up
int thisNum = int.Parse(textGameObjects[i].name);
textGameObjects[i].name = (thisNum + 1).ToString();
lastNum = thisNum;
}
}
}
//make the new text
GameObject newTextGo = new GameObject(lastNum.ToString(), typeof(CanvasRenderer), typeof(Text), typeof(LayoutElement));
newTextGo.transform.SetParent(scrollViewContent.transform);
newTextGo.transform.SetAsLastSibling();
newTextGo.GetComponent<RectTransform>().localScale = Vector3.one;
Text text = newTextGo.GetComponent<Text>();
TextSettings.SetTextSettings(text, logType, message);
//might want to position to the last message instead.
scrollViewContentRectTransform.anchoredPosition = Vector2.zero;
textGameObjects.Add(newTextGo);
}
private GameObject saveLogButton;
private GameObject screenShotButton;
private GameObject clearLogButton;
void MakeButtons()
{
saveLogButton = new GameObject("SaveLogButton", typeof(CanvasRenderer), typeof(Image), typeof(Button));
saveLogButton.transform.SetParent(canvas.transform);
saveLogButton.transform.SetAsLastSibling();
ButtonSettings.SetButton(saveLogButton, "Save Log", () => { SaveLogButtonPressed(); });
RectTransform rt = saveLogButton.GetComponent<RectTransform>();
rt.anchoredPosition = new Vector3(-85f, 0f, 0f);
rt.sizeDelta = new Vector2(80f, 30f);
screenShotButton = new GameObject("ScreenshotButton", typeof(CanvasRenderer), typeof(Image), typeof(Button));
screenShotButton.transform.SetParent(canvas.transform);
screenShotButton.transform.SetAsLastSibling();
ButtonSettings.SetButton(screenShotButton, "Take Screenshot", () => { ScreenShotButton(); });
RectTransform rt1 = screenShotButton.GetComponent<RectTransform>();
rt1.anchoredPosition = new Vector3(-170f, 0f, 0f);
rt1.sizeDelta = new Vector2(110f, 30f);
clearLogButton = new GameObject("ClearLogButton", typeof(CanvasRenderer), typeof(Image), typeof(Button));
clearLogButton.transform.SetParent(canvas.transform);
clearLogButton.transform.SetAsLastSibling();
ButtonSettings.SetButton(clearLogButton, "Clear Log", () => { ClearLog(); });
RectTransform rt2 = clearLogButton.GetComponent<RectTransform>();
rt2.anchoredPosition = new Vector3(0f, 0f, 0f);
rt2.sizeDelta = new Vector2(80f, 30f);
}
public bool saveLogButtonVisible = true;
public bool screenShotButtonVisible = true;
public bool clearLogButtonVisible = true;
private bool m_isVisible = false;
public bool isVisible
{
get { return m_isVisible; }
set
{
m_isVisible = value;
if (canvas != null)
canvas.SetActive(m_isVisible);
if (saveLogButton != null)
{
if (!saveLogButtonVisible)
saveLogButton.SetActive(false);
else
saveLogButton.SetActive(m_isVisible);
}
if (screenShotButton != null)
{
if (!screenShotButtonVisible)
screenShotButton.SetActive(false);
else
screenShotButton.SetActive(m_isVisible);
}
if (clearLogButton != null)
{
if (!clearLogButtonVisible)
clearLogButton.SetActive(false);
else
clearLogButton.SetActive(m_isVisible);
}
}
}
public bool shouldSaveWindowLog = true;
public void SaveLogButtonPressed()
{
if (shouldSaveWindowLog)
{
string path = GetFileSavePath();
string file = Application.productName + "_errorlog.txt";
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path + "/" + file))
{
for (int i = 0; i < textGameObjects.Count; i++)
{
Text text = textGameObjects[i].GetComponent<Text>();
if (text != null)
{
sw.WriteLine(text.text);
}
}
sw.Close();
}
}
if (SaveLogButtonCallback != null)
SaveLogButtonCallback();
}
public bool shouldTakeScreenShot = true;
public void ScreenShotButton()
{
if (shouldTakeScreenShot)
{
string path = GetFileSavePath();
string file = Application.productName + "_errorscreen.png";
StartCoroutine(TakeScreenshot(path + "/" + file));
}
else
{
if (ScreenshotButtonCallback != null)
ScreenshotButtonCallback();
}
}
IEnumerator TakeScreenshot(string pathfile)
{
bool wasVisible = DebugConsole.instance.isVisible;
DebugConsole.instance.isVisible = false;
yield return new WaitForEndOfFrame();
ScreenCapture.CaptureScreenshot(pathfile);
yield return new WaitForEndOfFrame();
DebugConsole.instance.isVisible = wasVisible;
if (ScreenshotButtonCallback != null)
ScreenshotButtonCallback();
}
private string GetFileSavePath()
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory);
if (!System.IO.Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);
return path;
}
private void ClearLog()
{
for (int i = 0; i < textGameObjects.Count; i++)
{
Destroy(textGameObjects[i]);
}
if (ClearLogButtonCallback != null)
ClearLogButtonCallback();
}
}
public class TextSettings
{
private static Color assert = Color.magenta;
private static Color error = Color.red;
private static Color warning = Color.yellow;
private static Color log = Color.white;
public static Color GetColorByLogType(LogType logType)
{
switch (logType)
{
case LogType.Error:
return error;
case LogType.Assert:
return assert;
case LogType.Warning:
return warning;
case LogType.Log:
return log;
case LogType.Exception:
return error;
default:
return log;
}
}
public static FontStyle fontStyle
{ get { return FontStyle.Normal; } }
public static int fontSize
{ get { return 12; } }
public static float lineSpacing
{ get { return 1; } }
public static bool richText
{ get { return true; } }
public static TextAnchor alignment
{ get { return TextAnchor.UpperLeft; } }
public static HorizontalWrapMode horizontalOverflow
{ get { return HorizontalWrapMode.Wrap; } }
public static VerticalWrapMode verticalOverflow
{ get { return VerticalWrapMode.Truncate; } }
public static bool bestFit
{ get { return false; } }
public static bool rayCastTarget
{ get { return true; } }
public static void SetTextSettings(Text text , LogType logType, string message , Font font)
{
text.color = GetColorByLogType(logType);
text.text = message;
text.fontStyle = fontStyle;
text.fontSize = fontSize;
text.lineSpacing = lineSpacing;
text.supportRichText = richText;
text.alignment = alignment;
text.horizontalOverflow = horizontalOverflow;
text.verticalOverflow = verticalOverflow;
text.resizeTextForBestFit = bestFit;
text.raycastTarget = rayCastTarget;
text.font = font;
}
public static void SetTextSettings(Text text, LogType logType, string message)
{ SetTextSettings(text, logType, message, Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font); }
public static void SetTextSettings(Text text, LogType logType)
{ SetTextSettings(text, logType, "" , Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font); }
public static void SetTextSettings(Text text)
{ SetTextSettings(text, LogType.Log, "", Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font); }
}
public class ButtonSettings
{
public static void SetButton(GameObject buttonGo , string label , UnityAction buttonListener)
{
Image image = buttonGo.GetComponent<Image>();
if (image != null)
{
image.sprite = null;
image.color = Color.white;
image.raycastTarget = true;
}
Button button = buttonGo.GetComponent<Button>();
if (button != null)
{
button.interactable = true;
button.targetGraphic = image;
button.onClick.RemoveAllListeners();
button.onClick.AddListener(buttonListener);
}
RectTransform rt = buttonGo.GetComponent<RectTransform>();
rt.anchorMin = Vector2.right;
rt.anchorMax = Vector2.right;
rt.pivot = Vector2.right;
Text text = buttonGo.GetComponentInChildren<Text>();
if (text == null)
{
GameObject textLabel = new GameObject("Text" , typeof(CanvasRenderer), typeof(Text));
textLabel.transform.SetParent(buttonGo.transform);
text = textLabel.GetComponent<Text>();
text.font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
text.fontStyle = FontStyle.Normal;
text.fontSize = 14;
text.supportRichText = true;
text.alignment = TextAnchor.MiddleCenter;
text.horizontalOverflow = HorizontalWrapMode.Wrap;
text.verticalOverflow = VerticalWrapMode.Truncate;
text.resizeTextForBestFit = false;
text.color = Color.black;
text.raycastTarget = true;
RectTransform textRt = textLabel.GetComponent<RectTransform>();
textRt.anchoredPosition = Vector3.zero;
textRt.anchorMin = Vector2.zero;
textRt.anchorMax = Vector2.one;
textRt.pivot = new Vector2(0.5f, 0.5f);
textRt.offsetMin = Vector2.zero;
textRt.offsetMax = Vector2.zero;
}
text.text = label;
}
}
| |
// Copyright 2019 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Android.App;
using Android.OS;
using Android.Widget;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Android.Content;
using Android.Graphics;
using Android.Views;
namespace ArcGISRuntimeXamarin.Samples.EditFeatureAttachments
{
[Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Edit feature attachments",
category: "Data",
description: "Add, delete, and download attachments for features from a service.",
instructions: "Tap a feature to load its attachments. Use the buttons to save, delete, or add attachments.",
tags: new[] { "JPEG", "PDF", "PNG", "TXT", "data", "image", "picture" })]
public class EditFeatureAttachments : Activity
{
// Hold references to the UI controls.
private MapView _myMapView;
private ListView _attachmentsListView;
private Button _addButton;
// Hold a reference to the layer.
private FeatureLayer _damageLayer;
// Hold references to the currently selected feature & any attachments.
private ArcGISFeature _selectedFeature;
private IReadOnlyList<Attachment> _featureAttachments;
// URL to the feature service.
private const string FeatureServiceUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0";
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Edit feature attachments";
CreateLayout();
Initialize();
}
private void Initialize()
{
// Create the map with streets basemap.
_myMapView.Map = new Map(BasemapStyle.ArcGISStreets);
// Create the feature table, referring to the Damage Assessment feature service.
ServiceFeatureTable damageTable = new ServiceFeatureTable(new Uri(FeatureServiceUrl));
// Create a feature layer to visualize the features in the table.
_damageLayer = new FeatureLayer(damageTable);
// Add the layer to the map.
_myMapView.Map.OperationalLayers.Add(_damageLayer);
// Listen for user taps on the map.
_myMapView.GeoViewTapped += MapView_Tapped;
// Zoom to the United States.
_myMapView.SetViewpointCenterAsync(new MapPoint(-10800000, 4500000, SpatialReferences.WebMercator), 3e7);
}
private async void MapView_Tapped(object sender, GeoViewInputEventArgs e)
{
// Clear any existing selection.
_damageLayer.ClearSelection();
_addButton.Enabled = false;
_attachmentsListView.Enabled = false;
try
{
// Perform an identify to determine if a user tapped on a feature.
IdentifyLayerResult identifyResult = await _myMapView.IdentifyLayerAsync(_damageLayer, e.Position, 2, false);
// Do nothing if there are no results.
if (!identifyResult.GeoElements.Any())
{
return;
}
// Get the selected feature as an ArcGISFeature. It is assumed that all GeoElements in the result are of type ArcGISFeature.
GeoElement tappedElement = identifyResult.GeoElements.First();
_selectedFeature = (ArcGISFeature) tappedElement;
// Update the UI.
UpdateUIForFeature();
_addButton.Enabled = true;
_attachmentsListView.Enabled = true;
}
catch (Exception ex)
{
ShowMessage(ex.ToString(), "Error selecting feature");
}
}
private async void UpdateUIForFeature()
{
// Select the feature.
_damageLayer.SelectFeature(_selectedFeature);
// Get the attachments.
_featureAttachments = await _selectedFeature.GetAttachmentsAsync();
// Limit to only feature attachments with an image/jpeg content type.
_featureAttachments = _featureAttachments.Where(attachment => attachment.ContentType == "image/jpeg").ToList();
// Configure array adapter.
ArrayAdapter attachmentAdapter = new ArrayAdapter<string>(
this,
Android.Resource.Layout.SimpleListItem1,
_featureAttachments.Select(attachment => attachment.Name).ToArray());
// Populate the list.
_attachmentsListView.Adapter = attachmentAdapter;
}
private async Task PreviewAttachment(Attachment selectedAttachment)
{
if (selectedAttachment.ContentType.Contains("image"))
{
// Get the image data.
Stream contentStream = await selectedAttachment.GetDataAsync();
byte[] attachmentData = new byte[contentStream.Length];
contentStream.Read(attachmentData, 0, attachmentData.Length);
// Convert the image into a usable form on Android.
Bitmap bmp = BitmapFactory.DecodeByteArray (attachmentData, 0, attachmentData.Length);
// Create the view that will present the image.
ImageView imageView = new ImageView(this);
imageView.SetImageBitmap(bmp);
// Show the image view in a dialog.
ShowImageDialog(imageView);
}
else
{
ShowMessage("This sample can only show image attachments", "Can't show attachment");
}
}
private void ShowImageDialog(ImageView previewImageView)
{
// Create the dialog.
Dialog imageDialog = new Dialog(this);
// Remove the title bar for the dialog.
imageDialog.Window.RequestFeature(WindowFeatures.NoTitle);
// Add the image to the dialog.
imageDialog.SetContentView(previewImageView);
// Show the dialog.
imageDialog.Show();
}
private async Task DeleteAttachment(Attachment attachmentToDelete)
{
try
{
// Delete the attachment.
await _selectedFeature.DeleteAttachmentAsync(attachmentToDelete);
// Get a reference to the feature's service feature table.
ServiceFeatureTable serviceTable = (ServiceFeatureTable) _selectedFeature.FeatureTable;
// Apply the edits to the service feature table.
await serviceTable.ApplyEditsAsync();
// Update UI.
_selectedFeature.Refresh();
_featureAttachments = await _selectedFeature.GetAttachmentsAsync();
UpdateUIForFeature();
ShowMessage("Successfully deleted attachment", "Success!");
}
catch (Exception exception)
{
ShowMessage(exception.ToString(), "Error deleting attachment");
}
}
private void RequestImage()
{
// Start the process of requesting an image. Will be completed in OnActivityResult.
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), 1000);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
// Method called when the image picker activity ends.
if (requestCode == 1000 && resultCode == Result.Ok && data != null)
{
// Get the path to the selected image.
Android.Net.Uri uri = data.Data;
// Upload the image as an attachment.
AddAttachment(uri);
}
else
{
ShowMessage("No image selected.", "Error adding attachment");
}
}
private async void AddAttachment(Android.Net.Uri imageUri)
{
string contentType = "image/jpeg";
// Read the image into a stream.
Stream stream = ContentResolver.OpenInputStream(imageUri);
// Read from the stream into the byte array.
byte[] attachmentData;
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
attachmentData = memoryStream.ToArray();
}
// Add the attachment.
// The contentType string is the MIME type for JPEG files, image/jpeg.
await _selectedFeature.AddAttachmentAsync(imageUri.LastPathSegment + ".jpg", contentType, attachmentData);
// Get a reference to the feature's service feature table.
ServiceFeatureTable serviceTable = (ServiceFeatureTable) _selectedFeature.FeatureTable;
// Apply the edits to the service feature table.
await serviceTable.ApplyEditsAsync();
// Update UI.
_selectedFeature.Refresh();
_featureAttachments = await _selectedFeature.GetAttachmentsAsync();
UpdateUIForFeature();
ShowMessage("Successfully added attachment", "Success!");
}
private void Attachment_Clicked(object sender, AdapterView.ItemClickEventArgs e)
{
// Get the selected attachment.
Attachment selectedAttachment = _featureAttachments[e.Position];
// Create menu to show options.
PopupMenu menu = new PopupMenu(this, (ListView) sender);
// Handle the click, calling the right method depending on the command.
menu.MenuItemClick += async (o, menuArgs) =>
{
menu.Dismiss();
switch (menuArgs.Item.ToString())
{
case "View":
await PreviewAttachment(selectedAttachment);
break;
case "Delete":
await DeleteAttachment(selectedAttachment);
break;
}
UpdateUIForFeature();
};
// Add the menu commands.
menu.Menu.Add("View");
menu.Menu.Add("Delete");
// Show menu in the view.
menu.Show();
}
private void ShowMessage(string message, string title)
{
// Display the message to the user.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetMessage(message).SetTitle(title).Show();
}
private void CreateLayout()
{
// Create a new vertical layout for the app.
var layout = new LinearLayout(this) {Orientation = Orientation.Vertical};
// Create the MapView.
_myMapView = new MapView(this);
// Create the help label.
TextView helpLabel = new TextView(this);
helpLabel.Text = "Tap to select features.";
helpLabel.TextAlignment = TextAlignment.Center;
helpLabel.Gravity = GravityFlags.Center;
// Add the help label to the layout.
layout.AddView(helpLabel);
// Create and add a listview for showing attachments;
_attachmentsListView = new ListView(this);
_attachmentsListView.Enabled = false;
_attachmentsListView.SetMinimumHeight(100);
layout.AddView(_attachmentsListView);
_attachmentsListView.ItemClick += Attachment_Clicked;
// Create and add an 'add attachment' button.
_addButton = new Button(this);
_addButton.Text = "Add attachment";
_addButton.Enabled = false;
_addButton.Click += AddButton_Clicked;
layout.AddView(_addButton);
// Add the map view to the layout.
layout.AddView(_myMapView);
// Show the layout in the app.
SetContentView(layout);
}
private void AddButton_Clicked(object sender, EventArgs e)
{
// Do nothing if nothing selected.
if (_selectedFeature == null)
{
return;
}
// Start the process of requesting an image to add.
RequestImage();
}
}
}
| |
using System;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Animation.Animators;
using Avalonia.Animation.Utils;
using Avalonia.Data;
using Avalonia.Reactive;
namespace Avalonia.Animation
{
/// <summary>
/// Handles interpolation and time-related functions
/// for keyframe animations.
/// </summary>
internal class AnimationInstance<T> : SingleSubscriberObservableBase<T>
{
private T _lastInterpValue;
private T _firstKFValue;
private ulong? _iterationCount;
private ulong _currentIteration;
private bool _gotFirstKFValue;
private FillMode _fillMode;
private PlaybackDirection _playbackDirection;
private Animator<T> _animator;
private Animation _animation;
private Animatable _targetControl;
private T _neutralValue;
private double _speedRatioConv;
private TimeSpan _initialDelay;
private TimeSpan _iterationDelay;
private TimeSpan _duration;
private Easings.Easing _easeFunc;
private Action _onCompleteAction;
private Func<double, T, T> _interpolator;
private IDisposable _timerSub;
private readonly IClock _baseClock;
private IClock _clock;
public AnimationInstance(Animation animation, Animatable control, Animator<T> animator, IClock baseClock, Action OnComplete, Func<double, T, T> Interpolator)
{
_animator = animator;
_animation = animation;
_targetControl = control;
_onCompleteAction = OnComplete;
_interpolator = Interpolator;
_baseClock = baseClock;
_neutralValue = (T)_targetControl.GetValue(_animator.Property);
FetchProperties();
}
private void FetchProperties()
{
if (_animation.SpeedRatio < 0d)
throw new ArgumentOutOfRangeException("SpeedRatio value should not be negative.");
if (_animation.Duration.TotalSeconds <= 0)
throw new InvalidOperationException("Duration value cannot be negative or zero.");
_easeFunc = _animation.Easing;
_speedRatioConv = 1d / _animation.SpeedRatio;
_initialDelay = _animation.Delay;
_duration = _animation.Duration;
_iterationDelay = _animation.DelayBetweenIterations;
if (_animation.IterationCount.RepeatType == IterationType.Many)
_iterationCount = _animation.IterationCount.Value;
else
_iterationCount = null;
_playbackDirection = _animation.PlaybackDirection;
_fillMode = _animation.FillMode;
}
protected override void Unsubscribed()
{
// Animation may have been stopped before it has finished.
ApplyFinalFill();
_timerSub?.Dispose();
_clock.PlayState = PlayState.Stop;
}
protected override void Subscribed()
{
_clock = new Clock(_baseClock);
_timerSub = _clock.Subscribe(Step);
}
public void Step(TimeSpan frameTick)
{
try
{
InternalStep(frameTick);
}
catch (Exception e)
{
PublishError(e);
}
}
private void ApplyFinalFill()
{
if (_fillMode == FillMode.Forward || _fillMode == FillMode.Both)
_targetControl.SetValue(_animator.Property, _lastInterpValue, BindingPriority.LocalValue);
}
private void DoComplete()
{
ApplyFinalFill();
_onCompleteAction?.Invoke();
PublishCompleted();
}
private void DoDelay()
{
if (_fillMode == FillMode.Backward || _fillMode == FillMode.Both)
if (_currentIteration == 0)
PublishNext(_firstKFValue);
else
PublishNext(_lastInterpValue);
}
private void DoPlayStates()
{
if (_clock.PlayState == PlayState.Stop || _baseClock.PlayState == PlayState.Stop)
DoComplete();
if (!_gotFirstKFValue)
{
_firstKFValue = (T)_animator.First().Value;
_gotFirstKFValue = true;
}
}
private void InternalStep(TimeSpan time)
{
DoPlayStates();
FetchProperties();
// Scale timebases according to speedratio.
var indexTime = time.Ticks;
var iterDuration = _duration.Ticks * _speedRatioConv;
var iterDelay = _iterationDelay.Ticks * _speedRatioConv;
var initDelay = _initialDelay.Ticks * _speedRatioConv;
if (indexTime > 0 & indexTime <= initDelay)
{
DoDelay();
}
else
{
// Calculate timebases.
var iterationTime = iterDuration + iterDelay;
var opsTime = indexTime - initDelay;
var playbackTime = opsTime % iterationTime;
_currentIteration = (ulong)(opsTime / iterationTime);
// Stop animation when the current iteration is beyond the iteration count.
if ((_currentIteration + 1) > _iterationCount)
DoComplete();
if (playbackTime <= iterDuration)
{
// Normalize time for interpolation.
var normalizedTime = playbackTime / iterDuration;
// Check if normalized time needs to be reversed according to PlaybackDirection
bool playbackReversed;
switch (_playbackDirection)
{
case PlaybackDirection.Normal:
playbackReversed = false;
break;
case PlaybackDirection.Reverse:
playbackReversed = true;
break;
case PlaybackDirection.Alternate:
playbackReversed = (_currentIteration % 2 == 0) ? false : true;
break;
case PlaybackDirection.AlternateReverse:
playbackReversed = (_currentIteration % 2 == 0) ? true : false;
break;
default:
throw new InvalidOperationException($"Animation direction value is unknown: {_playbackDirection}");
}
if (playbackReversed)
normalizedTime = 1 - normalizedTime;
// Ease and interpolate
var easedTime = _easeFunc.Ease(normalizedTime);
_lastInterpValue = _interpolator(easedTime, _neutralValue);
PublishNext(_lastInterpValue);
}
else if (playbackTime > iterDuration &
playbackTime <= iterationTime &
iterDelay > 0)
{
// The last iteration's trailing delay should be skipped.
if ((_currentIteration + 1) < _iterationCount)
DoDelay();
else
DoComplete();
}
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Prime31;
namespace Prime31
{
public class EtceteraAndroidManager : AbstractManager
{
#if UNITY_ANDROID
// Fired when an alert button is clicked and returns the text from the button
public static event Action<string> alertButtonClickedEvent;
// Fired when the user presses the back button to avoid the alert
public static event Action alertCancelledEvent;
// Fired when a prompt finishes with the text the user entered
public static event Action<string> promptFinishedWithTextEvent;
// Fired when a prompt is cancelled either with back button or the negative button
public static event Action promptCancelledEvent;
// Fired when a prompt finishes with the text the user entered
public static event Action<string, string> twoFieldPromptFinishedWithTextEvent;
// Fired when a prompt is cancelled either with back button or the negative button
public static event Action twoFieldPromptCancelledEvent;
// Fired when the user presses the back button while viewing a web page
public static event Action webViewCancelledEvent;
// Fired when the user cancels selection of an image from the photo album
public static event Action albumChooserCancelledEvent;
// Fired when a user chooses an image. Returns the full path to the image.
public static event Action<string> albumChooserSucceededEvent;
// Fired when a user cancels the camera app without taking a picture
public static event Action photoChooserCancelledEvent;
// Fired when a photo is taking. Returns the full path to the image.
public static event Action<string> photoChooserSucceededEvent;
// Fired when a video is successfully taken and returns the full path to the video
public static event Action<string> videoRecordingSucceededEvent;
// Fired when the user cancels the video recording operation
public static event Action videoRecordingCancelledEvent;
// Fired when the text to speech system is ready for use
public static event Action ttsInitializedEvent;
// Fired when the text to speech system fails to initialize
public static event Action ttsFailedToInitializeEvent;
// Fired when the user chooses to review your app
public static event Action askForReviewWillOpenMarketEvent;
// Fired when the remind me later button is pressed when asking for a review
public static event Action askForReviewRemindMeLaterEvent;
// Fired when the dont ask me again button is pressed when asking for a review
public static event Action askForReviewDontAskAgainEvent;
// Fired when the loaded JavaScript in an inline web view calls UnityBridge.sendMessage(). Note that the Android javascript interface
// has many open bugs and this will not work on all device/OS combinations!
public static event Action<string> inlineWebViewJSCallbackEvent;
// Fired when a notification is received or after calling checkForNotifications and the app was launched from a notification
public static event Action<string> notificationReceivedEvent;
public static event Action<List<EtceteraAndroid.Contact>> contactsLoadedEvent;
static EtceteraAndroidManager()
{
AbstractManager.initialize( typeof( EtceteraAndroidManager ) );
}
public void alertButtonClicked( string positiveButton )
{
if( alertButtonClickedEvent != null )
alertButtonClickedEvent( positiveButton );
}
public void alertCancelled( string empty )
{
if( alertCancelledEvent != null )
alertCancelledEvent();
}
// handles single and two field prompts
public void promptFinishedWithText( string text )
{
// Was this one prompt or 2?
string[] promptText = text.Split( new string[] {"|||"}, StringSplitOptions.None );
if( promptText.Length == 1 )
{
if( promptFinishedWithTextEvent != null )
promptFinishedWithTextEvent( promptText[0] );
}
if( promptText.Length == 2 )
{
if( twoFieldPromptFinishedWithTextEvent != null )
twoFieldPromptFinishedWithTextEvent( promptText[0], promptText[1] );
}
}
public void promptCancelled( string empty )
{
if( promptCancelledEvent != null )
promptCancelledEvent();
}
public void twoFieldPromptCancelled( string empty )
{
if( twoFieldPromptCancelledEvent != null )
twoFieldPromptCancelledEvent();
}
public void webViewCancelled( string empty )
{
if( webViewCancelledEvent != null )
webViewCancelledEvent();
}
public void albumChooserCancelled( string empty )
{
if( albumChooserCancelledEvent != null )
albumChooserCancelledEvent();
}
public void albumChooserSucceeded( string path )
{
if( albumChooserSucceededEvent != null )
{
// make sure the file exists before proceeding to load it
if( System.IO.File.Exists( path ) )
albumChooserSucceededEvent( path );
else if( albumChooserCancelledEvent != null )
albumChooserCancelledEvent();
}
}
public void photoChooserCancelled( string empty )
{
if( photoChooserCancelledEvent != null )
photoChooserCancelledEvent();
}
public void photoChooserSucceeded( string path )
{
if( photoChooserSucceededEvent != null )
{
// make sur the file exists before proceeding to load it
if( System.IO.File.Exists( path ) )
photoChooserSucceededEvent( path );
else if( photoChooserCancelledEvent != null )
photoChooserCancelledEvent();
}
}
public void videoRecordingSucceeded( string path )
{
if( videoRecordingSucceededEvent != null )
videoRecordingSucceededEvent( path );
}
public void videoRecordingCancelled( string empty )
{
if( videoRecordingCancelledEvent != null )
videoRecordingCancelledEvent();
}
public void ttsInitialized( string result )
{
var res = result == "1";
if( res && ttsInitializedEvent != null )
ttsInitializedEvent();
if( !res && ttsFailedToInitializeEvent != null )
ttsFailedToInitializeEvent();
}
public void ttsUtteranceCompleted( string utteranceId )
{
Debug.Log( "utterance completed: " + utteranceId );
}
// Ask for review
public void askForReviewWillOpenMarket( string empty )
{
if( askForReviewWillOpenMarketEvent != null )
askForReviewWillOpenMarketEvent();
}
public void askForReviewRemindMeLater( string empty )
{
if( askForReviewRemindMeLaterEvent != null )
askForReviewRemindMeLaterEvent();
}
public void askForReviewDontAskAgain( string empty )
{
if( askForReviewDontAskAgainEvent != null )
askForReviewDontAskAgainEvent();
}
// Inline web view
public void inlineWebViewJSCallback( string message )
{
inlineWebViewJSCallbackEvent.fire( message );
}
// Notifications
public void notificationReceived( string extraData )
{
notificationReceivedEvent.fire( extraData );
}
void contactsLoaded( string json )
{
if( contactsLoadedEvent != null )
{
var list = Json.decode<List<EtceteraAndroid.Contact>>( json );
contactsLoadedEvent( list );
}
}
#endif
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using BinaryBitmap = com.google.zxing.BinaryBitmap;
using DecodeHintType = com.google.zxing.DecodeHintType;
using Reader = com.google.zxing.Reader;
using ReaderException = com.google.zxing.ReaderException;
using Result = com.google.zxing.Result;
using ResultMetadataType = com.google.zxing.ResultMetadataType;
using ResultPoint = com.google.zxing.ResultPoint;
using BitArray = com.google.zxing.common.BitArray;
using System.Collections.Generic; namespace com.google.zxing.oned
{
/// <summary> Encapsulates functionality and implementation that is common to all families
/// of one-dimensional barcodes.
///
/// </summary>
/// <author> dswitkin@google.com (Daniel Switkin)
/// </author>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
public abstract class OneDReader : Reader
{
private const int INTEGER_MATH_SHIFT = 8;
//UPGRADE_NOTE: Final was removed from the declaration of 'PATTERN_MATCH_RESULT_SCALE_FACTOR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
internal static readonly int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT;
public virtual Result decode(BinaryBitmap image)
{
return decode(image, null);
}
// Note that we don't try rotation without the try harder flag, even if rotation was supported.
public virtual Result decode(BinaryBitmap image, Dictionary<object, object> hints)
{
try
{
return doDecode(image, hints);
}
catch (ReaderException re)
{
bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
if (tryHarder && image.RotateSupported)
{
BinaryBitmap rotatedImage = image.rotateCounterClockwise();
Result result = doDecode(rotatedImage, hints);
// Record that we found it rotated 90 degrees CCW / 270 degrees CW
Dictionary<object, object> metadata = result.ResultMetadata;
int orientation = 270;
if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION))
{
// But if we found it reversed in doDecode(), add in that result here:
orientation = (orientation + ((System.Int32) metadata[ResultMetadataType.ORIENTATION])) % 360;
}
result.putMetadata(ResultMetadataType.ORIENTATION, (System.Object) orientation);
// Update result points
ResultPoint[] points = result.ResultPoints;
int height = rotatedImage.Height;
for (int i = 0; i < points.Length; i++)
{
points[i] = new ResultPoint(height - points[i].Y - 1, points[i].X);
}
return result;
}
else
{
throw re;
}
}
}
/// <summary> We're going to examine rows from the middle outward, searching alternately above and below the
/// middle, and farther out each time. rowStep is the number of rows between each successive
/// attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
/// middle + rowStep, then middle - (2 * rowStep), etc.
/// rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
/// decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
/// image if "trying harder".
///
/// </summary>
/// <param name="image">The image to decode
/// </param>
/// <param name="hints">Any hints that were requested
/// </param>
/// <returns> The contents of the decoded barcode
/// </returns>
/// <throws> ReaderException Any spontaneous errors which occur </throws>
private Result doDecode(BinaryBitmap image, Dictionary<object, object> hints)
{
int width = image.Width;
int height = image.Height;
BitArray row = new BitArray(width);
int middle = height >> 1;
bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
int rowStep = System.Math.Max(1, height >> (tryHarder?7:4));
int maxLines;
if (tryHarder)
{
maxLines = height; // Look at the whole image, not just the center
}
else
{
maxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image
}
for (int x = 0; x < maxLines; x++)
{
// Scanning from the middle out. Determine which row we're looking at next:
int rowStepsAboveOrBelow = (x + 1) >> 1;
bool isAbove = (x & 0x01) == 0; // i.e. is x even?
int rowNumber = middle + rowStep * (isAbove?rowStepsAboveOrBelow:- rowStepsAboveOrBelow);
if (rowNumber < 0 || rowNumber >= height)
{
// Oops, if we run off the top or bottom, stop
break;
}
// Estimate black point for this row and load it:
try
{
row = image.getBlackRow(rowNumber, row);
}
catch (ReaderException)
{
continue;
}
// While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
// handle decoding upside down barcodes.
for (int attempt = 0; attempt < 2; attempt++)
{
if (attempt == 1)
{
// trying again?
row.reverse(); // reverse the row and continue
// This means we will only ever draw result points *once* in the life of this method
// since we want to avoid drawing the wrong points after flipping the row, and,
// don't want to clutter with noise from every single row scan -- just the scans
// that start on the center line.
if (hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
{
Dictionary<object, object> newHints = new Dictionary<object, object>();
System.Collections.IEnumerator hintEnum = hints.Keys.GetEnumerator();
//UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
while (hintEnum.MoveNext())
{
//UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
System.Object key = hintEnum.Current;
if (!key.Equals(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
{
newHints[key] = hints[key];
}
}
hints = newHints;
}
}
try
{
// Look for a barcode
Result result = decodeRow(rowNumber, row, hints);
// We found our barcode
if (attempt == 1)
{
// But it was upside down, so note that
result.putMetadata(ResultMetadataType.ORIENTATION, (System.Object) 180);
// And remember to flip the result points horizontally.
ResultPoint[] points = result.ResultPoints;
points[0] = new ResultPoint(width - points[0].X - 1, points[0].Y);
points[1] = new ResultPoint(width - points[1].X - 1, points[1].Y);
}
return result;
}
catch (ReaderException)
{
// continue -- just couldn't decode this row
}
}
}
throw ReaderException.Instance;
}
/// <summary> Records the size of successive runs of white and black pixels in a row, starting at a given point.
/// The values are recorded in the given array, and the number of runs recorded is equal to the size
/// of the array. If the row starts on a white pixel at the given start point, then the first count
/// recorded is the run of white pixels starting from that point; likewise it is the count of a run
/// of black pixels if the row begin on a black pixels at that point.
///
/// </summary>
/// <param name="row">row to count from
/// </param>
/// <param name="start">offset into row to start at
/// </param>
/// <param name="counters">array into which to record counts
/// </param>
/// <throws> ReaderException if counters cannot be filled entirely from row before running out </throws>
/// <summary> of pixels
/// </summary>
internal static void recordPattern(BitArray row, int start, int[] counters)
{
int numCounters = counters.Length;
for (int i = 0; i < numCounters; i++)
{
counters[i] = 0;
}
int end = row.Size;
if (start >= end)
{
throw ReaderException.Instance;
}
bool isWhite = !row.get_Renamed(start);
int counterPosition = 0;
int i2 = start;
while (i2 < end)
{
bool pixel = row.get_Renamed(i2);
if (pixel ^ isWhite)
{
// that is, exactly one is true
counters[counterPosition]++;
}
else
{
counterPosition++;
if (counterPosition == numCounters)
{
break;
}
else
{
counters[counterPosition] = 1;
isWhite ^= true; // isWhite = !isWhite;
}
}
i2++;
}
// If we read fully the last section of pixels and filled up our counters -- or filled
// the last counter but ran off the side of the image, OK. Otherwise, a problem.
if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i2 == end)))
{
throw ReaderException.Instance;
}
}
/// <summary> Determines how closely a set of observed counts of runs of black/white values matches a given
/// target pattern. This is reported as the ratio of the total variance from the expected pattern
/// proportions across all pattern elements, to the length of the pattern.
///
/// </summary>
/// <param name="counters">observed counters
/// </param>
/// <param name="pattern">expected pattern
/// </param>
/// <param name="maxIndividualVariance">The most any counter can differ before we give up
/// </param>
/// <returns> ratio of total variance between counters and pattern compared to total pattern size,
/// where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
/// the total variance between counters and patterns equals the pattern length, higher values mean
/// even more variance
/// </returns>
internal static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance)
{
int numCounters = counters.Length;
int total = 0;
int patternLength = 0;
for (int i = 0; i < numCounters; i++)
{
total += counters[i];
patternLength += pattern[i];
}
if (total < patternLength)
{
// If we don't even have one pixel per unit of bar width, assume this is too small
// to reliably match, so fail:
return System.Int32.MaxValue;
}
// We're going to fake floating-point math in integers. We just need to use more bits.
// Scale up patternLength so that intermediate values below like scaledCounter will have
// more "significant digits"
int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
int totalVariance = 0;
for (int x = 0; x < numCounters; x++)
{
int counter = counters[x] << INTEGER_MATH_SHIFT;
int scaledPattern = pattern[x] * unitBarWidth;
int variance = counter > scaledPattern?counter - scaledPattern:scaledPattern - counter;
if (variance > maxIndividualVariance)
{
return System.Int32.MaxValue;
}
totalVariance += variance;
}
return totalVariance / total;
}
/// <summary> <p>Attempts to decode a one-dimensional barcode format given a single row of
/// an image.</p>
///
/// </summary>
/// <param name="rowNumber">row number from top of the row
/// </param>
/// <param name="row">the black/white pixel data of the row
/// </param>
/// <param name="hints">decode hints
/// </param>
/// <returns> {@link Result} containing encoded string and start/end of barcode
/// </returns>
/// <throws> ReaderException if an error occurs or barcode cannot be found </throws>
public abstract Result decodeRow(int rowNumber, BitArray row, Dictionary<object, object> hints);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Resources;
using Microsoft.Build.CommandLine;
using Microsoft.Build.Construction;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Shouldly;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public class CommandLineSwitchesTests
{
public CommandLineSwitchesTests()
{
// Make sure resources are initialized
MSBuildApp.Initialize();
}
[Fact]
public void BogusSwitchIdentificationTests()
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
CommandLineSwitches.IsParameterlessSwitch("bogus", out parameterlessSwitch, out duplicateSwitchErrorMessage).ShouldBeFalse();
parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.Invalid);
duplicateSwitchErrorMessage.ShouldBeNull();
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch("bogus", out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeFalse();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Invalid);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldBeNull();
unquoteParameters.ShouldBeFalse();
}
[Theory]
[InlineData("help")]
[InlineData("HELP")]
[InlineData("Help")]
[InlineData("h")]
[InlineData("H")]
[InlineData("?")]
public void HelpSwitchIdentificationTests(string help)
{
CommandLineSwitches.IsParameterlessSwitch(help, out CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, out string duplicateSwitchErrorMessage).ShouldBeTrue();
parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.Help);
duplicateSwitchErrorMessage.ShouldBeNull();
}
[Theory]
[InlineData("version")]
[InlineData("Version")]
[InlineData("VERSION")]
[InlineData("ver")]
[InlineData("VER")]
[InlineData("Ver")]
public void VersionSwitchIdentificationTests(string version)
{
CommandLineSwitches.IsParameterlessSwitch(version, out CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, out string duplicateSwitchErrorMessage).ShouldBeTrue();
parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.Version);
duplicateSwitchErrorMessage.ShouldBeNull();
}
[Theory]
[InlineData("nologo")]
[InlineData("NOLOGO")]
[InlineData("NoLogo")]
public void NoLogoSwitchIdentificationTests(string nologo)
{
CommandLineSwitches.IsParameterlessSwitch(nologo, out CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, out string duplicateSwitchErrorMessage).ShouldBeTrue();
parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.NoLogo);
duplicateSwitchErrorMessage.ShouldBeNull();
}
[Theory]
[InlineData("noautoresponse")]
[InlineData("NOAUTORESPONSE")]
[InlineData("NoAutoResponse")]
[InlineData("noautorsp")]
[InlineData("NOAUTORSP")]
[InlineData("NoAutoRsp")]
public void NoAutoResponseSwitchIdentificationTests(string noautoresponse)
{
CommandLineSwitches.IsParameterlessSwitch(noautoresponse, out CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, out string duplicateSwitchErrorMessage).ShouldBeTrue();
parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse);
duplicateSwitchErrorMessage.ShouldBeNull();
}
[Theory]
[InlineData("noconsolelogger")]
[InlineData("NOCONSOLELOGGER")]
[InlineData("NoConsoleLogger")]
[InlineData("noconlog")]
[InlineData("NOCONLOG")]
[InlineData("NoConLog")]
public void NoConsoleLoggerSwitchIdentificationTests(string noconsolelogger)
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
CommandLineSwitches.IsParameterlessSwitch(noconsolelogger, out parameterlessSwitch, out duplicateSwitchErrorMessage).ShouldBeTrue();
parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger);
duplicateSwitchErrorMessage.ShouldBeNull();
}
[Theory]
[InlineData("fileLogger")]
[InlineData("FILELOGGER")]
[InlineData("FileLogger")]
[InlineData("fl")]
[InlineData("FL")]
public void FileLoggerSwitchIdentificationTests(string filelogger)
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
CommandLineSwitches.IsParameterlessSwitch(filelogger, out parameterlessSwitch, out duplicateSwitchErrorMessage).ShouldBeTrue();
parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.FileLogger);
duplicateSwitchErrorMessage.ShouldBeNull();
}
[Theory]
[InlineData("distributedfilelogger")]
[InlineData("DISTRIBUTEDFILELOGGER")]
[InlineData("DistributedFileLogger")]
[InlineData("dfl")]
[InlineData("DFL")]
public void DistributedFileLoggerSwitchIdentificationTests(string distributedfilelogger)
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
CommandLineSwitches.IsParameterlessSwitch(distributedfilelogger, out parameterlessSwitch, out duplicateSwitchErrorMessage).ShouldBeTrue();
parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.DistributedFileLogger);
duplicateSwitchErrorMessage.ShouldBeNull();
}
[Theory]
[InlineData("flp")]
[InlineData("FLP")]
[InlineData("fileLoggerParameters")]
[InlineData("FILELOGGERPARAMETERS")]
public void FileLoggerParametersIdentificationTests(string fileloggerparameters)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(fileloggerparameters, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.FileLoggerParameters);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldNotBeNull();
unquoteParameters.ShouldBeTrue();
}
#if FEATURE_NODE_REUSE
[Theory]
[InlineData("nr")]
[InlineData("NR")]
[InlineData("nodereuse")]
[InlineData("NodeReuse")]
public void NodeReuseParametersIdentificationTests(string nodereuse)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(nodereuse, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.NodeReuse);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldNotBeNull();
unquoteParameters.ShouldBeTrue();
}
#endif
[Fact]
public void ProjectSwitchIdentificationTests()
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
Assert.True(CommandLineSwitches.IsParameterizedSwitch(null, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Project, parameterizedSwitch);
Assert.NotNull(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.True(unquoteParameters);
// for the virtual project switch, we match on null, not empty string
Assert.False(CommandLineSwitches.IsParameterizedSwitch(String.Empty, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed));
Assert.Equal(CommandLineSwitches.ParameterizedSwitch.Invalid, parameterizedSwitch);
Assert.Null(duplicateSwitchErrorMessage);
Assert.False(multipleParametersAllowed);
Assert.Null(missingParametersErrorMessage);
Assert.False(unquoteParameters);
}
[Theory]
[InlineData("ignoreprojectextensions")]
[InlineData("IgnoreProjectExtensions")]
[InlineData("IGNOREPROJECTEXTENSIONS")]
[InlineData("ignore")]
[InlineData("IGNORE")]
public void IgnoreProjectExtensionsSwitchIdentificationTests(string ignoreprojectextensions)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(ignoreprojectextensions, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.IgnoreProjectExtensions);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeTrue();
missingParametersErrorMessage.ShouldNotBeNull();
unquoteParameters.ShouldBeTrue();
}
[Theory]
[InlineData("target")]
[InlineData("TARGET")]
[InlineData("Target")]
[InlineData("t")]
[InlineData("T")]
public void TargetSwitchIdentificationTests(string target)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(target, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Target);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeTrue();
missingParametersErrorMessage.ShouldNotBeNull();
unquoteParameters.ShouldBeTrue();
}
[Theory]
[InlineData("property")]
[InlineData("PROPERTY")]
[InlineData("Property")]
[InlineData("p")]
[InlineData("P")]
public void PropertySwitchIdentificationTests(string property)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(property, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Property);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeTrue();
missingParametersErrorMessage.ShouldNotBeNull();
unquoteParameters.ShouldBeTrue();
}
[Theory]
[InlineData("logger")]
[InlineData("LOGGER")]
[InlineData("Logger")]
[InlineData("l")]
[InlineData("L")]
public void LoggerSwitchIdentificationTests(string logger)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(logger, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Logger);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldNotBeNull();
unquoteParameters.ShouldBeFalse();
}
[Theory]
[InlineData("verbosity")]
[InlineData("VERBOSITY")]
[InlineData("Verbosity")]
[InlineData("v")]
[InlineData("V")]
public void VerbositySwitchIdentificationTests(string verbosity)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(verbosity, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Verbosity);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldNotBeNull();
unquoteParameters.ShouldBeTrue();
}
[Theory]
[InlineData("ds")]
[InlineData("DS")]
[InlineData("Ds")]
[InlineData("detailedsummary")]
[InlineData("DETAILEDSUMMARY")]
[InlineData("DetailedSummary")]
public void DetailedSummarySwitchIndentificationTests(string detailedsummary)
{
CommandLineSwitches.ParameterlessSwitch parameterlessSwitch;
string duplicateSwitchErrorMessage;
CommandLineSwitches.IsParameterlessSwitch(detailedsummary, out parameterlessSwitch, out duplicateSwitchErrorMessage).ShouldBeTrue();
parameterlessSwitch.ShouldBe(CommandLineSwitches.ParameterlessSwitch.DetailedSummary);
duplicateSwitchErrorMessage.ShouldBeNull();
}
[Theory]
[InlineData("m")]
[InlineData("M")]
[InlineData("maxcpucount")]
[InlineData("MAXCPUCOUNT")]
public void MaxCPUCountSwitchIdentificationTests(string maxcpucount)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(maxcpucount, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.MaxCPUCount);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldNotBeNull();
unquoteParameters.ShouldBeTrue();
}
#if FEATURE_XML_SCHEMA_VALIDATION
[Theory]
[InlineData("validate")]
[InlineData("VALIDATE")]
[InlineData("Validate")]
[InlineData("val")]
[InlineData("VAL")]
[InlineData("Val")]
public void ValidateSwitchIdentificationTests(string validate)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(validate, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Validate);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldBeNull();
unquoteParameters.ShouldBeTrue();
}
#endif
[Theory]
[InlineData("preprocess")]
[InlineData("pp")]
public void PreprocessSwitchIdentificationTests(string preprocess)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(preprocess, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Preprocess);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldBeNull();
unquoteParameters.ShouldBeTrue();
}
[Theory]
[InlineData("targets")]
[InlineData("tArGeTs")]
[InlineData("ts")]
public void TargetsSwitchIdentificationTests(string @switch)
{
CommandLineSwitches.IsParameterizedSwitch(
@switch,
out var parameterizedSwitch,
out var duplicateSwitchErrorMessage,
out var multipleParametersAllowed,
out var missingParametersErrorMessage,
out var unquoteParameters,
out var emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.Targets);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldBeNull();
unquoteParameters.ShouldBeTrue();
emptyParametersAllowed.ShouldBeFalse();
}
[Fact]
public void TargetsSwitchParameter()
{
CommandLineSwitches switches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList() { "/targets:targets.txt" }, switches);
switches.HaveErrors().ShouldBeFalse();
switches[CommandLineSwitches.ParameterizedSwitch.Targets].ShouldBe(new[] { "targets.txt" });
}
[Fact]
public void TargetsSwitchDoesNotSupportMultipleOccurrences()
{
CommandLineSwitches switches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList() { "/targets /targets" }, switches);
switches.HaveErrors().ShouldBeTrue();
}
[Theory]
[InlineData("isolate")]
[InlineData("ISOLATE")]
[InlineData("isolateprojects")]
[InlineData("isolateProjects")]
public void IsolateProjectsSwitchIdentificationTests(string isolateprojects)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(isolateprojects, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.IsolateProjects);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldBeNull();
unquoteParameters.ShouldBeTrue();
emptyParametersAllowed.ShouldBeFalse();
}
[Theory]
[InlineData("graph")]
[InlineData("GRAPH")]
[InlineData("graphbuild")]
[InlineData("graphBuild")]
public void GraphBuildSwitchIdentificationTests(string graph)
{
CommandLineSwitches.ParameterizedSwitch parameterizedSwitch;
string duplicateSwitchErrorMessage;
bool multipleParametersAllowed;
string missingParametersErrorMessage;
bool unquoteParameters;
bool emptyParametersAllowed;
CommandLineSwitches.IsParameterizedSwitch(graph, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters, out emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.GraphBuild);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldBeNull();
unquoteParameters.ShouldBeTrue();
emptyParametersAllowed.ShouldBeFalse();
}
[Theory]
[InlineData("low")]
[InlineData("LOW")]
[InlineData("lowpriority")]
[InlineData("lowPriority")]
public void LowPrioritySwitchIdentificationTests(string lowpriority)
{
CommandLineSwitches.IsParameterizedSwitch(lowpriority,
out CommandLineSwitches.ParameterizedSwitch parameterizedSwitch,
out string duplicateSwitchErrorMessage,
out bool multipleParametersAllowed,
out string missingParametersErrorMessage,
out bool unquoteParameters,
out bool emptyParametersAllowed).ShouldBeTrue();
parameterizedSwitch.ShouldBe(CommandLineSwitches.ParameterizedSwitch.LowPriority);
duplicateSwitchErrorMessage.ShouldBeNull();
multipleParametersAllowed.ShouldBeFalse();
missingParametersErrorMessage.ShouldBeNull();
unquoteParameters.ShouldBeTrue();
emptyParametersAllowed.ShouldBeFalse();
}
[Fact]
public void InputResultsCachesSupportsMultipleOccurrence()
{
CommandLineSwitches switches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(){"/irc", "/irc:a;b", "/irc:c;d"}, switches);
switches[CommandLineSwitches.ParameterizedSwitch.InputResultsCaches].ShouldBe(new []{null, "a", "b", "c", "d"});
switches.HaveErrors().ShouldBeFalse();
}
[Fact]
public void OutputResultsCache()
{
CommandLineSwitches switches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(){"/orc:a"}, switches);
switches[CommandLineSwitches.ParameterizedSwitch.OutputResultsCache].ShouldBe(new []{"a"});
switches.HaveErrors().ShouldBeFalse();
}
[Fact]
public void OutputResultsCachesDoesNotSupportMultipleOccurrences()
{
CommandLineSwitches switches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(){"/orc:a", "/orc:b"}, switches);
switches.HaveErrors().ShouldBeTrue();
}
[Fact]
public void SetParameterlessSwitchTests()
{
CommandLineSwitches switches = new CommandLineSwitches();
switches.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoLogo, "/nologo");
Assert.Equal("/nologo", switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoLogo));
Assert.True(switches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoLogo));
Assert.True(switches[CommandLineSwitches.ParameterlessSwitch.NoLogo]);
// set it again
switches.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoLogo, "-NOLOGO");
Assert.Equal("-NOLOGO", switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoLogo));
Assert.True(switches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoLogo));
Assert.True(switches[CommandLineSwitches.ParameterlessSwitch.NoLogo]);
// we didn't set this switch
Assert.Null(switches.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.Version));
Assert.False(switches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Version));
Assert.False(switches[CommandLineSwitches.ParameterlessSwitch.Version]);
}
[Fact]
public void SetParameterizedSwitchTests1()
{
CommandLineSwitches switches = new CommandLineSwitches();
Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Verbosity, "/v:q", "q", false, true, false));
Assert.Equal("/v:q", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Verbosity));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Verbosity));
string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.Verbosity];
Assert.NotNull(parameters);
Assert.Single(parameters);
Assert.Equal("q", parameters[0]);
// set it again -- this is bogus, because the /verbosity switch doesn't allow multiple parameters, but for the
// purposes of testing the SetParameterizedSwitch() method, it doesn't matter
Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Verbosity, "/verbosity:\"diag\";minimal", "\"diag\";minimal", true, true, false));
Assert.Equal("/v:q /verbosity:\"diag\";minimal", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Verbosity));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Verbosity));
parameters = switches[CommandLineSwitches.ParameterizedSwitch.Verbosity];
Assert.NotNull(parameters);
Assert.Equal(3, parameters.Length);
Assert.Equal("q", parameters[0]);
Assert.Equal("diag", parameters[1]);
Assert.Equal("minimal", parameters[2]);
}
[Fact]
public void SetParameterizedSwitchTests2()
{
CommandLineSwitches switches = new CommandLineSwitches();
// we haven't set this switch yet
Assert.Null(switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target));
Assert.False(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.Target];
Assert.NotNull(parameters);
Assert.Empty(parameters);
// fake/missing parameters -- this is bogus because the /target switch allows multiple parameters but we're turning
// that off here just for testing purposes
Assert.False(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:\"", "\"", false, true, false));
// switch has been set
Assert.Equal("/t:\"", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
parameters = switches[CommandLineSwitches.ParameterizedSwitch.Target];
// but no parameters
Assert.NotNull(parameters);
Assert.Empty(parameters);
// more fake/missing parameters
Assert.False(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:A,\"\";B", "A,\"\";B", true, true, false));
Assert.Equal("/t:\" /t:A,\"\";B", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
parameters = switches[CommandLineSwitches.ParameterizedSwitch.Target];
// now we have some parameters
Assert.NotNull(parameters);
Assert.Equal(2, parameters.Length);
Assert.Equal("A", parameters[0]);
Assert.Equal("B", parameters[1]);
}
[Fact]
public void SetParameterizedSwitchTests3()
{
CommandLineSwitches switches = new CommandLineSwitches();
// we haven't set this switch yet
Assert.Null(switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Logger));
Assert.False(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Logger));
string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.Logger];
Assert.NotNull(parameters);
Assert.Empty(parameters);
// don't unquote fake/missing parameters
Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Logger, "/l:\"", "\"", false, false, false));
Assert.Equal("/l:\"", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Logger));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Logger));
parameters = switches[CommandLineSwitches.ParameterizedSwitch.Logger];
Assert.NotNull(parameters);
Assert.Single(parameters);
Assert.Equal("\"", parameters[0]);
// don't unquote multiple fake/missing parameters -- this is bogus because the /logger switch does not take multiple
// parameters, but for testing purposes this is fine
Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Logger, "/LOGGER:\"\",asm;\"p,a;r\"", "\"\",asm;\"p,a;r\"", true, false, false));
Assert.Equal("/l:\" /LOGGER:\"\",asm;\"p,a;r\"", switches.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Logger));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Logger));
parameters = switches[CommandLineSwitches.ParameterizedSwitch.Logger];
Assert.NotNull(parameters);
Assert.Equal(4, parameters.Length);
Assert.Equal("\"", parameters[0]);
Assert.Equal("\"\"", parameters[1]);
Assert.Equal("asm", parameters[2]);
Assert.Equal("\"p,a;r\"", parameters[3]);
}
[Fact]
public void SetParameterizedSwitchTestsAllowEmpty()
{
CommandLineSwitches switches = new CommandLineSwitches();
Assert.True(switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.WarningsAsErrors, "/warnaserror", "", multipleParametersAllowed: true, unquoteParameters: false, emptyParametersAllowed: true));
Assert.True(switches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.WarningsAsErrors));
string[] parameters = switches[CommandLineSwitches.ParameterizedSwitch.WarningsAsErrors];
Assert.NotNull(parameters);
Assert.True(parameters.Length > 0);
Assert.Null(parameters.Last());
}
[Fact]
public void AppendErrorTests1()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
CommandLineSwitches switchesRight = new CommandLineSwitches();
Assert.False(switchesLeft.HaveErrors());
Assert.False(switchesRight.HaveErrors());
switchesLeft.Append(switchesRight);
Assert.False(switchesLeft.HaveErrors());
Assert.False(switchesRight.HaveErrors());
switchesLeft.SetUnknownSwitchError("/bogus");
Assert.True(switchesLeft.HaveErrors());
Assert.False(switchesRight.HaveErrors());
switchesLeft.Append(switchesRight);
Assert.True(switchesLeft.HaveErrors());
Assert.False(switchesRight.HaveErrors());
VerifySwitchError(switchesLeft, "/bogus");
switchesRight.Append(switchesLeft);
Assert.True(switchesLeft.HaveErrors());
Assert.True(switchesRight.HaveErrors());
VerifySwitchError(switchesLeft, "/bogus");
VerifySwitchError(switchesRight, "/bogus");
}
[Fact]
public void AppendErrorTests2()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
CommandLineSwitches switchesRight = new CommandLineSwitches();
Assert.False(switchesLeft.HaveErrors());
Assert.False(switchesRight.HaveErrors());
switchesLeft.SetUnknownSwitchError("/bogus");
switchesRight.SetUnexpectedParametersError("/nologo:foo");
Assert.True(switchesLeft.HaveErrors());
Assert.True(switchesRight.HaveErrors());
VerifySwitchError(switchesLeft, "/bogus");
VerifySwitchError(switchesRight, "/nologo:foo");
switchesLeft.Append(switchesRight);
VerifySwitchError(switchesLeft, "/bogus");
VerifySwitchError(switchesRight, "/nologo:foo");
}
[Fact]
public void AppendParameterlessSwitchesTests()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
switchesLeft.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.Help, "/?");
Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.False(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
CommandLineSwitches switchesRight1 = new CommandLineSwitches();
switchesRight1.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, "/noconlog");
Assert.False(switchesRight1.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesRight1.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
switchesLeft.Append(switchesRight1);
Assert.Equal("/noconlog", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger]);
// this switch is not affected
Assert.Equal("/?", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.Help]);
CommandLineSwitches switchesRight2 = new CommandLineSwitches();
switchesRight2.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger, "/NOCONSOLELOGGER");
Assert.False(switchesRight2.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesRight2.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
switchesLeft.Append(switchesRight2);
Assert.Equal("/NOCONSOLELOGGER", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger));
Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger]);
Assert.Equal("/?", switchesLeft.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesLeft.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Help));
Assert.True(switchesLeft[CommandLineSwitches.ParameterlessSwitch.Help]);
Assert.False(switchesLeft.HaveErrors());
}
[Fact]
public void AppendParameterizedSwitchesTests1()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
switchesLeft.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Project, "tempproject.proj", "tempproject.proj", false, true, false);
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
Assert.False(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
CommandLineSwitches switchesRight = new CommandLineSwitches();
switchesRight.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:build", "build", true, true, false);
Assert.False(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
Assert.True(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
switchesLeft.Append(switchesRight);
Assert.Equal("tempproject.proj", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Project));
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
string[] parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Project];
Assert.NotNull(parameters);
Assert.Single(parameters);
Assert.Equal("tempproject.proj", parameters[0]);
Assert.Equal("/t:build", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target));
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Target];
Assert.NotNull(parameters);
Assert.Single(parameters);
Assert.Equal("build", parameters[0]);
}
[Fact]
public void AppendParameterizedSwitchesTests2()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
switchesLeft.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/target:Clean", "Clean", true, true, false);
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
CommandLineSwitches switchesRight = new CommandLineSwitches();
switchesRight.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Target, "/t:\"RESOURCES\";build", "\"RESOURCES\";build", true, true, false);
Assert.True(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
switchesLeft.Append(switchesRight);
Assert.Equal("/t:\"RESOURCES\";build", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Target));
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Target));
string[] parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Target];
Assert.NotNull(parameters);
Assert.Equal(3, parameters.Length);
Assert.Equal("Clean", parameters[0]);
Assert.Equal("RESOURCES", parameters[1]);
Assert.Equal("build", parameters[2]);
}
[Fact]
public void AppendParameterizedSwitchesTests3()
{
CommandLineSwitches switchesLeft = new CommandLineSwitches();
switchesLeft.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Project, "tempproject.proj", "tempproject.proj", false, true, false);
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
CommandLineSwitches switchesRight = new CommandLineSwitches();
switchesRight.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Project, "Rhubarb.proj", "Rhubarb.proj", false, true, false);
Assert.True(switchesRight.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
switchesLeft.Append(switchesRight);
Assert.Equal("tempproject.proj", switchesLeft.GetParameterizedSwitchCommandLineArg(CommandLineSwitches.ParameterizedSwitch.Project));
Assert.True(switchesLeft.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Project));
string[] parameters = switchesLeft[CommandLineSwitches.ParameterizedSwitch.Project];
Assert.NotNull(parameters);
Assert.Single(parameters);
Assert.Equal("tempproject.proj", parameters[0]);
Assert.True(switchesLeft.HaveErrors());
VerifySwitchError(switchesLeft, "Rhubarb.proj");
}
[Fact]
public void InvalidToolsVersionErrors()
{
Assert.Throws<InitializationException>(() =>
{
string filename = null;
try
{
filename = FileUtilities.GetTemporaryFile();
ProjectRootElement project = ProjectRootElement.Create();
project.Save(filename);
MSBuildApp.BuildProject(
filename,
null,
"ScoobyDoo",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
new ILogger[] { },
LoggerVerbosity.Normal,
new DistributedLoggerRecord[] { },
#if FEATURE_XML_SCHEMA_VALIDATION
false,
null,
#endif
1,
true,
new StringWriter(),
new StringWriter(),
false,
warningsAsErrors: null,
warningsAsMessages: null,
enableRestore: false,
profilerLogger: null,
enableProfiler: false,
interactive: false,
isolateProjects: false,
graphBuild: false,
lowPriority: false,
inputResultsCaches: null,
outputResultsCache: null
);
}
finally
{
if (File.Exists(filename)) File.Delete(filename);
}
}
);
}
[Fact]
public void TestHaveAnySwitchesBeenSet()
{
// Check if method works with parameterized switch
CommandLineSwitches switches = new CommandLineSwitches();
Assert.False(switches.HaveAnySwitchesBeenSet());
switches.SetParameterizedSwitch(CommandLineSwitches.ParameterizedSwitch.Verbosity, "/v:q", "q", false, true, false);
Assert.True(switches.HaveAnySwitchesBeenSet());
// Check if method works with parameterless switches
switches = new CommandLineSwitches();
Assert.False(switches.HaveAnySwitchesBeenSet());
switches.SetParameterlessSwitch(CommandLineSwitches.ParameterlessSwitch.Help, "/?");
Assert.True(switches.HaveAnySwitchesBeenSet());
}
#if FEATURE_NODE_REUSE
/// <summary>
/// /nodereuse:false /nodereuse:true should result in "true"
/// </summary>
[Fact]
public void ProcessNodeReuseSwitchTrueLast()
{
bool nodeReuse = MSBuildApp.ProcessNodeReuseSwitch(new string[] { "false", "true" });
Assert.True(nodeReuse);
}
/// <summary>
/// /nodereuse:true /nodereuse:false should result in "false"
/// </summary>
[Fact]
public void ProcessNodeReuseSwitchFalseLast()
{
bool nodeReuse = MSBuildApp.ProcessNodeReuseSwitch(new string[] { "true", "false" });
Assert.False(nodeReuse);
}
#endif
/// <summary>
/// Regress DDB #143341:
/// msbuild /clp:v=quiet /clp:v=diag /m:2
/// gave console logger in quiet verbosity; expected diagnostic
/// </summary>
[Fact]
public void ExtractAnyLoggerParameterPickLast()
{
string result = MSBuildApp.ExtractAnyLoggerParameter("v=diag;v=q", new string[] { "v", "verbosity" });
Assert.Equal("v=q", result);
}
/// <summary>
/// Verifies that when the /warnaserror switch is not specified, the set of warnings is null.
/// </summary>
[Fact]
public void ProcessWarnAsErrorSwitchNotSpecified()
{
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[] { "" }), commandLineSwitches);
Assert.Null(MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches));
}
/// <summary>
/// Verifies that the /warnaserror switch is parsed properly when codes are specified.
/// </summary>
[Fact]
public void ProcessWarnAsErrorSwitchWithCodes()
{
ISet<string> expectedWarningsAsErrors = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a", "B", "c", "D", "e" };
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[]
{
"\"/warnaserror: a,B ; c \"", // Leading, trailing, leading and trailing whitespace
"/warnaserror:A,b,C", // Repeats of different case
"\"/warnaserror:, ,,\"", // Empty items
"/err:D,d;E,e", // A different source with new items and uses the short form
"/warnaserror:a", // A different source with a single duplicate
"/warnaserror:a,b", // A different source with multiple duplicates
}), commandLineSwitches);
ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches);
Assert.NotNull(actualWarningsAsErrors);
Assert.Equal(expectedWarningsAsErrors, actualWarningsAsErrors, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Verifies that an empty /warnaserror switch clears the list of codes.
/// </summary>
[Fact]
public void ProcessWarnAsErrorSwitchEmptySwitchClearsSet()
{
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[]
{
"/warnaserror:a;b;c",
"/warnaserror",
}), commandLineSwitches);
ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches);
Assert.NotNull(actualWarningsAsErrors);
Assert.Empty(actualWarningsAsErrors);
}
/// <summary>
/// Verifies that when values are specified after an empty /warnaserror switch that they are added to the cleared list.
/// </summary>
[Fact]
public void ProcessWarnAsErrorSwitchValuesAfterEmptyAddOn()
{
ISet<string> expectedWarningsAsErors = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "e", "f", "g" };
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[]
{
"/warnaserror:a;b;c",
"/warnaserror",
"/warnaserror:e;f;g",
}), commandLineSwitches);
ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches);
Assert.NotNull(actualWarningsAsErrors);
Assert.Equal(expectedWarningsAsErors, actualWarningsAsErrors, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Verifies that the /warnaserror switch is parsed properly when no codes are specified.
/// </summary>
[Fact]
public void ProcessWarnAsErrorSwitchEmpty()
{
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new [] { "/warnaserror" }), commandLineSwitches);
ISet<string> actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches);
Assert.NotNull(actualWarningsAsErrors);
Assert.Empty(actualWarningsAsErrors);
}
/// <summary>
/// Verifies that when the /warnasmessage switch is used with no values that an error is shown.
/// </summary>
[Fact]
public void ProcessWarnAsMessageSwitchEmpty()
{
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[] { "/warnasmessage" }), commandLineSwitches);
VerifySwitchError(commandLineSwitches, "/warnasmessage", AssemblyResources.GetString("MissingWarnAsMessageParameterError"));
}
/// <summary>
/// Verifies that the /warnasmessage switch is parsed properly when codes are specified.
/// </summary>
[Fact]
public void ProcessWarnAsMessageSwitchWithCodes()
{
ISet<string> expectedWarningsAsMessages = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a", "B", "c", "D", "e" };
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[]
{
"\"/warnasmessage: a,B ; c \"", // Leading, trailing, leading and trailing whitespace
"/warnasmessage:A,b,C", // Repeats of different case
"\"/warnasmessage:, ,,\"", // Empty items
"/nowarn:D,d;E,e", // A different source with new items and uses the short form
"/warnasmessage:a", // A different source with a single duplicate
"/warnasmessage:a,b", // A different source with multiple duplicates
}), commandLineSwitches);
ISet<string> actualWarningsAsMessages = MSBuildApp.ProcessWarnAsMessageSwitch(commandLineSwitches);
Assert.NotNull(actualWarningsAsMessages);
Assert.Equal(expectedWarningsAsMessages, actualWarningsAsMessages, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Verifies that when the /profileevaluation switch is used with no values "no-file" is specified.
/// </summary>
[Fact]
public void ProcessProfileEvaluationEmpty()
{
CommandLineSwitches commandLineSwitches = new CommandLineSwitches();
MSBuildApp.GatherCommandLineSwitches(new ArrayList(new[] { "/profileevaluation" }), commandLineSwitches);
commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.ProfileEvaluation][0].ShouldBe("no-file");
}
[Fact]
public void ProcessBooleanSwitchTest()
{
MSBuildApp.ProcessBooleanSwitch(new string[0], defaultValue: true, resourceName: null).ShouldBeTrue();
MSBuildApp.ProcessBooleanSwitch(new string[0], defaultValue: false, resourceName: null).ShouldBeFalse();
MSBuildApp.ProcessBooleanSwitch(new [] { "true" }, defaultValue: false, resourceName: null).ShouldBeTrue();
MSBuildApp.ProcessBooleanSwitch(new[] { "false" }, defaultValue: true, resourceName: null).ShouldBeFalse();
Should.Throw<CommandLineSwitchException>(() => MSBuildApp.ProcessBooleanSwitch(new[] { "invalid" }, defaultValue: true, resourceName: "InvalidRestoreValue"));
}
/// <summary>
/// Verifies that when the /profileevaluation switch is used with invalid filenames an error is shown.
/// </summary>
[MemberData(nameof(GetInvalidFilenames))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, ".NET Core 2.1+ no longer validates paths: https://github.com/dotnet/corefx/issues/27779#issuecomment-371253486")]
[Theory]
public void ProcessProfileEvaluationInvalidFilename(string filename)
{
bool enableProfiler = false;
Should.Throw(
() => MSBuildApp.ProcessProfileEvaluationSwitch(new[] {filename}, new ArrayList(), out enableProfiler),
typeof(CommandLineSwitchException));
}
public static IEnumerable<object[]> GetInvalidFilenames()
{
yield return new object[] { $"a_file_with${Path.GetInvalidFileNameChars().First()}invalid_chars" };
yield return new object[] { $"C:\\a_path\\with{Path.GetInvalidPathChars().First()}invalid\\chars" };
}
#if FEATURE_RESOURCEMANAGER_GETRESOURCESET
/// <summary>
/// Verifies that help messages are correctly formed with the right width and leading spaces.
/// </summary>
[Fact]
public void HelpMessagesAreValid()
{
ResourceManager resourceManager = new ResourceManager("MSBuild.Strings", typeof(AssemblyResources).Assembly);
const string switchLeadingSpaces = " ";
const string otherLineLeadingSpaces = " ";
const string examplesLeadingSpaces = " ";
foreach (KeyValuePair<string, string> item in resourceManager.GetResourceSet(CultureInfo.CurrentUICulture, createIfNotExists: true, tryParents: true)
.Cast<DictionaryEntry>().Where(i => i.Key is string && ((string)i.Key).StartsWith("HelpMessage_"))
.Select(i => new KeyValuePair<string, string>((string)i.Key, (string)i.Value)))
{
string[] helpMessageLines = item.Value.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < helpMessageLines.Length; i++)
{
// All lines should be 80 characters or less
Assert.True(helpMessageLines[i].Length <= 80, $"Line {i + 1} of '{item.Key}' should be no longer than 80 characters.");
string trimmedLine = helpMessageLines[i].Trim();
if (i == 0)
{
if (trimmedLine.StartsWith("-") || trimmedLine.StartsWith("@"))
{
// If the first line in a switch it needs a certain amount of leading spaces
Assert.StartsWith(switchLeadingSpaces, helpMessageLines[i]);
}
else
{
// Otherwise it should have no leading spaces because it's a section
Assert.False(helpMessageLines[i].StartsWith(" "));
}
}
else
{
// Ignore empty lines
if (!String.IsNullOrWhiteSpace(helpMessageLines[i]))
{
if (item.Key.Contains("Examples"))
{
// Examples require a certain number of leading spaces
Assert.StartsWith(examplesLeadingSpaces, helpMessageLines[i]);
}
else if (trimmedLine.StartsWith("-") || trimmedLine.StartsWith("@"))
{
// Switches require a certain number of leading spaces
Assert.StartsWith(switchLeadingSpaces, helpMessageLines[i]);
}
else
{
// All other lines require a certain number of leading spaces
Assert.StartsWith(otherLineLeadingSpaces, helpMessageLines[i]);
}
}
}
}
}
}
#endif
/// <summary>
/// Verifies that a switch collection has an error registered for the given command line arg.
/// </summary>
private void VerifySwitchError(CommandLineSwitches switches, string badCommandLineArg, string expectedMessage = null)
{
bool caughtError = false;
try
{
switches.ThrowErrors();
}
catch (CommandLineSwitchException e)
{
Assert.Equal(badCommandLineArg, e.CommandLineArg);
caughtError = true;
if (expectedMessage != null)
{
Assert.Contains(expectedMessage, e.Message);
}
// so I can see the message in NUnit's "Standard Out" window
Console.WriteLine(e.Message);
}
finally
{
Assert.True(caughtError);
}
}
}
}
| |
/*
* Copyright (c) Contributors
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
[assembly: Addin("EventRecordingModule", "0.1")]
[assembly: AddinDependency("OpenSim", "0.5")]
namespace EventRecorder
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EventRecordingModule")]
public class EventRecordingModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Name { get { return "Event Recording Module"; } }
public Type ReplaceableInterface { get { return null; } }
/// <summary>
/// Is this module enabled?
/// </summary>
public bool Enabled { get; private set; }
/// <summary>
/// Are we recording when a user logs in?
/// </summary>
public bool RecordUserLoginEvents { get; set; }
/// <summary>
/// Are we recording when a user logs out?
/// </summary>
public bool RecordUserLogoutEvents { get; set; }
/// <summary>
/// Are we recording when an avatar enters a region other than on the one they enter on login?
/// </summary>
public bool RecordUserRegionEnterEvents { get; set; }
/// <summary>
/// Are we recording user chat?
/// </summary>
public bool RecordUserChatEvents { get; set; }
/// <summary>
/// Are we recording user to user instant messages?
/// </summary>
public bool RecordUserToUserImEvents { get; set; }
/// <summary>
/// Are we recording user to group instant messages?
/// </summary>
public bool RecordUserToGroupImEvents { get; set; }
/// <summary>
/// Track the number of scenes being monitored.
/// </summary>
/// <remarks>
/// This only exists to help handle a bug in OpenSimulator 0.8 where Close() is not called on simulator
/// shutdown.
public int RegionsMonitoredCount { get; private set; }
/// <summary>
/// This only exists so that we know when all regions have initially loaded. Dumb, eh?
/// </summary>
public int RegionsLoadedCount { get; private set; }
/// <summary>
/// Used to record events.
/// </summary>
private QueueingRecorder m_recorder;
/// <summary>
/// Used to resolve UUID -> user name.
/// </summary>
private IUserManagement m_userManagementModule;
/// <summary>
/// Used to resolve UUID -> group name.
/// </summary>
private IGroupsModule m_groupsModule;
private string m_gridId;
public void Initialise(IConfigSource configSource)
{
// m_log.DebugFormat("[EVENT RECORDER]: INITIALIZED MODULE");
HashSet<string> recorders = new HashSet<string>{ "OpenSimLog", "MySQL" };
IConfig config = configSource.Configs["EventRecorder"];
if (config == null)
{
m_log.DebugFormat("[EVENT RECORDER]: No [EventRecorder] config section found");
return;
}
bool enabledInConfig = config.GetBoolean("Enabled", false);
if (!enabledInConfig)
return;
// This is not necessary for all recorders but it's cleaner to enforce upfront than potentially end up
// with a migration problem later.
if (!config.Contains("GridID"))
throw new Exception("A GridID must bs specified in the [EventRecorder] config section.");
m_gridId = config.GetString("GridID");
if (m_gridId.Length > EventRecordingModuleConstants.GridIdMaxSize)
throw new Exception(
string.Format(
"GridID [{0}] at {1} chars is longer than the maximum {2} chars",
m_gridId, m_gridId.Length, EventRecordingModuleConstants.GridIdMaxSize));
m_log.DebugFormat("[EVENT RECORDER]: GridID set to {0}", m_gridId);
string recorderName = config.GetString("Recorder");
IRecorder decoratedRecorder;
if (recorderName == "OpenSimLog")
decoratedRecorder = new OpenSimLoggingRecorder();
else if (recorderName == "MySQL")
decoratedRecorder = new MySQLRecorder();
else if (recorderName == null)
throw new Exception(
string.Format("No Recorder parameter found in [EventRecorder] config. Must be one of {0}",
string.Join(", ", recorders)));
else
throw new Exception(
string.Format(
"Recorder '{0}' is not a valid recorder name. Must be one of {1}",
recorderName, string.Join(", ", recorders)));
m_recorder = new QueueingRecorder(decoratedRecorder);
m_recorder.Initialise(configSource);
RecordUserLoginEvents = config.GetBoolean("RecordUserLoginEvents", true);
RecordUserLogoutEvents = config.GetBoolean("RecordUserLogoutEvents", true);
RecordUserRegionEnterEvents = config.GetBoolean("RecordUserRegionEnterEvents", true);
RecordUserChatEvents = config.GetBoolean("RecordUserChatEvents", false);
RecordUserToUserImEvents = config.GetBoolean("RecordUserToUserImEvents", false);
RecordUserToGroupImEvents = config.GetBoolean("RecordUserToGroupImEvents", false);
}
public void PostInitialise()
{
// m_log.DebugFormat("[EVENT RECORDER]: POST INITIALIZED MODULE");
}
public void Close()
{
// m_log.DebugFormat("[EVENT RECORDER]: CLOSED MODULE");
// DUE TO A BUG IN OPENSIMULATOR 0.8 AND BEFORE, THIS IS NOT BEING CALLED ON REGION SHUTDOWN
}
public void AddRegion(Scene scene)
{
// Console.WriteLine("[EVENT RECORDER]: ADD REGION {0}", scene.Name);
RegionsMonitoredCount++;
scene.EventManager.OnMakeRootAgent += HandleOnMakeRootAgent;
// scene.EventManager.OnMakeChildAgent
// += p
// => m_log.DebugFormat(
// "[EVENT RECORDER]: Notified of avatar {0} moving away from scene {1}", p.UUID, p.Scene.Name);
// scene.EventManager.OnClientClosed
// += (agentID, s)
// => m_log.DebugFormat(
// "[EVENT RECORDER]: Notified of avatar {0} logging out of scene {1}", agentID, s.Name);
scene.EventManager.OnClientClosed += HandleOnClientClosed;
//scene.EventManager.OnChatToClients += HandleOnChatToClients;
}
private void HandleInfoCommand(string module, string[] args)
{
ConsoleDisplayList cdl = new ConsoleDisplayList();
cdl.AddRow("Recorder", m_recorder.Name);
cdl.AddRow("Grid ID", m_gridId);
cdl.AddRow("RecordUserLoginEvents", RecordUserLoginEvents);
cdl.AddRow("RecordUserLogoutEvents", RecordUserLogoutEvents);
cdl.AddRow("RecordUserRegionEnterEvents", RecordUserRegionEnterEvents);
cdl.AddRow("RecordUserChatEvents", RecordUserChatEvents);
cdl.AddRow("RecordUserToUserImEvents", RecordUserToUserImEvents);
cdl.AddRow("RecordUserToGroupImEvents", RecordUserToGroupImEvents);
cdl.AddRow("Events queue capacity", m_recorder.Capacity);
cdl.AddRow("Events queued", m_recorder.Count);
MainConsole.Instance.Output(cdl.ToString());
}
private void HandleOnClientClosed(UUID agentId, Scene s)
{
if (!Enabled || !RecordUserLogoutEvents)
return;
ScenePresence sp = s.GetScenePresence(agentId);
if (sp == null)
{
m_log.WarnFormat(
"[EVENT RECORDER]: Received event that agent {0} had closed in {1} but no scene presence found",
agentId, s.Name);
}
if (!sp.IsChildAgent)
m_recorder.RecordEvent(new UserRegionEvent(agentId, sp.Name, "logout", m_gridId, s.Name));
}
private void HandleOnMakeRootAgent(ScenePresence sp)
{
if (!Enabled)
return;
if ((sp.TeleportFlags & Constants.TeleportFlags.ViaLogin) != 0)
{
if (RecordUserLoginEvents)
m_recorder.RecordEvent(new UserRegionEvent(sp.UUID, sp.Name, "login", m_gridId, sp.Scene.Name));
}
else
{
if (RecordUserRegionEnterEvents)
m_recorder.RecordEvent(new UserRegionEvent(sp.UUID, sp.Name, "enter", m_gridId, sp.Scene.Name));
}
sp.ControllingClient.OnChatFromClient += HandleOnChatFromClient;
sp.ControllingClient.OnInstantMessage += HandleOnInstantMessage;
}
private void HandleOnChatFromClient(object sender, OSChatMessage e)
{
if (!RecordUserChatEvents)
return;
IClientAPI client = (IClientAPI)sender;
if (ChatTypeEnum.Whisper != e.Type && ChatTypeEnum.Say != e.Type && ChatTypeEnum.Shout != e.Type)
return;
m_recorder.RecordEvent(
new UserChatEvent(
client.AgentId, client.Name, e.Position, e.Type, e.Message, e.Channel, m_gridId, client.Scene.Name));
}
private void HandleOnInstantMessage(IClientAPI client, GridInstantMessage msg)
{
// m_log.DebugFormat(
// "[EVENT RECORDER]: Handling IM from {0} {1}, type {2}",
// client.Name, client.AgentId, (InstantMessageDialog)msg.dialog);
if (msg.dialog != (byte)InstantMessageDialog.MessageFromAgent
&& msg.dialog != (byte)InstantMessageDialog.SessionSend)
return;
bool toGroup = msg.dialog == (byte)InstantMessageDialog.SessionSend;
if (toGroup)
{
if (!RecordUserToGroupImEvents)
return;
}
else
{
if (!RecordUserToUserImEvents)
return;
}
string receiverName = "UNKNOWN";
UUID receiverId;
if (toGroup)
{
receiverId = new UUID(msg.imSessionID);
if (m_groupsModule != null)
{
GroupRecord gr = m_groupsModule.GetGroupRecord(receiverId);
if (gr != null)
receiverName = gr.GroupName;
}
}
else
{
receiverId = new UUID(msg.fromAgentID);
receiverName = m_userManagementModule.GetUserName(new UUID(msg.toAgentID));
}
m_recorder.RecordEvent(
new UserImEvent(
new UUID(msg.fromAgentID), msg.fromAgentName, receiverId, receiverName,
toGroup, msg.message, m_gridId, client.Scene.Name));
}
public void RemoveRegion(Scene scene)
{
// m_log.DebugFormat("[EVENT RECORDER]: REGION {0} REMOVED", scene.RegionInfo.RegionName);
scene.EventManager.OnMakeRootAgent -= HandleOnMakeRootAgent;
scene.EventManager.OnClientClosed -= HandleOnClientClosed;
if (--RegionsMonitoredCount <= 0)
{
m_recorder.Stop();
m_log.DebugFormat("[EVENT RECORDER]: Stopped.");
}
}
public void RegionLoaded(Scene scene)
{
// m_log.DebugFormat("[EVENT RECORDER]: REGION {0} LOADED", scene.RegionInfo.RegionName);
RegionsLoadedCount++;
if (RegionsLoadedCount == RegionsMonitoredCount && !Enabled)
{
m_userManagementModule = scene.RequestModuleInterface<IUserManagement>();
if (m_userManagementModule == null)
{
m_log.ErrorFormat("[EVENT RECORDER]: IUserManagement module required but not present. Not enabling.");
return;
}
// If this scene doesn't have a groups module then we shouldn't see any group requests.
m_groupsModule = scene.RequestModuleInterface<IGroupsModule>();
MainConsole.Instance.Commands.AddCommand(
"EventRecorder", true, "evr info", "evr info", "Show event recorder info", HandleInfoCommand);
m_log.InfoFormat("[EVENT RECORDER]: Initialized with recorder {0}", m_recorder.Name);
Enabled = true;
m_recorder.Start();
}
}
}
}
| |
/*
* ParameterBuilder.cs - Implementation of the
* "System.Reflection.Emit.ParameterBuilder" class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* Contributed by Gopal.V <gopalv82@symonds.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Reflection.Emit
{
#if CONFIG_REFLECTION_EMIT
using System;
using System.Runtime.CompilerServices;
public class ParameterBuilder : IClrProgramItem, IDetachItem
{
// Internal state.
private TypeBuilder type;
private MethodBase method;
private IntPtr privateData;
// Constructor.
internal ParameterBuilder(TypeBuilder type, MethodBase method,
int position, ParameterAttributes attributes,
String strParamName)
{
// Initialize the internal state.
this.type = type;
this.method = method;
// Register this item to be detached later.
type.module.assembly.AddDetach(this);
// Create the parameter.
lock(typeof(AssemblyBuilder))
{
this.privateData = ClrParameterCreate
(((IClrProgramItem)method).ClrHandle,
position, attributes, strParamName);
}
}
// Get the token for this parameter.
public virtual ParameterToken GetToken()
{
lock(typeof(AssemblyBuilder))
{
return new ParameterToken
(AssemblyBuilder.ClrGetItemToken(privateData));
}
}
// Set a default constant value for this parameter.
public virtual void SetConstant(Object defaultValue)
{
Type paramType;
int position;
try
{
type.StartSync();
position = Position;
if(position == 0)
{
if(method is MethodInfo)
{
paramType = ((MethodInfo)method).ReturnType;
}
else
{
paramType = typeof(void);
}
}
else
{
paramType = ((method.GetParameters())[position - 1])
.ParameterType;
}
FieldBuilder.ValidateConstant(paramType, defaultValue);
lock(typeof(AssemblyBuilder))
{
FieldBuilder.ClrFieldSetConstant
(privateData, defaultValue);
}
}
finally
{
type.EndSync();
}
}
// Set a custom attribute on this parameter.
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
try
{
type.StartSync();
type.module.assembly.SetCustomAttribute
(this, customBuilder);
}
finally
{
type.EndSync();
}
}
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
try
{
type.StartSync();
type.module.assembly.SetCustomAttribute
(this, con, binaryAttribute);
}
finally
{
type.EndSync();
}
}
// Set the marshalling information for this parameter.
public virtual void SetMarshal(UnmanagedMarshal unmanagedMarshal)
{
try
{
type.StartSync();
if(unmanagedMarshal == null)
{
throw new ArgumentNullException("unmanagedMarshal");
}
lock(typeof(AssemblyBuilder))
{
FieldBuilder.ClrFieldSetMarshal
(privateData, unmanagedMarshal.ToBytes());
}
}
finally
{
type.EndSync();
}
}
// Get the attributes for this parameter.
public virtual int Attributes
{
get
{
lock(typeof(AssemblyBuilder))
{
return ClrParameterGetAttrs(privateData);
}
}
}
// Determine if this is an "in" parameter.
public bool IsIn
{
get
{
return ((Attributes & 0x0001) != 0);
}
}
// Determine if this is an "optional" parameter.
public bool IsOptional
{
get
{
return ((Attributes & 0x0004) != 0);
}
}
// Determine if this is an "out" parameter.
public bool IsOut
{
get
{
return ((Attributes & 0x0002) != 0);
}
}
// Get the name that is associated with this parameter.
public virtual String Name
{
get
{
lock(typeof(AssemblyBuilder))
{
return ClrParameterGetName(privateData);
}
}
}
// Get the position associated with this parameter.
public virtual int Position
{
get
{
lock(typeof(AssemblyBuilder))
{
return ClrParameterGetPosition(privateData);
}
}
}
// Get the CLR handle for this program item.
IntPtr IClrProgramItem.ClrHandle
{
get
{
return privateData;
}
}
// Detach this program item.
void IDetachItem.Detach()
{
privateData = IntPtr.Zero;
}
// Create a new parameter and attach it to a particular method.
[MethodImpl(MethodImplOptions.InternalCall)]
extern internal static IntPtr ClrParameterCreate
(IntPtr method, int position,
ParameterAttributes attributes, String name);
// Get the attributes associated with a parameter.
[MethodImpl(MethodImplOptions.InternalCall)]
extern internal static int ClrParameterGetAttrs(IntPtr parameter);
// Get the name associated with a parameter.
[MethodImpl(MethodImplOptions.InternalCall)]
extern internal static String ClrParameterGetName(IntPtr parameter);
// Get the position associated with a parameter.
[MethodImpl(MethodImplOptions.InternalCall)]
extern internal static int ClrParameterGetPosition(IntPtr parameter);
}; // class ParameterBuilder
#endif // CONFIG_REFLECTION_EMIT
}; // namespace System.Reflection.Emit
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
namespace System.IO.MemoryMappedFiles
{
internal partial class MemoryMappedView
{
[SecurityCritical]
public static unsafe MemoryMappedView CreateView(
SafeMemoryMappedFileHandle memMappedFileHandle, MemoryMappedFileAccess access,
long requestedOffset, long requestedSize)
{
if (requestedOffset > memMappedFileHandle._capacity)
{
throw new ArgumentOutOfRangeException("offset");
}
if (requestedSize > MaxProcessAddressSpace)
{
throw new IOException(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed);
}
if (requestedOffset + requestedSize > memMappedFileHandle._capacity)
{
throw new UnauthorizedAccessException();
}
if (memMappedFileHandle.IsClosed)
{
throw new ObjectDisposedException(typeof(MemoryMappedFile).Name);
}
if (requestedSize == MemoryMappedFile.DefaultSize)
{
requestedSize = memMappedFileHandle._capacity - requestedOffset;
}
// mmap can only create views that start at a multiple of the page size. As on Windows,
// we hide this restriction form the user by creating larger views than the user requested and hiding the parts
// that the user did not request. extraMemNeeded is the amount of extra memory we allocate before the start of the
// requested view. (mmap may round up the actual length such that it is also page-aligned; we hide that by using
// the right size and not extending the size to be page-aligned.)
ulong nativeSize;
long extraMemNeeded, nativeOffset;
long pageSize = Interop.Sys.SysConf(Interop.Sys.SysConfName._SC_PAGESIZE);
Debug.Assert(pageSize > 0);
ValidateSizeAndOffset(
requestedSize, requestedOffset, pageSize,
out nativeSize, out extraMemNeeded, out nativeOffset);
// Determine whether to create the pages as private or as shared; the former is used for copy-on-write.
Interop.Sys.MemoryMappedFlags flags =
(memMappedFileHandle._access == MemoryMappedFileAccess.CopyOnWrite || access == MemoryMappedFileAccess.CopyOnWrite) ?
Interop.Sys.MemoryMappedFlags.MAP_PRIVATE :
Interop.Sys.MemoryMappedFlags.MAP_SHARED;
// If we have a file handle, get the file descriptor from it. If the handle is null,
// we'll use an anonymous backing store for the map.
SafeFileHandle fd;
if (memMappedFileHandle._fileStream != null)
{
// Get the file descriptor from the SafeFileHandle
fd = memMappedFileHandle._fileStream.SafeFileHandle;
Debug.Assert(!fd.IsInvalid);
}
else
{
fd = new SafeFileHandle(new IntPtr(-1), false);
flags |= Interop.Sys.MemoryMappedFlags.MAP_ANONYMOUS;
}
// Nothing to do for options.DelayAllocatePages, since we're only creating the map
// with mmap when creating the view.
// Verify that the requested view permissions don't exceed the map's permissions
Interop.Sys.MemoryMappedProtections viewProtForVerification = GetProtections(access, forVerification: true);
Interop.Sys.MemoryMappedProtections mapProtForVerification = GetProtections(memMappedFileHandle._access, forVerification: true);
if ((viewProtForVerification & mapProtForVerification) != viewProtForVerification)
{
throw new UnauthorizedAccessException();
}
// viewProtections is strictly less than mapProtections, so use viewProtections for actually creating the map.
Interop.Sys.MemoryMappedProtections viewProtForCreation = GetProtections(access, forVerification: false);
// Create the map
IntPtr addr = IntPtr.Zero;
if (nativeSize > 0)
{
addr = Interop.Sys.MMap(
IntPtr.Zero, // don't specify an address; let the system choose one
nativeSize, // specify the rounded-size we computed so as to page align; size + extraMemNeeded
viewProtForCreation,
flags,
fd, // mmap adds a ref count to the fd, so there's no need to dup it.
nativeOffset); // specify the rounded-offset we computed so as to page align; offset - extraMemNeeded
}
else
{
// There are some corner cases where the .NET API allows the requested size to be zero, e.g. the caller is
// creating a map at the end of the capacity. We can't pass 0 to mmap, as that'll fail with EINVAL, nor can
// we create a map that extends beyond the end of the underlying file, as that'll fail on some platforms at the
// time of the map's creation. Instead, since there's no data to be read/written, it doesn't actually matter
// what backs the view, so we just create an anonymous mapping.
addr = Interop.Sys.MMap(
IntPtr.Zero,
1, // any length that's greater than zero will suffice
viewProtForCreation,
flags | Interop.Sys.MemoryMappedFlags.MAP_ANONYMOUS,
new SafeFileHandle(new IntPtr(-1), false), // ignore the actual fd even if there was one
0);
requestedSize = 0;
extraMemNeeded = 0;
}
if (addr == IntPtr.Zero) // note that shim uses null pointer, not non-null MAP_FAILED sentinel
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo());
}
// Based on the HandleInheritability, try to prevent the memory-mapped region
// from being inherited by a forked process
if (memMappedFileHandle._inheritability == HandleInheritability.None)
{
DisableForkingIfPossible(addr, nativeSize);
}
// Create and return the view handle
var viewHandle = new SafeMemoryMappedViewHandle(addr, ownsHandle: true);
viewHandle.Initialize((ulong)nativeSize);
return new MemoryMappedView(
viewHandle,
extraMemNeeded, // the view points to offset - extraMemNeeded, so we need to shift back by extraMemNeeded
requestedSize, // only allow access to the actual size requested
access);
}
[SecurityCritical]
public unsafe void Flush(UIntPtr capacity)
{
if (capacity == UIntPtr.Zero)
return;
byte* ptr = null;
try
{
_viewHandle.AcquirePointer(ref ptr);
int result = Interop.Sys.MSync(
(IntPtr)ptr, (ulong)capacity,
Interop.Sys.MemoryMappedSyncFlags.MS_SYNC | Interop.Sys.MemoryMappedSyncFlags.MS_INVALIDATE);
if (result < 0)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo());
}
}
finally
{
if (ptr != null)
{
_viewHandle.ReleasePointer();
}
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Attempt to prevent the specified pages from being copied into forked processes.</summary>
/// <param name="addr">The starting address.</param>
/// <param name="length">The length.</param>
private static void DisableForkingIfPossible(IntPtr addr, ulong length)
{
if (length > 0)
{
Interop.Sys.MAdvise(addr, length, Interop.Sys.MemoryAdvice.MADV_DONTFORK);
// Intentionally ignore error code -- it's just a hint and it's not supported on all systems.
}
}
/// <summary>
/// The Windows implementation limits maps to the size of the logical address space.
/// We use the same value here.
/// </summary>
private const long MaxProcessAddressSpace = 8192L * 1000 * 1000 * 1000;
/// <summary>Maps a MemoryMappedFileAccess to the associated MemoryMappedProtections.</summary>
internal static Interop.Sys.MemoryMappedProtections GetProtections(
MemoryMappedFileAccess access, bool forVerification)
{
switch (access)
{
default:
case MemoryMappedFileAccess.Read:
return Interop.Sys.MemoryMappedProtections.PROT_READ;
case MemoryMappedFileAccess.Write:
return Interop.Sys.MemoryMappedProtections.PROT_WRITE;
case MemoryMappedFileAccess.ReadWrite:
return
Interop.Sys.MemoryMappedProtections.PROT_READ |
Interop.Sys.MemoryMappedProtections.PROT_WRITE;
case MemoryMappedFileAccess.ReadExecute:
return
Interop.Sys.MemoryMappedProtections.PROT_READ |
Interop.Sys.MemoryMappedProtections.PROT_EXEC;
case MemoryMappedFileAccess.ReadWriteExecute:
return
Interop.Sys.MemoryMappedProtections.PROT_READ |
Interop.Sys.MemoryMappedProtections.PROT_WRITE |
Interop.Sys.MemoryMappedProtections.PROT_EXEC;
case MemoryMappedFileAccess.CopyOnWrite:
return forVerification ?
Interop.Sys.MemoryMappedProtections.PROT_READ :
Interop.Sys.MemoryMappedProtections.PROT_READ | Interop.Sys.MemoryMappedProtections.PROT_WRITE;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.IO;
using System.Text;
public class LegacyMissionReader : MonoBehaviour {
private FileStream fileStream;
private BinaryReader binReader;
private System.Text.Encoding enc = System.Text.Encoding.ASCII;
private LegacyMissionData legacyMissionData;
private LegacyMissionDisplay legacyMissionDisplay;
private int numFGs = 0;
// Use this for initialization
void Start () {
legacyMissionDisplay = transform.GetComponent("LegacyMissionDisplay") as LegacyMissionDisplay;
GameObject legacyMissionDataObj = GameObject.Find("LegacyMissionData");
legacyMissionData = legacyMissionDataObj.GetComponent("LegacyMissionData") as LegacyMissionData;
}
// Update is called once per frame
void Update () {
}
public void ReadFile (string fileName) {
fileStream = new FileStream(fileName, FileMode.Open);
binReader = new BinaryReader(fileStream);
ReadHeader();
ReadFGs();
fileStream.Close();
}
void ReadHeader() {
short platformID = binReader.ReadInt16();
short numFGs = binReader.ReadInt16();
short numMessages = binReader.ReadInt16();
byte unknown1 = binReader.ReadByte();
byte unknown2 = binReader.ReadByte();
// * dead bytes.
binReader.ReadBytes(12);
string iffName1 = ReadString(20);
string iffName2 = ReadString(20);
string iffName3 = ReadString(20);
string iffName4 = ReadString(20);
string regionName1 = ReadString(132);
string regionName2 = ReadString(132);
string regionName3 = ReadString(132);
string regionName4 = ReadString(132);
string globalCargo1 = ReadGlobalCargo();
string globalCargo2 = ReadGlobalCargo();
string globalCargo3 = ReadGlobalCargo();
string globalCargo4 = ReadGlobalCargo();
string globalCargo5 = ReadGlobalCargo();
string globalCargo6 = ReadGlobalCargo();
string globalCargo7 = ReadGlobalCargo();
string globalCargo8 = ReadGlobalCargo();
string globalCargo9 = ReadGlobalCargo();
string globalCargo10 = ReadGlobalCargo();
string globalCargo11 = ReadGlobalCargo();
string globalCargo12 = ReadGlobalCargo();
string globalCargo13 = ReadGlobalCargo();
string globalCargo14 = ReadGlobalCargo();
string globalCargo15 = ReadGlobalCargo();
string globalCargo16 = ReadGlobalCargo();
string globalGroupName1 = ReadGlobalGroupName();
string globalGroupName2 = ReadGlobalGroupName();
string globalGroupName3 = ReadGlobalGroupName();
string globalGroupName4 = ReadGlobalGroupName();
string globalGroupName5 = ReadGlobalGroupName();
string globalGroupName6 = ReadGlobalGroupName();
string globalGroupName7 = ReadGlobalGroupName();
string globalGroupName8 = ReadGlobalGroupName();
string globalGroupName9 = ReadGlobalGroupName();
string globalGroupName10 = ReadGlobalGroupName();
string globalGroupName11 = ReadGlobalGroupName();
string globalGroupName12 = ReadGlobalGroupName();
string globalGroupName13 = ReadGlobalGroupName();
string globalGroupName14 = ReadGlobalGroupName();
string globalGroupName15 = ReadGlobalGroupName();
string globalGroupName16 = ReadGlobalGroupName();
byte hangarEnum = binReader.ReadByte();
byte timeLimitMinutes = binReader.ReadByte();
bool endMissionWhenComplete = binReader.ReadBoolean();
byte briefingOfficer = binReader.ReadByte();
byte briefingLogo = binReader.ReadByte();
byte unknown3 = binReader.ReadByte();
byte unknown4 = binReader.ReadByte();
byte unknown5 = binReader.ReadByte();
// * Dead space
binReader.ReadBytes(4932);
legacyMissionData.headerXWA.platformID = platformID;
legacyMissionData.headerXWA.numFGs = numFGs;
legacyMissionData.headerXWA.iffName1 = iffName1;
legacyMissionData.headerXWA.iffName2 = iffName2;
legacyMissionData.headerXWA.iffName3 = iffName3;
legacyMissionData.headerXWA.iffName4 = iffName4;
legacyMissionData.headerXWA.regionName1 = regionName1;
legacyMissionData.headerXWA.regionName2 = regionName2;
legacyMissionData.headerXWA.regionName3 = regionName3;
legacyMissionData.headerXWA.regionName4 = regionName4;
legacyMissionData.headerXWA.globalCargo1 = globalCargo1;
legacyMissionData.headerXWA.globalCargo2 = globalCargo2;
legacyMissionData.headerXWA.globalCargo3 = globalCargo3;
legacyMissionData.headerXWA.globalCargo4 = globalCargo4;
legacyMissionData.headerXWA.globalCargo5 = globalCargo5;
legacyMissionData.headerXWA.globalCargo6 = globalCargo6;
legacyMissionData.headerXWA.globalCargo7 = globalCargo7;
legacyMissionData.headerXWA.globalCargo8 = globalCargo8;
legacyMissionData.headerXWA.globalCargo9 = globalCargo9;
legacyMissionData.headerXWA.globalCargo10 = globalCargo10;
legacyMissionData.headerXWA.globalCargo11 = globalCargo11;
legacyMissionData.headerXWA.globalCargo12 = globalCargo12;
legacyMissionData.headerXWA.globalCargo13 = globalCargo13;
legacyMissionData.headerXWA.globalCargo14 = globalCargo14;
legacyMissionData.headerXWA.globalCargo15 = globalCargo15;
legacyMissionData.headerXWA.globalCargo16 = globalCargo16;
legacyMissionData.headerXWA.globalGroupName1 = globalGroupName1;
legacyMissionData.headerXWA.globalGroupName2 = globalGroupName2;
legacyMissionData.headerXWA.globalGroupName3 = globalGroupName3;
legacyMissionData.headerXWA.globalGroupName4 = globalGroupName4;
legacyMissionData.headerXWA.globalGroupName5 = globalGroupName5;
legacyMissionData.headerXWA.globalGroupName6 = globalGroupName6;
legacyMissionData.headerXWA.globalGroupName7 = globalGroupName7;
legacyMissionData.headerXWA.globalGroupName8 = globalGroupName8;
legacyMissionData.headerXWA.globalGroupName9 = globalGroupName9;
legacyMissionData.headerXWA.globalGroupName10 = globalGroupName10;
legacyMissionData.headerXWA.globalGroupName11 = globalGroupName11;
legacyMissionData.headerXWA.globalGroupName12 = globalGroupName12;
legacyMissionData.headerXWA.globalGroupName13 = globalGroupName13;
legacyMissionData.headerXWA.globalGroupName14 = globalGroupName14;
legacyMissionData.headerXWA.globalGroupName15 = globalGroupName15;
legacyMissionData.headerXWA.globalGroupName16 = globalGroupName16;
}
string ReadGlobalCargo() {
string globalCargo = ReadString(64);
byte unknown1 = binReader.ReadByte();
byte unknown2 = binReader.ReadByte();
byte unknown3 = binReader.ReadByte();
byte unknown4 = binReader.ReadByte();
byte unknown5 = binReader.ReadByte();
// * dead bytes.
binReader.ReadBytes(71);
return globalCargo;
}
string ReadGlobalGroupName() {
return ReadString(87);
}
void ReadFGs() {
short numFG = legacyMissionData.headerXWA.numFGs;
Debug.Log("numFG: " + numFG);
for(int x = 0; x < legacyMissionData.headerXWA.numFGs; x++) {
FlightGroup flightGroup = CreateAndReadFG();
legacyMissionData.flightGroups.Add(flightGroup);
}
}
FlightGroup CreateAndReadFG() {
FlightGroup fg = new FlightGroup();
fg.name = ReadString(20);
fg.enableDesignation = binReader.ReadBoolean();
fg.enableDesignation2 = binReader.ReadBoolean();
fg.designationEnum = binReader.ReadByte();
fg.designationEnum2 = binReader.ReadByte();
fg.unknown1 = binReader.ReadByte();
fg.globalCargoIndex = binReader.ReadByte();
fg.globalSpecialCargoIndex = binReader.ReadByte();
// * dead bytes.
binReader.ReadBytes(13);
fg.cargo = ReadString(20);
fg.specialCargo = ReadString(20);
fg.craftRole = ReadString(20);
fg.specialCargoCraft = binReader.ReadByte();
fg.randomSpecialCargoCraft = binReader.ReadBoolean();
fg.craftType = binReader.ReadByte();
fg.numberOfCraft = binReader.ReadByte();
fg.status1Enum = binReader.ReadByte();
fg.warheadEnum = binReader.ReadByte();
fg.beamEnum = binReader.ReadByte();
fg.iff = binReader.ReadByte();
fg.team = binReader.ReadByte();
fg.groupAIEnum = binReader.ReadByte();
fg.markingsEnum = binReader.ReadByte();
fg.radioEnum = binReader.ReadByte();
fg.formationEnum = binReader.ReadByte();
fg.formationSpacing = binReader.ReadByte();
fg.globalGroup = binReader.ReadByte();
fg.leaderSpacing = binReader.ReadByte();
fg.numberOfWaves = binReader.ReadByte();
fg.unknown3 = binReader.ReadByte();
fg.playerNumber = binReader.ReadByte();
fg.arriveOnlyIfHuman = binReader.ReadBoolean();
fg.playerCraft = binReader.ReadByte();
fg.yaw = binReader.ReadByte();
fg.pitch = binReader.ReadByte();
fg.roll = binReader.ReadByte();
fg.unknown4 = binReader.ReadByte();
fg.arrivalDifficultyEnum = binReader.ReadByte();
fg.unknown5 = binReader.ReadByte();
fg.arrival1 = ReadTrigger();
fg.arrival2 = ReadTrigger();
fg.arrival1OrArrival2 = binReader.ReadBoolean();
fg.unknown6 = binReader.ReadBoolean();
fg.arrival3 = ReadTrigger();
fg.arrival4 = ReadTrigger();
fg.arrival3OrArrival4 = binReader.ReadBoolean();
fg.arrivals12OrArrivals34 = binReader.ReadBoolean();
fg.arrivalDelayMinutes = binReader.ReadByte();
fg.arrivalDelaySeconds = binReader.ReadByte();
fg.departure1 = ReadTrigger();
fg.departure2 = ReadTrigger();
fg.departure1OrDeparture2 = binReader.ReadBoolean();
fg.departureDelayMinutes = binReader.ReadByte();
fg.departureDelaySeconds = binReader.ReadByte();
fg.abortTriggerEnum = binReader.ReadByte();
fg.unknown7 = binReader.ReadByte();
fg.unknown8 = binReader.ReadByte();
fg.arrivalMothership = binReader.ReadByte();
fg.arriveViaMothership = binReader.ReadBoolean();
fg.alternateArrivalMothership = binReader.ReadByte();
fg.alternateArriveViaMothership = binReader.ReadBoolean();
fg.departureMothership = binReader.ReadByte();
fg.departViaMothership = binReader.ReadBoolean();
fg.alternateDepartureMothership = binReader.ReadByte();
fg.alternateDepartViaMothership = binReader.ReadBoolean();
fg.orders = ReadOrders(16);
fg.skip = ReadSkips(16);
fg.goalFG = ReadGoalFGs(8);
fg.startPoints = ReadWaypts(3);
fg.hyperPoint = ReadWaypt();
fg.startPointRegions = binReader.ReadBytes(3);
fg.hyperPointRegion = binReader.ReadByte();
fg.unknown16 = binReader.ReadByte();
fg.unknown17 = binReader.ReadByte();
fg.unknown18 = binReader.ReadByte();
fg.unknown19 = binReader.ReadByte();
fg.unknown20 = binReader.ReadByte();
fg.unknown21 = binReader.ReadByte();
fg.unknown22 = binReader.ReadBoolean();
fg.unknown23 = binReader.ReadByte();
fg.unknown24 = binReader.ReadByte();
fg.unknown25 = binReader.ReadByte();
fg.unknown26 = binReader.ReadByte();
fg.unknown27 = binReader.ReadByte();
fg.unknown28 = binReader.ReadByte();
fg.unknown29 = binReader.ReadBoolean();
fg.unknown30 = binReader.ReadBoolean();
fg.unknown31 = binReader.ReadBoolean();
fg.enableGlobalUnit = binReader.ReadBoolean();
fg.unknown32 = binReader.ReadByte();
fg.unknown33 = binReader.ReadByte();
fg.countermeasures = binReader.ReadByte();
fg.craftExplosionTime = binReader.ReadByte();
fg.status2 = binReader.ReadByte();
fg.globalUnit = binReader.ReadByte();
fg.optionalWarheads = binReader.ReadBytes(8);
fg.optionalBeams = binReader.ReadBytes(4);
fg.optionalCountermeasures = binReader.ReadBytes(3);
fg.optionalCraftCategory = binReader.ReadByte();
fg.optionalCraft = binReader.ReadBytes(10);
fg.numberOfOptionalCraft = binReader.ReadBytes(10);
fg.numberofOptionalCraftWaves = binReader.ReadBytes(10);
fg.pilotID = ReadString(16);;
fg.backdrop = binReader.ReadByte();
fg.unknown34 = binReader.ReadBoolean();
fg.unknown35 = binReader.ReadBoolean();
fg.unknown36 = binReader.ReadBoolean();
fg.unknown37 = binReader.ReadBoolean();
fg.unknown38 = binReader.ReadBoolean();
fg.unknown39 = binReader.ReadBoolean();
fg.unknown40 = binReader.ReadBoolean();
fg.unknown41 = binReader.ReadBoolean();
// * dead bytes.
binReader.ReadBytes(6);
return fg;
}
string ReadString(int size) {
System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] str = binReader.ReadBytes(size);
return enc.GetString(str);
}
Trigger ReadTrigger() {
Trigger trigger = new Trigger();
trigger.condition = binReader.ReadByte();
trigger.variableType = binReader.ReadByte();
trigger.variable = binReader.ReadByte();
trigger.amountEnum = binReader.ReadByte();
trigger.parameter = binReader.ReadByte();
trigger.parameter2 = binReader.ReadByte();
return new Trigger();
}
Order ReadOrder() {
Order order = new Order();
order.orderEnum = binReader.ReadByte();
order.throttle = binReader.ReadByte();
order.variable1 = binReader.ReadByte();
order.variable2 = binReader.ReadByte();
order.variable3 = binReader.ReadByte();
order.unknown9 = binReader.ReadByte(); // * retains FG Unknown numbering
order.target3TypeEnum = binReader.ReadByte(); // * VariableType)
order.target4TypeEnum = binReader.ReadByte(); // * VariableType)
order.target3 = binReader.ReadByte();
order.target4 = binReader.ReadByte();
order.target3OorTarget4 = binReader.ReadBoolean();
order.target1TypeEnum = binReader.ReadByte(); // * VariableType)
order.target1 = binReader.ReadByte();
order.target2TypeEnum = binReader.ReadByte(); // * VariableType)
order.target2 = binReader.ReadByte();
order.target1OrTarget2 = binReader.ReadBoolean();
order.speed = binReader.ReadByte();
order.waypts = ReadWaypts(8);
order.unknown10 = binReader.ReadByte();
order.unknown11 = binReader.ReadBoolean();
order.unknown12 = binReader.ReadBoolean();
order.unknown13 = binReader.ReadBoolean();
order.unknown14 = binReader.ReadBoolean();
// * dead bytes.
binReader.ReadBytes(19);
return order;
}
Order[] ReadOrders(int size) {
Order[] orders = new Order[size];
for(int index = 0; index < size; index++) {
orders[index] = ReadOrder();
}
return orders;
}
Skip ReadSkip() {
Skip skip = new Skip();
skip.trigger1 = ReadTrigger();
skip.trigger2 = ReadTrigger();
skip.trigger10Trigger2 = binReader.ReadBoolean();
// * dead bytes.
binReader.ReadBytes(1);
return skip;
}
Skip[] ReadSkips(int size) {
Skip[] skips = new Skip[size];
for(int index = 0; index < size; index++) {
skips[index] = ReadSkip();
}
return skips;
}
GoalFG ReadGoalFG() {
GoalFG goalFG = new GoalFG();
goalFG.argument = binReader.ReadByte();
goalFG.condition = binReader.ReadByte();
goalFG.amount = binReader.ReadByte();
goalFG.points = binReader.ReadSByte();
goalFG.enabled = binReader.ReadBoolean();
goalFG.team = binReader.ReadByte();
goalFG.unknown42 = binReader.ReadByte();
goalFG.parameter = binReader.ReadByte();
goalFG.activeSequence = binReader.ReadByte();
goalFG.unknown15 = binReader.ReadBoolean();
return goalFG;
}
GoalFG[] ReadGoalFGs(int size) {
GoalFG[] goalFGs = new GoalFG[size];
for(int index = 0; index < size; index++) {
goalFGs[index] = ReadGoalFG();
}
return goalFGs;
}
Waypt ReadWaypt() {
Waypt waypt = new Waypt();
waypt.x = binReader.ReadInt16();
waypt.y = binReader.ReadInt16();
waypt.z = binReader.ReadInt16();
waypt.enabled = binReader.ReadBoolean();
// * dead bytes.
binReader.ReadBytes(1);
return waypt;
}
Waypt[] ReadWaypts(int size) {
Waypt[] waypts = new Waypt[size];
for(int index = 0; index < size; index++) {
waypts[index] = ReadWaypt();
}
return new Waypt[size];
}
}
| |
// Copyright 2018 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 Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.LongRunning.Snippets
{
/// <summary>Generated snippets</summary>
public class GeneratedOperationsClientSnippets
{
/// <summary>Snippet for GetOperationAsync</summary>
public async Task GetOperationAsync()
{
// Snippet: GetOperationAsync(string,CallSettings)
// Additional: GetOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
Operation response = await operationsClient.GetOperationAsync(name);
// End snippet
}
/// <summary>Snippet for GetOperation</summary>
public void GetOperation()
{
// Snippet: GetOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
Operation response = operationsClient.GetOperation(name);
// End snippet
}
/// <summary>Snippet for GetOperationAsync</summary>
public async Task GetOperationAsync_RequestObject()
{
// Snippet: GetOperationAsync(GetOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
GetOperationRequest request = new GetOperationRequest
{
Name = "",
};
// Make the request
Operation response = await operationsClient.GetOperationAsync(request);
// End snippet
}
/// <summary>Snippet for GetOperation</summary>
public void GetOperation_RequestObject()
{
// Snippet: GetOperation(GetOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
GetOperationRequest request = new GetOperationRequest
{
Name = "",
};
// Make the request
Operation response = operationsClient.GetOperation(request);
// End snippet
}
/// <summary>Snippet for ListOperationsAsync</summary>
public async Task ListOperationsAsync()
{
// Snippet: ListOperationsAsync(string,string,string,int?,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
string filter = "";
// Make the request
PagedAsyncEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperationsAsync(name, filter);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Operation item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListOperationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListOperations</summary>
public void ListOperations()
{
// Snippet: ListOperations(string,string,string,int?,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
string filter = "";
// Make the request
PagedEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperations(name, filter);
// Iterate over all response items, lazily performing RPCs as required
foreach (Operation item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListOperationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListOperationsAsync</summary>
public async Task ListOperationsAsync_RequestObject()
{
// Snippet: ListOperationsAsync(ListOperationsRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
ListOperationsRequest request = new ListOperationsRequest
{
Name = "",
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperationsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Operation item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListOperationsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListOperations</summary>
public void ListOperations_RequestObject()
{
// Snippet: ListOperations(ListOperationsRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
ListOperationsRequest request = new ListOperationsRequest
{
Name = "",
Filter = "",
};
// Make the request
PagedEnumerable<ListOperationsResponse, Operation> response =
operationsClient.ListOperations(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Operation item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListOperationsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Operation item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Operation> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Operation item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CancelOperationAsync</summary>
public async Task CancelOperationAsync()
{
// Snippet: CancelOperationAsync(string,CallSettings)
// Additional: CancelOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
await operationsClient.CancelOperationAsync(name);
// End snippet
}
/// <summary>Snippet for CancelOperation</summary>
public void CancelOperation()
{
// Snippet: CancelOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
operationsClient.CancelOperation(name);
// End snippet
}
/// <summary>Snippet for CancelOperationAsync</summary>
public async Task CancelOperationAsync_RequestObject()
{
// Snippet: CancelOperationAsync(CancelOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
CancelOperationRequest request = new CancelOperationRequest
{
Name = "",
};
// Make the request
await operationsClient.CancelOperationAsync(request);
// End snippet
}
/// <summary>Snippet for CancelOperation</summary>
public void CancelOperation_RequestObject()
{
// Snippet: CancelOperation(CancelOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
CancelOperationRequest request = new CancelOperationRequest
{
Name = "",
};
// Make the request
operationsClient.CancelOperation(request);
// End snippet
}
/// <summary>Snippet for DeleteOperationAsync</summary>
public async Task DeleteOperationAsync()
{
// Snippet: DeleteOperationAsync(string,CallSettings)
// Additional: DeleteOperationAsync(string,CancellationToken)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
await operationsClient.DeleteOperationAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteOperation</summary>
public void DeleteOperation()
{
// Snippet: DeleteOperation(string,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
operationsClient.DeleteOperation(name);
// End snippet
}
/// <summary>Snippet for DeleteOperationAsync</summary>
public async Task DeleteOperationAsync_RequestObject()
{
// Snippet: DeleteOperationAsync(DeleteOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = await OperationsClient.CreateAsync();
// Initialize request argument(s)
DeleteOperationRequest request = new DeleteOperationRequest
{
Name = "",
};
// Make the request
await operationsClient.DeleteOperationAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteOperation</summary>
public void DeleteOperation_RequestObject()
{
// Snippet: DeleteOperation(DeleteOperationRequest,CallSettings)
// Create client
OperationsClient operationsClient = OperationsClient.Create();
// Initialize request argument(s)
DeleteOperationRequest request = new DeleteOperationRequest
{
Name = "",
};
// Make the request
operationsClient.DeleteOperation(request);
// End snippet
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
namespace ChartboostSDK {
public class CBExternal {
private static bool initialized = false;
private static string _logTag = "ChartboostSDK";
public static void Log (string message) {
if(CBSettings.isLogging() && Debug.isDebugBuild)
Debug.Log(_logTag + "/" + message);
}
private static bool checkInitialized() {
if (initialized) {
return true;
} else {
Debug.LogError("The Chartboost SDK needs to be initialized before we can show any ads");
return false;
}
}
#if UNITY_EDITOR || (!UNITY_ANDROID && !UNITY_IPHONE)
/// Initializes the Chartboost plugin.
/// This must be called before using any other Chartboost features.
public static void init() {
Log("Unity : init");
// Will verify all the id and signatures against example ones.
CBSettings.getIOSAppId ();
CBSettings.getIOSAppSecret ();
CBSettings.getAndroidAppId ();
CBSettings.getAndroidAppSecret ();
CBSettings.getAmazonAppId ();
CBSettings.getAmazonAppSecret ();
}
/// Caches an interstitial. Location is optional.
public static void cacheInterstitial(CBLocation location) {
Log("Unity : cacheInterstitial at location = " + location.ToString());
}
/// Checks for a cached an interstitial. Location is optional.
public static bool hasInterstitial(CBLocation location) {
Log("Unity : hasInterstitial at location = " + location.ToString());
return false;
}
/// Loads an interstitial. Location is optional.
public static void showInterstitial(CBLocation location) {
Log("Unity : showInterstitial at location = " + location.ToString());
}
/// Caches the more apps screen. Location is optional.
public static void cacheMoreApps(CBLocation location) {
Log("Unity : cacheMoreApps at location = " + location.ToString());
}
/// Checks to see if the more apps screen is cached. Location is optional.
public static bool hasMoreApps(CBLocation location) {
Log("Unity : hasMoreApps at location = " + location.ToString());
return false;
}
/// Shows the more apps screen. Location is optional.
public static void showMoreApps(CBLocation location) {
Log("Unity : showMoreApps at location = " + location.ToString());
}
public static void cacheInPlay(CBLocation location) {
Log("Unity : cacheInPlay at location = " + location.ToString());
}
public static bool hasInPlay(CBLocation location) {
Log("Unity : hasInPlay at location = " + location.ToString());
return false;
}
public static CBInPlay getInPlay(CBLocation location) {
Log("Unity : getInPlay at location = " + location.ToString());
return null;
}
/// Caches a rewarded video. Location is optional.
public static void cacheRewardedVideo(CBLocation location) {
Log("Unity : cacheRewardedVideo at location = " + location.ToString());
}
/// Checks for a cached a rewarded video. Location is optional.
public static bool hasRewardedVideo(CBLocation location) {
Log("Unity : hasRewardedVideo at location = " + location.ToString());
return false;
}
/// Loads a rewarded video. Location is optional.
public static void showRewardedVideo(CBLocation location) {
Log("Unity : showRewardedVideo at location = " + location.ToString());
}
// Sends back the reponse by the delegate call for ShouldDisplayInterstitial
public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) {
Log("Unity : chartBoostShouldDisplayInterstitialCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo
public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) {
Log("Unity : chartBoostShouldDisplayRewardedVideoCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayMoreApps
public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) {
Log("Unity : chartBoostShouldDisplayMoreAppsCallbackResult");
}
/// Sets the name of the game object to be used by the Chartboost iOS SDK
public static void setGameObjectName(string name) {
Log("Unity : Set Game object name for callbacks to = " + name);
}
/// Set the custom id used for rewarded video call
public static void setCustomId(string id) {
Log("Unity : setCustomId to = " + id);
}
/// Get the custom id used for rewarded video call
public static string getCustomId() {
Log("Unity : getCustomId");
return "";
}
/// Confirm if an age gate passed or failed. When specified
/// Chartboost will wait for this call before showing the ios app store
public static void didPassAgeGate(bool pass) {
Log("Unity : didPassAgeGate with value = " + pass);
}
/// Open a URL using a Chartboost Custom Scheme
public static void handleOpenURL(string url, string sourceApp) {
Log("Unity : handleOpenURL at url = " + url + " for app = " + sourceApp);
}
/// Set to true if you would like to implement confirmation for ad clicks, such as an age gate.
/// If using this feature, you should call CBBinding.didPassAgeGate() in your didClickInterstitial.
public static void setShouldPauseClickForConfirmation(bool pause) {
Log("Unity : setShouldPauseClickForConfirmation with value = " + pause);
}
/// Set to false if you want interstitials to be disabled in the first user session
public static void setShouldRequestInterstitialsInFirstSession(bool request) {
Log("Unity : setShouldRequestInterstitialsInFirstSession with value = " + request);
}
public static bool getAutoCacheAds() {
Log("Unity : getAutoCacheAds");
return false;
}
public static void setAutoCacheAds(bool autoCacheAds) {
Log("Unity : setAutoCacheAds with value = " + autoCacheAds);
}
public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) {
Log("Unity : setShouldDisplayLoadingViewForMoreApps with value = " + shouldDisplay);
}
public static void setShouldPrefetchVideoContent(bool shouldPrefetch) {
Log("Unity : setShouldPrefetchVideoContent with value = " + shouldPrefetch);
}
public static void pause(bool paused) {
Log("Unity : pause");
}
/// Shuts down the Chartboost plugin
public static void destroy() {
Log("Unity : destroy");
}
/// Used to notify Chartboost that the Android back button has been pressed
/// Returns true to indicate that Chartboost has handled the event and it should not be further processed
public static bool onBackPressed() {
Log("Unity : onBackPressed");
return true;
}
public static void trackInAppGooglePlayPurchaseEvent(string title, string description, string price, string currency, string productID, string purchaseData, string purchaseSignature) {
Log("Unity: trackInAppGooglePlayPurchaseEvent");
}
public static void trackInAppAmazonStorePurchaseEvent(string title, string description, string price, string currency, string productID, string userID, string purchaseToken) {
Log("Unity: trackInAppAmazonStorePurchaseEvent");
}
public static void trackInAppAppleStorePurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier) {
Log("Unity : trackInAppAppleStorePurchaseEvent");
}
public static bool isAnyViewVisible() {
Log("Unity : isAnyViewVisible");
return false;
}
#elif UNITY_IPHONE
[DllImport("__Internal")]
private static extern void _chartBoostInit(string appId, string appSignature);
[DllImport("__Internal")]
private static extern bool _chartBoostIsAnyViewVisible();
[DllImport("__Internal")]
private static extern void _chartBoostCacheInterstitial(string location);
[DllImport("__Internal")]
private static extern bool _chartBoostHasInterstitial(string location);
[DllImport("__Internal")]
private static extern void _chartBoostShowInterstitial(string location);
[DllImport("__Internal")]
private static extern void _chartBoostCacheRewardedVideo(string location);
[DllImport("__Internal")]
private static extern bool _chartBoostHasRewardedVideo(string location);
[DllImport("__Internal")]
private static extern void _chartBoostShowRewardedVideo(string location);
[DllImport("__Internal")]
private static extern void _chartBoostCacheMoreApps(string location);
[DllImport("__Internal")]
private static extern bool _chartBoostHasMoreApps(string location);
[DllImport("__Internal")]
private static extern void _chartBoostShowMoreApps(string location);
[DllImport("__Internal")]
private static extern void _chartBoostCacheInPlay(string location);
[DllImport("__Internal")]
private static extern bool _chartBoostHasInPlay(string location);
[DllImport("__Internal")]
private static extern IntPtr _chartBoostGetInPlay(string location);
[DllImport("__Internal")]
private static extern void _chartBoostSetCustomId(string id);
[DllImport("__Internal")]
private static extern void _chartBoostDidPassAgeGate(bool pass);
[DllImport("__Internal")]
private static extern string _chartBoostGetCustomId();
[DllImport("__Internal")]
private static extern void _chartBoostHandleOpenURL(string url, string sourceApp);
[DllImport("__Internal")]
private static extern void _chartBoostSetShouldPauseClickForConfirmation(bool pause);
[DllImport("__Internal")]
private static extern void _chartBoostSetShouldRequestInterstitialsInFirstSession(bool request);
[DllImport("__Internal")]
private static extern void _chartBoostShouldDisplayInterstitialCallbackResult(bool result);
[DllImport("__Internal")]
private static extern void _chartBoostShouldDisplayRewardedVideoCallbackResult(bool result);
[DllImport("__Internal")]
private static extern void _chartBoostShouldDisplayMoreAppsCallbackResult(bool result);
[DllImport("__Internal")]
private static extern bool _chartBoostGetAutoCacheAds();
[DllImport("__Internal")]
private static extern void _chartBoostSetAutoCacheAds(bool autoCacheAds);
[DllImport("__Internal")]
private static extern void _chartBoostSetShouldDisplayLoadingViewForMoreApps(bool shouldDisplay);
[DllImport("__Internal")]
private static extern void _chartBoostSetShouldPrefetchVideoContent(bool shouldDisplay);
[DllImport("__Internal")]
private static extern void _chartBoostTrackInAppPurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier);
[DllImport("__Internal")]
private static extern void _chartBoostSetGameObjectName(string name);
/// Initializes the Chartboost plugin.
/// This must be called before using any other Chartboost features.
public static void init() {
// get the AppID and AppSecret from CBSettings
string appID = CBSettings.getIOSAppId ();
string appSecret = CBSettings.getIOSAppSecret ();
if (Application.platform == RuntimePlatform.IPhonePlayer)
_chartBoostInit(appID, appSecret);
initialized = true;
Log("iOS : init");
}
/// Check to see if any chartboost ad or view is visible
public static bool isAnyViewVisible() {
bool handled = false;
if (!checkInitialized())
return handled;
handled = _chartBoostIsAnyViewVisible();
Log("iOS : isAnyViewVisible = " + handled );
return handled;
}
/// Caches an interstitial. Location is optional.
public static void cacheInterstitial(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostCacheInterstitial(location.ToString());
Log("iOS : cacheInterstitial at location = " + location.ToString());
}
/// Checks for a cached an interstitial. Location is optional.
public static bool hasInterstitial(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("iOS : hasInterstitial at location = " + location.ToString());
return _chartBoostHasInterstitial(location.ToString());
}
/// Loads an interstitial. Location is optional.
public static void showInterstitial(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostShowInterstitial(location.ToString());
Log("iOS : showInterstitial at location = " + location.ToString());
}
/// Caches the more apps screen. Location is optional.
public static void cacheMoreApps(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostCacheMoreApps(location.ToString());
Log("iOS : cacheMoreApps at location = " + location.ToString());
}
/// Checks to see if the more apps screen is cached. Location is optional.
public static bool hasMoreApps(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("iOS : hasMoreApps at location = " + location.ToString());
return _chartBoostHasMoreApps(location.ToString());
}
/// Shows the more apps screen. Location is optional.
public static void showMoreApps(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostShowMoreApps(location.ToString());
Log("iOS : showMoreApps at location = " + location.ToString());
}
public static void cacheInPlay(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostCacheInPlay(location.ToString());
Log("iOS : cacheInPlay at location = " + location.ToString());
}
public static bool hasInPlay(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("iOS : hasInPlay at location = " + location.ToString());
return _chartBoostHasInPlay(location.ToString());
}
public static CBInPlay getInPlay(CBLocation location) {
if (!checkInitialized())
return null;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return null;
}
IntPtr inPlayId = _chartBoostGetInPlay(location.ToString());
// No Inplay was available right now
if(inPlayId == IntPtr.Zero) {
return null;
}
CBInPlay inPlayAd = new CBInPlay(inPlayId);
Log("iOS : getInPlay at location = " + location.ToString());
return inPlayAd;
}
/// Caches a rewarded video. Location is optional.
public static void cacheRewardedVideo(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostCacheRewardedVideo(location.ToString());
Log("iOS : cacheRewardedVideo at location = " + location.ToString());
}
/// Checks for a cached a rewarded video. Location is optional.
public static bool hasRewardedVideo(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("iOS : hasRewardedVideo at location = " + location.ToString());
return _chartBoostHasRewardedVideo(location.ToString());
}
/// Loads a rewarded video. Location is optional.
public static void showRewardedVideo(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostShowRewardedVideo(location.ToString());
Log("iOS : showRewardedVideo at location = " + location.ToString());
}
// Sends back the reponse by the delegate call for ShouldDisplayInterstitial
public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) {
if (!checkInitialized())
return;
_chartBoostShouldDisplayInterstitialCallbackResult(result);
Log("iOS : chartBoostShouldDisplayInterstitialCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo
public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) {
if (!checkInitialized())
return;
_chartBoostShouldDisplayRewardedVideoCallbackResult(result);
Log("iOS : chartBoostShouldDisplayRewardedVideoCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayMoreApps
public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) {
if (!checkInitialized())
return;
_chartBoostShouldDisplayMoreAppsCallbackResult(result);
Log("iOS : chartBoostShouldDisplayMoreAppsCallbackResult");
}
/// Set the custom id used for rewarded video call
public static void setCustomId(string id) {
if (!checkInitialized())
return;
_chartBoostSetCustomId(id);
Log("iOS : setCustomId to = " + id);
}
/// Get the custom id used for rewarded video call
public static string getCustomId() {
if (!checkInitialized())
return null;
Log("iOS : getCustomId");
return _chartBoostGetCustomId();
}
/// Confirm if an age gate passed or failed. When specified
/// Chartboost will wait for this call before showing the ios app store
public static void didPassAgeGate(bool pass) {
if (!checkInitialized())
return;
_chartBoostDidPassAgeGate(pass);
Log("iOS : didPassAgeGate with value = " + pass);
}
/// Open a URL using a Chartboost Custom Scheme
public static void handleOpenURL(string url, string sourceApp) {
if (!checkInitialized())
return;
_chartBoostHandleOpenURL(url, sourceApp);
Log("iOS : handleOpenURL at url = " + url + " for app = " + sourceApp);
}
/// Set to true if you would like to implement confirmation for ad clicks, such as an age gate.
/// If using this feature, you should call CBBinding.didPassAgeGate() in your didClickInterstitial.
public static void setShouldPauseClickForConfirmation(bool pause) {
if (!checkInitialized())
return;
_chartBoostSetShouldPauseClickForConfirmation(pause);
Log("iOS : setShouldPauseClickForConfirmation with value = " + pause);
}
/// Set to false if you want interstitials to be disabled in the first user session
public static void setShouldRequestInterstitialsInFirstSession(bool request) {
if (!checkInitialized())
return;
_chartBoostSetShouldRequestInterstitialsInFirstSession(request);
Log("iOS : setShouldRequestInterstitialsInFirstSession with value = " + request);
}
/// Sets the name of the game object to be used by the Chartboost iOS SDK
public static void setGameObjectName(string name) {
_chartBoostSetGameObjectName(name);
Log("iOS : Set Game object name for callbacks to = " + name);
}
/// Check if we are autocaching ads after every show call
public static bool getAutoCacheAds() {
Log("iOS : getAutoCacheAds");
return _chartBoostGetAutoCacheAds();
}
/// Sets whether to autocache after every show call
public static void setAutoCacheAds(bool autoCacheAds) {
_chartBoostSetAutoCacheAds(autoCacheAds);
Log("iOS : Set AutoCacheAds to = " + autoCacheAds);
}
/// Sets whether to display loading view for moreapps
public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) {
_chartBoostSetShouldDisplayLoadingViewForMoreApps(shouldDisplay);
Log("iOS : Set Should Display Loading View for More Apps to = " + shouldDisplay);
}
/// Sets whether to prefetch videos or not
public static void setShouldPrefetchVideoContent(bool shouldPrefetch) {
_chartBoostSetShouldPrefetchVideoContent(shouldPrefetch);
Log("iOS : Set setShouldPrefetchVideoContent to = " + shouldPrefetch);
}
/// IAP Tracking call
public static void trackInAppAppleStorePurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier) {
_chartBoostTrackInAppPurchaseEvent(receipt, productTitle, productDescription, productPrice, productCurrency, productIdentifier);
Log("iOS : trackInAppAppleStorePurchaseEvent");
}
#elif UNITY_ANDROID
private static AndroidJavaObject _plugin;
/// Initialize the android sdk
public static void init() {
// get the AppID and AppSecret from CBSettings
string appID = CBSettings.getSelectAndroidAppId ();
string appSecret = CBSettings.getSelectAndroidAppSecret ();
// find the plugin instance
using (var pluginClass = new AndroidJavaClass("com.chartboost.sdk.unity.CBPlugin"))
_plugin = pluginClass.CallStatic<AndroidJavaObject>("instance");
_plugin.Call("init", appID, appSecret);
initialized = true;
Log("Android : init");
}
/// Check to see if any chartboost ad or view is visible
public static bool isAnyViewVisible() {
bool handled = false;
if (!checkInitialized())
return handled;
handled = _plugin.Call<bool>("isAnyViewVisible");
Log("Android : isAnyViewVisible = " + handled );
return handled;
}
/// Caches an interstitial. Location is optional.
public static void cacheInterstitial(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("cacheInterstitial", location.ToString());
Log("Android : cacheInterstitial at location = " + location.ToString());
}
/// Checks for a cached an interstitial. Location is optional.
public static bool hasInterstitial(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("Android : hasInterstitial at location = " + location.ToString());
return _plugin.Call<bool>("hasInterstitial", location.ToString());
}
/// Loads an interstitial. Location is optional.
public static void showInterstitial(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("showInterstitial", location.ToString());
Log("Android : showInterstitial at location = " + location.ToString());
}
/// Caches the more apps screen. Location is optional.
public static void cacheMoreApps(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
};
_plugin.Call("cacheMoreApps", location.ToString());
Log("Android : cacheMoreApps at location = " + location.ToString());
}
/// Checks to see if the more apps screen is cached. Location is optional.
public static bool hasMoreApps(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("Android : hasMoreApps at location = " + location.ToString());
return _plugin.Call<bool>("hasMoreApps", location.ToString());
}
/// Shows the more apps screen. Location is optional.
public static void showMoreApps(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("showMoreApps", location.ToString());
Log("Android : showMoreApps at location = " + location.ToString());
}
public static void cacheInPlay(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("cacheInPlay", location.ToString());
Log("Android : cacheInPlay at location = " + location.ToString());
}
public static bool hasInPlay(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("Android : hasInPlay at location = " + location.ToString());
return _plugin.Call<bool>("hasCachedInPlay", location.ToString());
}
public static CBInPlay getInPlay(CBLocation location) {
Log("Android : getInPlay at location = " + location.ToString());
if (!checkInitialized())
return null;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return null;
}
try
{
AndroidJavaObject androidInPlayAd = _plugin.Call<AndroidJavaObject>("getInPlay", location.ToString());
CBInPlay inPlayAd = new CBInPlay(androidInPlayAd, _plugin);
return inPlayAd;
}
catch
{
return null;
}
}
/// Caches a rewarded video.
public static void cacheRewardedVideo(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("cacheRewardedVideo", location.ToString());
Log("Android : cacheRewardedVideo at location = " + location.ToString());
}
/// Checks for a cached a rewarded video.
public static bool hasRewardedVideo(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("Android : hasRewardedVideo at location = " + location.ToString());
return _plugin.Call<bool>("hasRewardedVideo", location.ToString());
}
/// Loads a rewarded video.
public static void showRewardedVideo(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("showRewardedVideo", location.ToString());
Log("Android : showRewardedVideo at location = " + location.ToString());
}
// Sends back the reponse by the delegate call for ShouldDisplayInterstitial
public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) {
if (!checkInitialized())
return;
_plugin.Call("chartBoostShouldDisplayInterstitialCallbackResult", result);
Log("Android : chartBoostShouldDisplayInterstitialCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo
public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) {
if (!checkInitialized())
return;
_plugin.Call("chartBoostShouldDisplayRewardedVideoCallbackResult", result);
Log("Android : chartBoostShouldDisplayRewardedVideoCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayMoreApps
public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) {
if (!checkInitialized())
return;
_plugin.Call("chartBoostShouldDisplayMoreAppsCallbackResult", result);
Log("Android : chartBoostShouldDisplayMoreAppsCallbackResult");
}
public static void didPassAgeGate(bool pass) {
_plugin.Call ("didPassAgeGate",pass);
}
public static void setShouldPauseClickForConfirmation(bool shouldPause) {
_plugin.Call ("setShouldPauseClickForConfirmation",shouldPause);
}
public static String getCustomId() {
return _plugin.Call<String>("getCustomId");
}
public static void setCustomId(String customId) {
_plugin.Call("setCustomId", customId);
}
public static bool getAutoCacheAds() {
return _plugin.Call<bool>("getAutoCacheAds");
}
public static void setAutoCacheAds(bool autoCacheAds) {
_plugin.Call ("setAutoCacheAds", autoCacheAds);
}
public static void setShouldRequestInterstitialsInFirstSession(bool shouldRequest) {
_plugin.Call ("setShouldRequestInterstitialsInFirstSession", shouldRequest);
}
public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) {
_plugin.Call ("setShouldDisplayLoadingViewForMoreApps", shouldDisplay);
}
public static void setShouldPrefetchVideoContent(bool shouldPrefetch) {
_plugin.Call ("setShouldPrefetchVideoContent", shouldPrefetch);
}
/// Sets the name of the game object to be used by the Chartboost Android SDK
public static void setGameObjectName(string name) {
_plugin.Call("setGameObjectName", name);
}
/// Informs the Chartboost SDK about the lifecycle of your app
public static void pause(bool paused) {
if (!checkInitialized())
return;
_plugin.Call("pause", paused);
Log("Android : pause");
}
/// Shuts down the Chartboost plugin
public static void destroy() {
if (!checkInitialized())
return;
_plugin.Call("destroy");
initialized = false;
Log("Android : destroy");
}
/// Used to notify Chartboost that the Android back button has been pressed
/// Returns true to indicate that Chartboost has handled the event and it should not be further processed
public static bool onBackPressed() {
bool handled = false;
if (!checkInitialized())
return false;
handled = _plugin.Call<bool>("onBackPressed");
Log("Android : onBackPressed");
return handled;
}
public static void trackInAppGooglePlayPurchaseEvent(string title, string description, string price, string currency, string productID, string purchaseData, string purchaseSignature) {
Log("Android: trackInAppGooglePlayPurchaseEvent");
_plugin.Call("trackInAppGooglePlayPurchaseEvent", title,description,price,currency,productID,purchaseData,purchaseSignature);
}
public static void trackInAppAmazonStorePurchaseEvent(string title, string description, string price, string currency, string productID, string userID, string purchaseToken) {
Log("Android: trackInAppAmazonStorePurchaseEvent");
_plugin.Call("trackInAppAmazonStorePurchaseEvent", title,description,price,currency,productID,userID,purchaseToken);
}
#endif
}
}
| |
using System;
using Avalonia.Utilities;
using Avalonia.VisualTree;
namespace Avalonia.Layout
{
/// <summary>
/// Provides helper methods needed for layout.
/// </summary>
public static class LayoutHelper
{
/// <summary>
/// Epsilon value used for certain layout calculations.
/// Based on the value in WPF LayoutDoubleUtil.
/// </summary>
public static double LayoutEpsilon { get; } = 0.00000153;
/// <summary>
/// Calculates a control's size based on its <see cref="ILayoutable.Width"/>,
/// <see cref="ILayoutable.Height"/>, <see cref="ILayoutable.MinWidth"/>,
/// <see cref="ILayoutable.MaxWidth"/>, <see cref="ILayoutable.MinHeight"/> and
/// <see cref="ILayoutable.MaxHeight"/>.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="constraints">The space available for the control.</param>
/// <returns>The control's size.</returns>
public static Size ApplyLayoutConstraints(ILayoutable control, Size constraints)
{
var minmax = new MinMax(control);
return new Size(
MathUtilities.Clamp(constraints.Width, minmax.MinWidth, minmax.MaxWidth),
MathUtilities.Clamp(constraints.Height, minmax.MinHeight, minmax.MaxHeight));
}
public static Size MeasureChild(ILayoutable? control, Size availableSize, Thickness padding,
Thickness borderThickness)
{
return MeasureChild(control, availableSize, padding + borderThickness);
}
public static Size MeasureChild(ILayoutable? control, Size availableSize, Thickness padding)
{
if (control != null)
{
control.Measure(availableSize.Deflate(padding));
return control.DesiredSize.Inflate(padding);
}
return new Size(padding.Left + padding.Right, padding.Bottom + padding.Top);
}
public static Size ArrangeChild(ILayoutable? child, Size availableSize, Thickness padding, Thickness borderThickness)
{
return ArrangeChild(child, availableSize, padding + borderThickness);
}
public static Size ArrangeChild(ILayoutable? child, Size availableSize, Thickness padding)
{
child?.Arrange(new Rect(availableSize).Deflate(padding));
return availableSize;
}
/// <summary>
/// Invalidates measure for given control and all visual children recursively.
/// </summary>
public static void InvalidateSelfAndChildrenMeasure(ILayoutable control)
{
void InnerInvalidateMeasure(IVisual target)
{
if (target is ILayoutable targetLayoutable)
{
targetLayoutable.InvalidateMeasure();
}
var visualChildren = target.VisualChildren;
var visualChildrenCount = visualChildren.Count;
for (int i = 0; i < visualChildrenCount; i++)
{
IVisual child = visualChildren[i];
InnerInvalidateMeasure(child);
}
}
InnerInvalidateMeasure(control);
}
/// <summary>
/// Obtains layout scale of the given control.
/// </summary>
/// <param name="control">The control.</param>
/// <exception cref="Exception">Thrown when control has no root or returned layout scaling is invalid.</exception>
public static double GetLayoutScale(ILayoutable control)
{
var visualRoot = control.VisualRoot;
var result = (visualRoot as ILayoutRoot)?.LayoutScaling ?? 1.0;
if (result == 0 || double.IsNaN(result) || double.IsInfinity(result))
{
throw new Exception($"Invalid LayoutScaling returned from {visualRoot!.GetType()}");
}
return result;
}
/// <summary>
/// Rounds a size to integer values for layout purposes, compensating for high DPI screen
/// coordinates.
/// </summary>
/// <param name="size">Input size.</param>
/// <param name="dpiScaleX">DPI along x-dimension.</param>
/// <param name="dpiScaleY">DPI along y-dimension.</param>
/// <returns>Value of size that will be rounded under screen DPI.</returns>
/// <remarks>
/// This is a layout helper method. It takes DPI into account and also does not return
/// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper
/// associated with the UseLayoutRounding property and should not be used as a general rounding
/// utility.
/// </remarks>
public static Size RoundLayoutSize(Size size, double dpiScaleX, double dpiScaleY)
{
return new Size(RoundLayoutValue(size.Width, dpiScaleX), RoundLayoutValue(size.Height, dpiScaleY));
}
/// <summary>
/// Calculates the value to be used for layout rounding at high DPI.
/// </summary>
/// <param name="value">Input value to be rounded.</param>
/// <param name="dpiScale">Ratio of screen's DPI to layout DPI</param>
/// <returns>Adjusted value that will produce layout rounding on screen at high dpi.</returns>
/// <remarks>
/// This is a layout helper method. It takes DPI into account and also does not return
/// the rounded value if it is unacceptable for layout, e.g. Infinity or NaN. It's a helper
/// associated with the UseLayoutRounding property and should not be used as a general rounding
/// utility.
/// </remarks>
public static double RoundLayoutValue(double value, double dpiScale)
{
double newValue;
// If DPI == 1, don't use DPI-aware rounding.
if (!MathUtilities.IsOne(dpiScale))
{
newValue = Math.Round(value * dpiScale) / dpiScale;
// If rounding produces a value unacceptable to layout (NaN, Infinity or MaxValue),
// use the original value.
if (double.IsNaN(newValue) ||
double.IsInfinity(newValue) ||
MathUtilities.AreClose(newValue, double.MaxValue))
{
newValue = value;
}
}
else
{
newValue = Math.Round(value);
}
return newValue;
}
/// <summary>
/// Calculates the min and max height for a control. Ported from WPF.
/// </summary>
private readonly struct MinMax
{
public MinMax(ILayoutable e)
{
MaxHeight = e.MaxHeight;
MinHeight = e.MinHeight;
double l = e.Height;
double height = (double.IsNaN(l) ? double.PositiveInfinity : l);
MaxHeight = Math.Max(Math.Min(height, MaxHeight), MinHeight);
height = (double.IsNaN(l) ? 0 : l);
MinHeight = Math.Max(Math.Min(MaxHeight, height), MinHeight);
MaxWidth = e.MaxWidth;
MinWidth = e.MinWidth;
l = e.Width;
double width = (double.IsNaN(l) ? double.PositiveInfinity : l);
MaxWidth = Math.Max(Math.Min(width, MaxWidth), MinWidth);
width = (double.IsNaN(l) ? 0 : l);
MinWidth = Math.Max(Math.Min(MaxWidth, width), MinWidth);
}
public double MinWidth { get; }
public double MaxWidth { get; }
public double MinHeight { get; }
public double MaxHeight { get; }
}
}
}
| |
#if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2)
#define SupportCustomYieldInstruction
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using UniRx.InternalUtil;
using UnityEngine;
namespace UniRx
{
public sealed class MainThreadDispatcher : MonoBehaviour
{
public enum CullingMode
{
/// <summary>
/// Won't remove any MainThreadDispatchers.
/// </summary>
Disabled,
/// <summary>
/// Checks if there is an existing MainThreadDispatcher on Awake(). If so, the new dispatcher removes itself.
/// </summary>
Self,
/// <summary>
/// Search for excess MainThreadDispatchers and removes them all on Awake().
/// </summary>
All
}
public static CullingMode cullingMode = CullingMode.Self;
#if UNITY_EDITOR
// In UnityEditor's EditorMode can't instantiate and work MonoBehaviour.Update.
// EditorThreadDispatcher use EditorApplication.update instead of MonoBehaviour.Update.
class EditorThreadDispatcher
{
static object gate = new object();
static EditorThreadDispatcher instance;
public static EditorThreadDispatcher Instance
{
get
{
// Activate EditorThreadDispatcher is dangerous, completely Lazy.
lock (gate)
{
if (instance == null)
{
instance = new EditorThreadDispatcher();
}
return instance;
}
}
}
ThreadSafeQueueWorker editorQueueWorker = new ThreadSafeQueueWorker();
EditorThreadDispatcher()
{
UnityEditor.EditorApplication.update += Update;
}
public void Enqueue(Action<object> action, object state)
{
editorQueueWorker.Enqueue(action, state);
}
public void UnsafeInvoke(Action action)
{
try
{
action();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
public void UnsafeInvoke<T>(Action<T> action, T state)
{
try
{
action(state);
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
public void PseudoStartCoroutine(IEnumerator routine)
{
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null);
}
void Update()
{
editorQueueWorker.ExecuteAll(x => Debug.LogException(x));
}
void ConsumeEnumerator(IEnumerator routine)
{
if (routine.MoveNext())
{
var current = routine.Current;
if (current == null)
{
goto ENQUEUE;
}
var type = current.GetType();
if (type == typeof(WWW))
{
var www = (WWW)current;
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitWWW(www, routine)), null);
return;
}
else if (type == typeof(AsyncOperation))
{
var asyncOperation = (AsyncOperation)current;
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitAsyncOperation(asyncOperation, routine)), null);
return;
}
else if (type == typeof(WaitForSeconds))
{
var waitForSeconds = (WaitForSeconds)current;
var accessor = typeof(WaitForSeconds).GetField("m_Seconds", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic);
var second = (float)accessor.GetValue(waitForSeconds);
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitForSeconds(second, routine)), null);
return;
}
else if (type == typeof(Coroutine))
{
Debug.Log("Can't wait coroutine on UnityEditor");
goto ENQUEUE;
}
#if SupportCustomYieldInstruction
else if (current is IEnumerator)
{
var enumerator = (IEnumerator)current;
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapEnumerator(enumerator, routine)), null);
return;
}
#endif
ENQUEUE:
editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null); // next update
}
}
IEnumerator UnwrapWaitWWW(WWW www, IEnumerator continuation)
{
while (!www.isDone)
{
yield return null;
}
ConsumeEnumerator(continuation);
}
IEnumerator UnwrapWaitAsyncOperation(AsyncOperation asyncOperation, IEnumerator continuation)
{
while (!asyncOperation.isDone)
{
yield return null;
}
ConsumeEnumerator(continuation);
}
IEnumerator UnwrapWaitForSeconds(float second, IEnumerator continuation)
{
var startTime = DateTimeOffset.UtcNow;
while (true)
{
yield return null;
var elapsed = (DateTimeOffset.UtcNow - startTime).TotalSeconds;
if (elapsed >= second)
{
break;
}
};
ConsumeEnumerator(continuation);
}
IEnumerator UnwrapEnumerator(IEnumerator enumerator, IEnumerator continuation)
{
while (enumerator.MoveNext())
{
yield return null;
}
ConsumeEnumerator(continuation);
}
}
#endif
/// <summary>Dispatch Asyncrhonous action.</summary>
public static void Post(Action<object> action, object state)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; }
#endif
var dispatcher = Instance;
if (!isQuitting && !object.ReferenceEquals(dispatcher, null))
{
dispatcher.queueWorker.Enqueue(action, state);
}
}
/// <summary>Dispatch Synchronous action if possible.</summary>
public static void Send(Action<object> action, object state)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; }
#endif
if (mainThreadToken != null)
{
try
{
action(state);
}
catch (Exception ex)
{
var dispatcher = MainThreadDispatcher.Instance;
if (dispatcher != null)
{
dispatcher.unhandledExceptionCallback(ex);
}
}
}
else
{
Post(action, state);
}
}
/// <summary>Run Synchronous action.</summary>
public static void UnsafeSend(Action action)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action); return; }
#endif
try
{
action();
}
catch (Exception ex)
{
var dispatcher = MainThreadDispatcher.Instance;
if (dispatcher != null)
{
dispatcher.unhandledExceptionCallback(ex);
}
}
}
/// <summary>Run Synchronous action.</summary>
public static void UnsafeSend<T>(Action<T> action, T state)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action, state); return; }
#endif
try
{
action(state);
}
catch (Exception ex)
{
var dispatcher = MainThreadDispatcher.Instance;
if (dispatcher != null)
{
dispatcher.unhandledExceptionCallback(ex);
}
}
}
/// <summary>ThreadSafe StartCoroutine.</summary>
public static void SendStartCoroutine(IEnumerator routine)
{
if (mainThreadToken != null)
{
StartCoroutine(routine);
}
else
{
#if UNITY_EDITOR
// call from other thread
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (!isQuitting && !object.ReferenceEquals(dispatcher, null))
{
dispatcher.queueWorker.Enqueue(_ =>
{
var dispacher = Instance;
if (dispacher != null)
{
(dispacher as MonoBehaviour).StartCoroutine(routine);
}
}, null);
}
}
}
public static void StartUpdateMicroCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
dispatcher.updateMicroCoroutine.AddCoroutine(routine);
}
}
public static void StartFixedUpdateMicroCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
dispatcher.fixedUpdateMicroCoroutine.AddCoroutine(routine);
}
}
public static void StartEndOfFrameMicroCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
dispatcher.endOfFrameMicroCoroutine.AddCoroutine(routine);
}
}
new public static Coroutine StartCoroutine(IEnumerator routine)
{
#if UNITY_EDITOR
if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return null; }
#endif
var dispatcher = Instance;
if (dispatcher != null)
{
return (dispatcher as MonoBehaviour).StartCoroutine(routine);
}
else
{
return null;
}
}
public static void RegisterUnhandledExceptionCallback(Action<Exception> exceptionCallback)
{
if (exceptionCallback == null)
{
// do nothing
Instance.unhandledExceptionCallback = Stubs<Exception>.Ignore;
}
else
{
Instance.unhandledExceptionCallback = exceptionCallback;
}
}
ThreadSafeQueueWorker queueWorker = new ThreadSafeQueueWorker();
Action<Exception> unhandledExceptionCallback = ex => Debug.LogException(ex); // default
MicroCoroutine updateMicroCoroutine = null;
int updateCountForRefresh = 0;
const int UpdateRefreshCycle = 79;
MicroCoroutine fixedUpdateMicroCoroutine = null;
int fixedUpdateCountForRefresh = 0;
const int FixedUpdateRefreshCycle = 73;
MicroCoroutine endOfFrameMicroCoroutine = null;
int endOfFrameCountForRefresh = 0;
const int EndOfFrameRefreshCycle = 71;
static MainThreadDispatcher instance;
static bool initialized;
static bool isQuitting = false;
public static string InstanceName
{
get
{
if (instance == null)
{
throw new NullReferenceException("MainThreadDispatcher is not initialized.");
}
return instance.name;
}
}
public static bool IsInitialized
{
get { return initialized && instance != null; }
}
[ThreadStatic]
static object mainThreadToken;
static MainThreadDispatcher Instance
{
get
{
Initialize();
return instance;
}
}
public static void Initialize()
{
if (!initialized)
{
#if UNITY_EDITOR
// Don't try to add a GameObject when the scene is not playing. Only valid in the Editor, EditorView.
if (!ScenePlaybackDetector.IsPlaying) return;
#endif
MainThreadDispatcher dispatcher = null;
try
{
dispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>();
}
catch
{
// Throw exception when calling from a worker thread.
var ex = new Exception("UniRx requires a MainThreadDispatcher component created on the main thread. Make sure it is added to the scene before calling UniRx from a worker thread.");
UnityEngine.Debug.LogException(ex);
throw ex;
}
if (isQuitting)
{
// don't create new instance after quitting
// avoid "Some objects were not cleaned up when closing the scene find target" error.
return;
}
if (dispatcher == null)
{
instance = new GameObject("MainThreadDispatcher").AddComponent<MainThreadDispatcher>();
}
else
{
instance = dispatcher;
}
DontDestroyOnLoad(instance);
mainThreadToken = new object();
initialized = true;
}
}
void Awake()
{
if (instance == null)
{
instance = this;
mainThreadToken = new object();
initialized = true;
StartCoroutine(RunUpdateMicroCoroutine());
StartCoroutine(RunFixedUpdateMicroCoroutine());
StartCoroutine(RunEndOfFrameMicroCoroutine());
// Added for consistency with Initialize()
DontDestroyOnLoad(gameObject);
}
else
{
if (cullingMode == CullingMode.Self)
{
Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Removing myself...");
// Destroy this dispatcher if there's already one in the scene.
DestroyDispatcher(this);
}
else if (cullingMode == CullingMode.All)
{
Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Cleaning up all excess dispatchers...");
CullAllExcessDispatchers();
}
else
{
Debug.LogWarning("There is already a MainThreadDispatcher in the scene.");
}
}
}
IEnumerator RunUpdateMicroCoroutine()
{
this.updateMicroCoroutine = new MicroCoroutine(
() =>
{
if (updateCountForRefresh > UpdateRefreshCycle)
{
updateCountForRefresh = 0;
return true;
}
else
{
return false;
}
},
ex => unhandledExceptionCallback(ex));
while (true)
{
yield return null;
updateCountForRefresh++;
updateMicroCoroutine.Run();
}
}
IEnumerator RunFixedUpdateMicroCoroutine()
{
this.fixedUpdateMicroCoroutine = new MicroCoroutine(
() =>
{
if (fixedUpdateCountForRefresh > FixedUpdateRefreshCycle)
{
fixedUpdateCountForRefresh = 0;
return true;
}
else
{
return false;
}
},
ex => unhandledExceptionCallback(ex));
while (true)
{
yield return YieldInstructionCache.WaitForFixedUpdate;
fixedUpdateCountForRefresh++;
fixedUpdateMicroCoroutine.Run();
}
}
IEnumerator RunEndOfFrameMicroCoroutine()
{
this.endOfFrameMicroCoroutine = new MicroCoroutine(
() =>
{
if (endOfFrameCountForRefresh > EndOfFrameRefreshCycle)
{
endOfFrameCountForRefresh = 0;
return true;
}
else
{
return false;
}
},
ex => unhandledExceptionCallback(ex));
while (true)
{
yield return YieldInstructionCache.WaitForEndOfFrame;
endOfFrameCountForRefresh++;
endOfFrameMicroCoroutine.Run();
}
}
static void DestroyDispatcher(MainThreadDispatcher aDispatcher)
{
if (aDispatcher != instance)
{
// Try to remove game object if it's empty
var components = aDispatcher.gameObject.GetComponents<Component>();
if (aDispatcher.gameObject.transform.childCount == 0 && components.Length == 2)
{
if (components[0] is Transform && components[1] is MainThreadDispatcher)
{
Destroy(aDispatcher.gameObject);
}
}
else
{
// Remove component
MonoBehaviour.Destroy(aDispatcher);
}
}
}
public static void CullAllExcessDispatchers()
{
var dispatchers = GameObject.FindObjectsOfType<MainThreadDispatcher>();
for (int i = 0; i < dispatchers.Length; i++)
{
DestroyDispatcher(dispatchers[i]);
}
}
void OnDestroy()
{
if (instance == this)
{
instance = GameObject.FindObjectOfType<MainThreadDispatcher>();
initialized = instance != null;
/*
// Although `this` still refers to a gameObject, it won't be found.
var foundDispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>();
if (foundDispatcher != null)
{
// select another game object
Debug.Log("new instance: " + foundDispatcher.name);
instance = foundDispatcher;
initialized = true;
}
*/
}
}
void Update()
{
if (update != null)
{
try
{
update.OnNext(Unit.Default);
}
catch (Exception ex)
{
unhandledExceptionCallback(ex);
}
}
queueWorker.ExecuteAll(unhandledExceptionCallback);
}
// for Lifecycle Management
Subject<Unit> update;
public static IObservable<Unit> UpdateAsObservable()
{
return Instance.update ?? (Instance.update = new Subject<Unit>());
}
Subject<Unit> lateUpdate;
void LateUpdate()
{
if (lateUpdate != null) lateUpdate.OnNext(Unit.Default);
}
public static IObservable<Unit> LateUpdateAsObservable()
{
return Instance.lateUpdate ?? (Instance.lateUpdate = new Subject<Unit>());
}
Subject<bool> onApplicationFocus;
void OnApplicationFocus(bool focus)
{
if (onApplicationFocus != null) onApplicationFocus.OnNext(focus);
}
public static IObservable<bool> OnApplicationFocusAsObservable()
{
return Instance.onApplicationFocus ?? (Instance.onApplicationFocus = new Subject<bool>());
}
Subject<bool> onApplicationPause;
void OnApplicationPause(bool pause)
{
if (onApplicationPause != null) onApplicationPause.OnNext(pause);
}
public static IObservable<bool> OnApplicationPauseAsObservable()
{
return Instance.onApplicationPause ?? (Instance.onApplicationPause = new Subject<bool>());
}
Subject<Unit> onApplicationQuit;
void OnApplicationQuit()
{
isQuitting = true;
if (onApplicationQuit != null) onApplicationQuit.OnNext(Unit.Default);
}
public static IObservable<Unit> OnApplicationQuitAsObservable()
{
return Instance.onApplicationQuit ?? (Instance.onApplicationQuit = new Subject<Unit>());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlatRedBall.Graphics;
using Microsoft.Xna.Framework.Graphics;
using FlatRedBall;
using Microsoft.Xna.Framework;
using FlatRedBall.Content;
using FlatRedBall.Content.Scene;
using FlatRedBall.IO;
using FlatRedBall.Input;
using FlatRedBall.Debugging;
using FlatRedBall.Math;
using TMXGlueLib.DataTypes;
namespace FlatRedBall.TileGraphics
{
public enum SortAxis
{
None,
X,
Y
}
public class MapDrawableBatch : PositionedObject, IVisible, IDrawableBatch
{
#region Fields
protected Tileset mTileset;
#region XML Docs
/// <summary>
/// The effect used to draw. Shared by all instances for performance reasons
/// </summary>
#endregion
private static BasicEffect mBasicEffect;
private static AlphaTestEffect mAlphaTestEffect;
/// <summary>
/// The vertices used to draw the map.
/// </summary>
/// <remarks>
/// Coordinate order is:
/// 3 2
///
/// 0 1
/// </remarks>
protected VertexPositionTexture[] mVertices;
protected Texture2D mTexture;
#region XML Docs
/// <summary>
/// The indices to draw the shape
/// </summary>
#endregion
protected int[] mIndices;
Dictionary<string, List<int>> mNamedTileOrderedIndexes = new Dictionary<string, List<int>>();
private int mCurrentNumberOfTiles = 0;
private SortAxis mSortAxis;
#endregion
#region Properties
public List<TMXGlueLib.DataTypes.NamedValue> Properties
{
get;
private set;
} = new List<TMXGlueLib.DataTypes.NamedValue>();
public SortAxis SortAxis
{
get
{
return mSortAxis;
}
set
{
mSortAxis = value;
}
}
#region XML Docs
/// <summary>
/// Here we tell the engine if we want this batch
/// updated every frame. Since we have no updating to
/// do though, we will set this to false
/// </summary>
#endregion
public bool UpdateEveryFrame
{
get { return true; }
}
public float RenderingScale
{
get;
set;
}
public Dictionary<string, List<int>> NamedTileOrderedIndexes
{
get
{
return mNamedTileOrderedIndexes;
}
}
public bool Visible
{
get;
set;
}
public bool ZBuffered
{
get;
set;
}
public int QuadCount
{
get
{
return mVertices.Length / 4;
}
}
public VertexPositionTexture[] Vertices
{
get
{
return mVertices;
}
}
public Texture2D Texture
{
get
{
return mTexture;
}
}
// Doing these properties this way lets me avoid a computational step of 1 - ParallaxMultiplier in the Update() function
// To explain the get & set values, algebra:
// if _parallaxMultiplier = 1 - value (set)
// then _parallaxMultiplier - 1 = -value
// so -(_parallaxMultiplier - 1) = value
// thus -_parallaxMultiplier + 1 = value (get)
private float _parallaxMultiplierX;
public float ParallaxMultiplierX
{
get { return -_parallaxMultiplierX + 1; }
set { _parallaxMultiplierX = 1 - value; }
}
private float _parallaxMultiplierY;
public float ParallaxMultiplierY
{
get { return -_parallaxMultiplierY + 1; }
set { _parallaxMultiplierY = 1 - value; }
}
#endregion
#region Constructor / Initialization
// this exists purely for Clone
public MapDrawableBatch()
{
}
public MapDrawableBatch(int numberOfTiles, Texture2D texture)
: base()
{
if (texture == null)
throw new ArgumentNullException("texture");
Visible = true;
InternalInitialize();
mTexture = texture;
mVertices = new VertexPositionTexture[4 * numberOfTiles];
mIndices = new int[6 * numberOfTiles];
}
#region XML Docs
/// <summary>
/// Create and initialize all assets
/// </summary>
#endregion
public MapDrawableBatch(int numberOfTiles, int textureTileDimensionWidth, int textureTileDimensionHeight, Texture2D texture)
: base()
{
if (texture == null)
throw new ArgumentNullException("texture");
Visible = true;
InternalInitialize();
mTexture = texture;
mVertices = new VertexPositionTexture[4 * numberOfTiles];
mIndices = new int[6 * numberOfTiles];
mTileset = new Tileset(texture, textureTileDimensionWidth, textureTileDimensionHeight);
}
//public MapDrawableBatch(int mapWidth, int mapHeight, float mapTileDimension, int textureTileDimension, string tileSetFilename)
// : base()
//{
// InternalInitialize();
// mTileset = new Tileset(tileSetFilename, textureTileDimension);
// mMapWidth = mapWidth;
// mMapHeight = mapHeight;
// int numberOfTiles = mapWidth * mapHeight;
// // the number of vertices is 4 times the number of tiles (each tile gets 4 vertices)
// mVertices = new VertexPositionTexture[4 * numberOfTiles];
// // the number of indices is 6 times the number of tiles
// mIndices = new short[6 * numberOfTiles];
// for(int i = 0; i < mapHeight; i++)
// {
// for (int j = 0; j < mapWidth; j++)
// {
// int currentTile = mapHeight * i + j;
// int currentVertex = currentTile * 4;
// float xOffset = j * mapTileDimension;
// float yOffset = i * mapTileDimension;
// int currentIndex = currentTile * 6; // 6 indices per tile
// // TEMP
// Vector2[] coords = mTileset.GetTextureCoordinateVectorsOfTextureIndex(new Random().Next()%4);
// // END TEMP
// // create vertices
// mVertices[currentVertex + 0] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + 0f, 0f), coords[0]);
// mVertices[currentVertex + 1] = new VertexPositionTexture(new Vector3(xOffset + mapTileDimension, yOffset + 0f, 0f), coords[1]);
// mVertices[currentVertex + 2] = new VertexPositionTexture(new Vector3(xOffset + mapTileDimension, yOffset + mapTileDimension, 0f), coords[2]);
// mVertices[currentVertex + 3] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + mapTileDimension, 0f), coords[3]);
// // create indices
// mIndices[currentIndex + 0] = (short)(currentVertex + 0);
// mIndices[currentIndex + 1] = (short)(currentVertex + 1);
// mIndices[currentIndex + 2] = (short)(currentVertex + 2);
// mIndices[currentIndex + 3] = (short)(currentVertex + 0);
// mIndices[currentIndex + 4] = (short)(currentVertex + 2);
// mIndices[currentIndex + 5] = (short)(currentVertex + 3);
// mCurrentNumberOfTiles++;
// }
// }
// mTexture = FlatRedBallServices.Load<Texture2D>(@"content/tiles");
//}
void InternalInitialize()
{
// We're going to share these because creating effects is slow...
// But is this okay if we tombstone?
if (mBasicEffect == null)
{
mBasicEffect = new BasicEffect(FlatRedBallServices.GraphicsDevice);
mBasicEffect.VertexColorEnabled = false;
mBasicEffect.TextureEnabled = true;
}
if (mAlphaTestEffect == null)
{
mAlphaTestEffect = new AlphaTestEffect(FlatRedBallServices.GraphicsDevice);
mAlphaTestEffect.Alpha = 1;
mAlphaTestEffect.VertexColorEnabled = false;
}
RenderingScale = 1;
}
#endregion
#region Methods
public void AddToManagers()
{
SpriteManager.AddDrawableBatch(this);
//SpriteManager.AddPositionedObject(mMapBatch);
}
public void AddToManagers(Layer layer)
{
SpriteManager.AddToLayer(this, layer);
}
public static MapDrawableBatch FromScnx(string sceneFileName, string contentManagerName, bool verifySameTexturePerLayer)
{
// TODO: This line crashes when the path is already absolute!
string absoluteFileName = FileManager.MakeAbsolute(sceneFileName);
// TODO: The exception doesn't make sense when the file type is wrong.
SceneSave saveInstance = SceneSave.FromFile(absoluteFileName);
int startingIndex = 0;
string oldRelativeDirectory = FileManager.RelativeDirectory;
FileManager.RelativeDirectory = FileManager.GetDirectory(absoluteFileName);
// get the list of sprites from our map file
List<SpriteSave> spriteSaveList = saveInstance.SpriteList;
// we use the sprites as defined in the scnx file to create and draw the map.
MapDrawableBatch mMapBatch = FromSpriteSaves(spriteSaveList, startingIndex, spriteSaveList.Count, contentManagerName, verifySameTexturePerLayer);
FileManager.RelativeDirectory = oldRelativeDirectory;
// temp
//mMapBatch = new MapDrawableBatch(32, 32, 32f, 64, @"content/tiles");
return mMapBatch;
}
/* This creates a MapDrawableBatch (MDB) from the list of sprites provided to us by the FlatRedBall (FRB) Scene XML (scnx) file. */
public static MapDrawableBatch FromSpriteSaves(List<SpriteSave> spriteSaveList, int startingIndex, int count, string contentManagerName, bool verifySameTexturesPerLayer)
{
#if DEBUG
if (verifySameTexturesPerLayer)
{
VerifySingleTexture(spriteSaveList, startingIndex, count);
}
#endif
// We got it! We are going to make some assumptions:
// First we need the texture. We'll assume all Sprites
// use the same texture:
// TODO: I (Bryan) really HATE this assumption. But it will work for now.
SpriteSave firstSprite = spriteSaveList[startingIndex];
// This is the file name of the texture, but the file name is relative to the .scnx location
string textureRelativeToScene = firstSprite.Texture;
// so we load the texture
Texture2D texture = FlatRedBallServices.Load<Texture2D>(textureRelativeToScene, contentManagerName);
if (!MathFunctions.IsPowerOfTwo(texture.Width) || !MathFunctions.IsPowerOfTwo(texture.Height))
{
throw new Exception("The dimensions of the texture file " + texture.Name + " are not power of 2!");
}
// Assume all the dimensions of the textures are the same. I.e. all tiles use the same texture width and height.
// This assumption is safe for Iso and Ortho tile maps.
int tileFileDimensionsWidth = 0;
int tileFileDimensionsHeight = 0;
if (spriteSaveList.Count > startingIndex)
{
SpriteSave s = spriteSaveList[startingIndex];
// deduce the dimensionality of the tile from the texture coordinates
tileFileDimensionsWidth = (int)System.Math.Round((double)((s.RightTextureCoordinate - s.LeftTextureCoordinate) * texture.Width));
tileFileDimensionsHeight = (int)System.Math.Round((double)((s.BottomTextureCoordinate - s.TopTextureCoordinate) * texture.Height));
}
// alas, we create the MDB
MapDrawableBatch mMapBatch = new MapDrawableBatch(count, tileFileDimensionsWidth, tileFileDimensionsHeight, texture);
int lastIndexExclusive = startingIndex + count;
for (int i = startingIndex; i < lastIndexExclusive; i++)
{
SpriteSave spriteSave = spriteSaveList[i];
// We don't want objects within the IDB to have a different Z than the IDB itself
// (if possible) because that makes the IDB behave differently when using sorting vs.
// the zbuffer.
const bool setZTo0 = true;
mMapBatch.Paste(spriteSave, setZTo0);
}
return mMapBatch;
}
public MapDrawableBatch Clone()
{
return base.Clone<MapDrawableBatch>();
}
// Bring the texture coordinates in to adjust for rendering issues on dx9/ogl
public const float CoordinateAdjustment = .00002f;
internal static MapDrawableBatch FromReducedLayer(TMXGlueLib.DataTypes.ReducedLayerInfo reducedLayerInfo, LayeredTileMap owner, TMXGlueLib.DataTypes.ReducedTileMapInfo rtmi, string contentManagerName)
{
int tileDimensionWidth = reducedLayerInfo.TileWidth;
int tileDimensionHeight = reducedLayerInfo.TileHeight;
float quadWidth = reducedLayerInfo.TileWidth;
float quadHeight = reducedLayerInfo.TileHeight;
string textureName = reducedLayerInfo.Texture;
#if IOS || ANDROID
textureName = textureName.ToLowerInvariant();
#endif
Texture2D texture = FlatRedBallServices.Load<Texture2D>(textureName, contentManagerName);
MapDrawableBatch toReturn = new MapDrawableBatch(reducedLayerInfo.Quads.Count, tileDimensionWidth, tileDimensionHeight, texture);
toReturn.Name = reducedLayerInfo.Name;
Vector3 position = new Vector3();
Vector2 tileDimensions = new Vector2(quadWidth, quadHeight);
IEnumerable<TMXGlueLib.DataTypes.ReducedQuadInfo> quads = null;
if (rtmi.NumberCellsWide > rtmi.NumberCellsTall)
{
quads = reducedLayerInfo.Quads.OrderBy(item => item.LeftQuadCoordinate);
toReturn.mSortAxis = SortAxis.X;
}
else
{
quads = reducedLayerInfo.Quads.OrderBy(item => item.BottomQuadCoordinate);
toReturn.mSortAxis = SortAxis.Y;
}
foreach (var quad in quads)
{
position.X = quad.LeftQuadCoordinate;
position.Y = quad.BottomQuadCoordinate;
// The Z of the quad should be relative to this layer, not absolute Z values.
// A multi-layer map will offset the individual layer Z values, the quads should have a Z of 0.
// position.Z = reducedLayerInfo.Z;
var textureValues = new Vector4();
textureValues.X = CoordinateAdjustment + (float)quad.LeftTexturePixel / (float)texture.Width; // Left
textureValues.Y = -CoordinateAdjustment + (float)(quad.LeftTexturePixel + tileDimensionWidth) / (float)texture.Width; // Right
textureValues.Z = CoordinateAdjustment + (float)quad.TopTexturePixel / (float)texture.Height; // Top
textureValues.W = -CoordinateAdjustment + (float)(quad.TopTexturePixel + tileDimensionHeight) / (float)texture.Height; // Bottom
// pad before doing any rotations/flipping
const bool pad = true;
if (pad)
{
const float amountToAdd = .0000001f;
textureValues.X += amountToAdd; // Left
textureValues.Y -= amountToAdd; // Right
textureValues.Z += amountToAdd; // Top
textureValues.W -= amountToAdd; // Bottom
}
if ((quad.FlipFlags & TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedHorizontallyFlag) == TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedHorizontallyFlag)
{
var temp = textureValues.Y;
textureValues.Y = textureValues.X;
textureValues.X = temp;
}
if ((quad.FlipFlags & TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedVerticallyFlag) == TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedVerticallyFlag)
{
var temp = textureValues.Z;
textureValues.Z = textureValues.W;
textureValues.W = temp;
}
int tileIndex = toReturn.AddTile(position, tileDimensions,
//quad.LeftTexturePixel, quad.TopTexturePixel, quad.LeftTexturePixel + tileDimensionWidth, quad.TopTexturePixel + tileDimensionHeight);
textureValues);
if ((quad.FlipFlags & TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedDiagonallyFlag) == TMXGlueLib.DataTypes.ReducedQuadInfo.FlippedDiagonallyFlag)
{
toReturn.ApplyDiagonalFlip(tileIndex);
}
if (quad.QuadSpecificProperties != null)
{
var listToAdd = quad.QuadSpecificProperties.ToList();
listToAdd.Add(new NamedValue { Name = "Name", Value = quad.Name });
owner.Properties.Add(quad.Name, listToAdd);
}
toReturn.RegisterName(quad.Name, tileIndex);
}
return toReturn;
}
public void Paste(Sprite sprite)
{
Paste(sprite, false);
}
public int Paste(Sprite sprite, bool setZTo0)
{
// here we have the Sprite's X and Y in absolute coords as well as its texture coords
// NOTE: I appended the Z coordinate for the sake of iso maps. This SHOULDN'T have an effect on the ortho maps since I believe the
// TMX->SCNX tool sets all z to zero.
// The AddTile method expects the bottom-left corner
float x = sprite.X - sprite.ScaleX;
float y = sprite.Y - sprite.ScaleY;
float z = sprite.Z;
if (setZTo0)
{
z = 0;
}
float width = 2f * sprite.ScaleX; // w
float height = 2f * sprite.ScaleY; // z
float topTextureCoordinate = sprite.TopTextureCoordinate;
float bottomTextureCoordinate = sprite.BottomTextureCoordinate;
float leftTextureCoordinate = sprite.LeftTextureCoordinate;
float rightTextureCoordinate = sprite.RightTextureCoordinate;
int tileIndex = mCurrentNumberOfTiles;
RegisterName(sprite.Name, tileIndex);
// add the textured tile to our map so that we may draw it.
return AddTile(new Vector3(x, y, z),
new Vector2(width, height),
new Vector4(leftTextureCoordinate, rightTextureCoordinate, topTextureCoordinate, bottomTextureCoordinate));
}
public void Paste(SpriteSave spriteSave)
{
Paste(spriteSave, false);
}
public int Paste(SpriteSave spriteSave, bool setZTo0)
{
// here we have the Sprite's X and Y in absolute coords as well as its texture coords
// NOTE: I appended the Z coordinate for the sake of iso maps. This SHOULDN'T have an effect on the ortho maps since I believe the
// TMX->SCNX tool sets all z to zero.
// The AddTile method expects the bottom-left corner
float x = spriteSave.X - spriteSave.ScaleX;
float y = spriteSave.Y - spriteSave.ScaleY;
float z = spriteSave.Z;
if (setZTo0)
{
z = 0;
}
float width = 2f * spriteSave.ScaleX; // w
float height = 2f * spriteSave.ScaleY; // z
float topTextureCoordinate = spriteSave.TopTextureCoordinate;
float bottomTextureCoordinate = spriteSave.BottomTextureCoordinate;
float leftTextureCoordinate = spriteSave.LeftTextureCoordinate;
float rightTextureCoordinate = spriteSave.RightTextureCoordinate;
int tileIndex = mCurrentNumberOfTiles;
RegisterName(spriteSave.Name, tileIndex);
// add the textured tile to our map so that we may draw it.
return AddTile(new Vector3(x, y, z), new Vector2(width, height), new Vector4(leftTextureCoordinate, rightTextureCoordinate, topTextureCoordinate, bottomTextureCoordinate));
}
private static void VerifySingleTexture(List<SpriteSave> spriteSaveList, int startingIndex, int count)
{
// Every Sprite should either have the same texture
if (spriteSaveList.Count != 0)
{
string texture = spriteSaveList[startingIndex].Texture;
for (int i = startingIndex + 1; i < startingIndex + count; i++)
{
SpriteSave ss = spriteSaveList[i];
if (ss.Texture != texture)
{
float leftOfSprite = ss.X - ss.ScaleX;
float indexX = leftOfSprite / (ss.ScaleX * 2);
float topOfSprite = ss.Y + ss.ScaleY;
float indexY = (0 - topOfSprite) / (ss.ScaleY * 2);
throw new Exception("All Sprites do not have the same texture");
}
}
}
}
private void RegisterName(string name, int tileIndex)
{
int throwaway;
if (!string.IsNullOrEmpty(name) && !int.TryParse(name, out throwaway))
{
// TEMPORARY:
// The tmx converter
// names all Sprites with
// a number if their name is
// not explicitly set. Therefore
// we have to ignore those and look
// for explicit names (names not numbers).
// Will talk to Domenic about this to fix it.
if (!mNamedTileOrderedIndexes.ContainsKey(name))
{
mNamedTileOrderedIndexes.Add(name, new List<int>());
}
mNamedTileOrderedIndexes[name].Add(tileIndex);
}
}
Vector2[] coords = new Vector2[4];
/// <summary>
/// Paints a texture on a tile. This method takes the index of the Sprite in the order it was added
/// to the MapDrawableBatch, so it supports any configuration including non-rectangular maps and maps with
/// gaps.
/// </summary>
/// <param name="orderedTileIndex">The index of the tile to paint - this matches the index of the tile as it was added.</param>
/// <param name="newTextureId"></param>
public void PaintTile(int orderedTileIndex, int newTextureId)
{
int currentVertex = orderedTileIndex * 4; // 4 vertices per tile
// Reusing the coords array saves us on allocation
mTileset.GetTextureCoordinateVectorsOfTextureIndex(newTextureId, coords);
// Coords are
// 3 2
//
// 0 1
mVertices[currentVertex + 0].TextureCoordinate = coords[0];
mVertices[currentVertex + 1].TextureCoordinate = coords[1];
mVertices[currentVertex + 2].TextureCoordinate = coords[2];
mVertices[currentVertex + 3].TextureCoordinate = coords[3];
}
public void PaintTileTextureCoordinates(int orderedTileIndex, float textureXCoordinate, float textureYCoordinate)
{
int currentVertex = orderedTileIndex * 4; // 4 vertices per tile
mTileset.GetCoordinatesForTile(coords, textureXCoordinate, textureYCoordinate);
mVertices[currentVertex + 0].TextureCoordinate = coords[0];
mVertices[currentVertex + 1].TextureCoordinate = coords[1];
mVertices[currentVertex + 2].TextureCoordinate = coords[2];
mVertices[currentVertex + 3].TextureCoordinate = coords[3];
}
// Swaps the top-right for the bottom-left verts
public void ApplyDiagonalFlip(int orderedTileIndex)
{
int currentVertex = orderedTileIndex * 4; // 4 vertices per tile
// Coords are
// 3 2
//
// 0 1
var old0 = mVertices[currentVertex + 0].TextureCoordinate;
mVertices[currentVertex + 0].TextureCoordinate = mVertices[currentVertex + 2].TextureCoordinate;
mVertices[currentVertex + 2].TextureCoordinate = old0;
}
public void RotateTextureCoordinatesCounterclockwise(int orderedTileIndex)
{
int currentVertex = orderedTileIndex * 4; // 4 vertices per tile
// Coords are
// 3 2
//
// 0 1
var old3 = mVertices[currentVertex + 3].TextureCoordinate;
mVertices[currentVertex + 3].TextureCoordinate = mVertices[currentVertex + 2].TextureCoordinate;
mVertices[currentVertex + 2].TextureCoordinate = mVertices[currentVertex + 1].TextureCoordinate;
mVertices[currentVertex + 1].TextureCoordinate = mVertices[currentVertex + 0].TextureCoordinate;
mVertices[currentVertex + 0].TextureCoordinate = old3;
}
public void GetTextureCoordiantesForOrderedTile(int orderedTileIndex, out float textureX, out float textureY)
{
// The order is:
// 3 2
//
// 0 1
// So we want to add 3 to the index to get the top-left vert, then use
// the texture coordinates there to get the
Vector2 vector = mVertices[(orderedTileIndex * 4) + 3].TextureCoordinate;
textureX = vector.X;
textureY = vector.Y;
}
public void GetBottomLeftWorldCoordinateForOrderedTile(int orderedTileIndex, out float x, out float y)
{
// The order is:
// 3 2
//
// 0 1
// So we just need to mutiply by 4 and not add anything
Vector3 vector = mVertices[(orderedTileIndex * 4)].Position;
x = vector.X;
y = vector.Y;
}
/// <summary>
/// Adds a tile to the tile map
/// </summary>
/// <param name="bottomLeftPosition"></param>
/// <param name="dimensions"></param>
/// <param name="texture">
/// 4 points defining the boundaries in the texture for the tile.
/// (X = left, Y = right, Z = top, W = bottom)
/// </param>
public int AddTile(Vector3 bottomLeftPosition, Vector2 dimensions, Vector4 texture)
{
int toReturn = mCurrentNumberOfTiles;
int currentVertex = mCurrentNumberOfTiles * 4;
int currentIndex = mCurrentNumberOfTiles * 6; // 6 indices per tile (there are mVertices.Length/4 tiles)
float xOffset = bottomLeftPosition.X;
float yOffset = bottomLeftPosition.Y;
float zOffset = bottomLeftPosition.Z;
float width = dimensions.X;
float height = dimensions.Y;
// create vertices
mVertices[currentVertex + 0] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + 0f, zOffset), new Vector2(texture.X, texture.W));
mVertices[currentVertex + 1] = new VertexPositionTexture(new Vector3(xOffset + width, yOffset + 0f, zOffset), new Vector2(texture.Y, texture.W));
mVertices[currentVertex + 2] = new VertexPositionTexture(new Vector3(xOffset + width, yOffset + height, zOffset), new Vector2(texture.Y, texture.Z));
mVertices[currentVertex + 3] = new VertexPositionTexture(new Vector3(xOffset + 0f, yOffset + height, zOffset), new Vector2(texture.X, texture.Z));
// create indices
mIndices[currentIndex + 0] = currentVertex + 0;
mIndices[currentIndex + 1] = currentVertex + 1;
mIndices[currentIndex + 2] = currentVertex + 2;
mIndices[currentIndex + 3] = currentVertex + 0;
mIndices[currentIndex + 4] = currentVertex + 2;
mIndices[currentIndex + 5] = currentVertex + 3;
mCurrentNumberOfTiles++;
return toReturn;
}
/// <summary>
/// Add a tile to the map
/// </summary>
/// <param name="bottomLeftPosition"></param>
/// <param name="tileDimensions"></param>
/// <param name="textureTopLeftX">Top left X coordinate in the core texture</param>
/// <param name="textureTopLeftY">Top left Y coordinate in the core texture</param>
/// <param name="textureBottomRightX">Bottom right X coordinate in the core texture</param>
/// <param name="textureBottomRightY">Bottom right Y coordinate in the core texture</param>
public int AddTile(Vector3 bottomLeftPosition, Vector2 tileDimensions, int textureTopLeftX, int textureTopLeftY, int textureBottomRightX, int textureBottomRightY)
{
// Form vector4 for AddTile overload
var textureValues = new Vector4();
textureValues.X = (float)textureTopLeftX / (float)mTexture.Width; // Left
textureValues.Y = (float)textureBottomRightX / (float)mTexture.Width; // Right
textureValues.Z = (float)textureTopLeftY / (float)mTexture.Height; // Top
textureValues.W = (float)textureBottomRightY / (float)mTexture.Height; // Bottom
return AddTile(bottomLeftPosition, tileDimensions, textureValues);
}
#region XML Docs
/// <summary>
/// Custom drawing technique - sets graphics states and
/// draws the custom shape
/// </summary>
/// <param name="camera">The currently drawing camera</param>
#endregion
public void Draw(Camera camera)
{
////////////////////Early Out///////////////////
if (!AbsoluteVisible)
{
return;
}
if (mVertices.Length == 0)
{
return;
}
//////////////////End Early Out/////////////////
int firstVertIndex;
int lastVertIndex;
int indexStart;
int numberOfTriangles;
GetRenderingIndexValues(camera, out firstVertIndex, out lastVertIndex, out indexStart, out numberOfTriangles);
if (numberOfTriangles != 0)
{
TextureAddressMode oldTextureAddressMode;
Effect effectTouse = PrepareRenderingStates(camera, out oldTextureAddressMode);
foreach (EffectPass pass in effectTouse.CurrentTechnique.Passes)
{
// Start each pass
pass.Apply();
int numberVertsToDraw = lastVertIndex - firstVertIndex;
// Right now this uses the (slower) DrawUserIndexedPrimitives
// It could use DrawIndexedPrimitives instead for much faster performance,
// but to do that we'd have to keep VB's around and make sure to re-create them
// whenever the graphics device is lost.
FlatRedBallServices.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>(
PrimitiveType.TriangleList,
mVertices,
firstVertIndex,
numberVertsToDraw,
mIndices,
indexStart, numberOfTriangles);
}
Renderer.TextureAddressMode = oldTextureAddressMode;
if (ZBuffered)
{
FlatRedBallServices.GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
}
}
}
private Effect PrepareRenderingStates(Camera camera, out TextureAddressMode oldTextureAddressMode)
{
// Set graphics states
FlatRedBallServices.GraphicsDevice.RasterizerState = RasterizerState.CullNone;
FlatRedBall.Graphics.Renderer.BlendOperation = BlendOperation.Regular;
Effect effectTouse = null;
if (ZBuffered)
{
FlatRedBallServices.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
camera.SetDeviceViewAndProjection(mAlphaTestEffect, false);
mAlphaTestEffect.World = Matrix.CreateScale(RenderingScale) * base.TransformationMatrix;
mAlphaTestEffect.Texture = mTexture;
effectTouse = mAlphaTestEffect;
}
else
{
camera.SetDeviceViewAndProjection(mBasicEffect, false);
mBasicEffect.World = Matrix.CreateScale(RenderingScale) * base.TransformationMatrix;
mBasicEffect.Texture = mTexture;
effectTouse = mBasicEffect;
}
// We won't need to use any other kind of texture
// address mode besides clamp, and clamp is required
// on the "Reach" profile when the texture is not power
// of two. Let's set it to clamp here so that we don't crash
// on non-power-of-two textures.
oldTextureAddressMode = Renderer.TextureAddressMode;
Renderer.TextureAddressMode = TextureAddressMode.Clamp;
return effectTouse;
}
private void GetRenderingIndexValues(Camera camera, out int firstVertIndex, out int lastVertIndex, out int indexStart, out int numberOfTriangles)
{
firstVertIndex = 0;
lastVertIndex = mVertices.Length;
float tileWidth = mVertices[1].Position.X - mVertices[0].Position.X;
if (mSortAxis == SortAxis.X)
{
float minX = camera.AbsoluteLeftXEdgeAt(this.Z);
float maxX = camera.AbsoluteRightXEdgeAt(this.Z);
minX -= this.X;
maxX -= this.X;
firstVertIndex = GetFirstAfterX(mVertices, minX - tileWidth);
lastVertIndex = GetFirstAfterX(mVertices, maxX) + 4;
}
else if (mSortAxis == SortAxis.Y)
{
float minY = camera.AbsoluteBottomYEdgeAt(this.Z);
float maxY = camera.AbsoluteTopYEdgeAt(this.Z);
minY -= this.Y;
maxY -= this.Y;
firstVertIndex = GetFirstAfterY(mVertices, minY - tileWidth);
lastVertIndex = GetFirstAfterY(mVertices, maxY) + 4;
}
lastVertIndex = System.Math.Min(lastVertIndex, mVertices.Length);
indexStart = 0;// (firstVertIndex * 3) / 2;
int indexEndExclusive = ((lastVertIndex - firstVertIndex) * 3) / 2;
numberOfTriangles = (indexEndExclusive - indexStart) / 3;
}
public static int GetFirstAfterX(VertexPositionTexture[] list, float xGreaterThan)
{
int min = 0;
int originalMax = list.Length / 4;
int max = list.Length / 4;
int mid = (max + min) / 2;
while (min < max)
{
mid = (max + min) / 2;
float midItem = list[mid * 4].Position.X;
if (midItem > xGreaterThan)
{
// Is this the last one?
// Not sure why this is here, because if we have just 2 items,
// this will always return a value of 1 instead
//if (mid * 4 + 4 >= list.Length)
//{
// return mid * 4;
//}
// did we find it?
if (mid > 0 && list[(mid - 1) * 4].Position.X <= xGreaterThan)
{
return mid * 4;
}
else
{
max = mid - 1;
}
}
else if (midItem <= xGreaterThan)
{
if (mid == 0)
{
return mid * 4;
}
else if (mid < originalMax - 1 && list[(mid + 1) * 4].Position.X > xGreaterThan)
{
return (mid + 1) * 4;
}
else
{
min = mid + 1;
}
}
}
if (min == 0)
{
return 0;
}
else
{
return list.Length;
}
}
public static int GetFirstAfterY(VertexPositionTexture[] list, float yGreaterThan)
{
int min = 0;
int originalMax = list.Length / 4;
int max = list.Length / 4;
int mid = (max + min) / 2;
while (min < max)
{
mid = (max + min) / 2;
float midItem = list[mid * 4].Position.Y;
if (midItem > yGreaterThan)
{
// Is this the last one?
// See comment in GetFirstAfterX
//if (mid * 4 + 4 >= list.Length)
//{
// return mid * 4;
//}
// did we find it?
if (mid > 0 && list[(mid - 1) * 4].Position.Y <= yGreaterThan)
{
return mid * 4;
}
else
{
max = mid - 1;
}
}
else if (midItem <= yGreaterThan)
{
if (mid == 0)
{
return mid * 4;
}
else if (mid < originalMax - 1 && list[(mid + 1) * 4].Position.Y > yGreaterThan)
{
return (mid + 1) * 4;
}
else
{
min = mid + 1;
}
}
}
if (min == 0)
{
return 0;
}
else
{
return list.Length;
}
}
#region XML Docs
/// <summary>
/// Here we update our batch - but this batch doesn't
/// need to be updated
/// </summary>
#endregion
public void Update()
{
float leftView = Camera.Main.AbsoluteLeftXEdgeAt(0);
float topView = Camera.Main.AbsoluteTopYEdgeAt(0);
float cameraOffsetX = leftView - CameraOriginX;
float cameraOffsetY = topView - CameraOriginY;
this.RelativeX = cameraOffsetX * _parallaxMultiplierX;
this.RelativeY = cameraOffsetY * _parallaxMultiplierY;
this.TimedActivity(TimeManager.SecondDifference, TimeManager.SecondDifferenceSquaredDividedByTwo, TimeManager.LastSecondDifference);
// The MapDrawableBatch may be attached to a LayeredTileMap (the container of all layers)
// If so, the player may move the LayeredTileMap and expect all contained layers to move along
// with it. To allow this, we need to have dependencies updated. We'll do this by simply updating
// dependencies here, although I don't know at this point if there's a better way - like if we should
// be adding this to the SpriteManager's PositionedObjectList. This is an improvement so we'll do it for
// now and revisit this in case there's a problem in the future.
this.UpdateDependencies(TimeManager.CurrentTime);
}
// TODO: I would like to somehow make this a property on the LayeredTileMap, but right now it is easier to put them here
public float CameraOriginY { get; set; }
public float CameraOriginX { get; set; }
IVisible IVisible.Parent
{
get
{
return this.Parent as IVisible;
}
}
public bool AbsoluteVisible
{
get
{
if (this.Visible)
{
var parentAsIVisible = this.Parent as IVisible;
if (parentAsIVisible == null || IgnoresParentVisibility)
{
return true;
}
else
{
// this is true, so return if the parent is visible:
return parentAsIVisible.AbsoluteVisible;
}
}
else
{
return false;
}
}
}
public bool IgnoresParentVisibility
{
get;
set;
}
#region XML Docs
/// <summary>
/// Don't call this, instead call SpriteManager.RemoveDrawableBatch
/// </summary>
#endregion
public void Destroy()
{
this.RemoveSelfFromListsBelongingTo();
}
public void MergeOntoThis(IEnumerable<MapDrawableBatch> mapDrawableBatches)
{
int quadsToAdd = 0;
int quadsOnThis = QuadCount;
foreach (var mdb in mapDrawableBatches)
{
quadsToAdd += mdb.QuadCount;
}
int totalNumberOfVerts = 4 * (this.QuadCount + quadsToAdd);
int totalNumberOfIndexes = 6 * (this.QuadCount + quadsToAdd);
var oldVerts = mVertices;
var oldIndexes = mIndices;
mVertices = new VertexPositionTexture[totalNumberOfVerts];
mIndices = new int[totalNumberOfIndexes];
oldVerts.CopyTo(mVertices, 0);
oldIndexes.CopyTo(mIndices, 0);
int currentQuadIndex = quadsOnThis;
int index = 0;
foreach (var mdb in mapDrawableBatches)
{
int startVert = currentQuadIndex * 4;
int startIndex = currentQuadIndex * 6;
int numberOfIndices = mdb.mIndices.Length;
int numberOfNewVertices = mdb.mVertices.Length;
mdb.mVertices.CopyTo(mVertices, startVert);
mdb.mIndices.CopyTo(mIndices, startIndex);
for (int i = startIndex; i < startIndex + numberOfIndices; i++)
{
mIndices[i] += startVert;
}
for (int i = startVert; i < startVert + numberOfNewVertices; i++)
{
mVertices[i].Position.Z += index + 1;
}
foreach (var kvp in mdb.mNamedTileOrderedIndexes)
{
string key = kvp.Key;
List<int> toAddTo;
if (mNamedTileOrderedIndexes.ContainsKey(key))
{
toAddTo = mNamedTileOrderedIndexes[key];
}
else
{
toAddTo = new List<int>();
mNamedTileOrderedIndexes[key] = toAddTo;
}
foreach (var namedIndex in kvp.Value)
{
toAddTo.Add(namedIndex + currentQuadIndex);
}
}
currentQuadIndex += mdb.QuadCount;
index++;
}
}
public void RemoveQuads(IEnumerable<int> quadIndexes)
{
var vertList = mVertices.ToList();
// Reverse - go from biggest to smallest
foreach (var indexToRemove in quadIndexes.Distinct().OrderBy(item => -item))
{
// and go from biggest to smallest here too
vertList.RemoveAt(indexToRemove * 4 + 3);
vertList.RemoveAt(indexToRemove * 4 + 2);
vertList.RemoveAt(indexToRemove * 4 + 1);
vertList.RemoveAt(indexToRemove * 4 + 0);
}
mVertices = vertList.ToArray();
// The mNamedTileOrderedIndexes is a dictionary that stores which indexes are stored
// with which tiles. For example, the key in the dictionary may be "Lava", in which case
// the value is the indexes of the tiles that use the Lava tile.
// If we do end up removing any quads, then all following quads will shift, so we need to
// adjust the indexes so the naming works correctly
List<int> orderedInts = quadIndexes.OrderBy(item => item).Distinct().ToList();
int numberOfRemovals = 0;
foreach (var kvp in mNamedTileOrderedIndexes)
{
var ints = kvp.Value;
numberOfRemovals = 0;
for (int i = 0; i < ints.Count; i++)
{
// Nothing left to test, so subtract and move on....
if (numberOfRemovals == orderedInts.Count)
{
ints[i] -= numberOfRemovals;
}
else if (ints[i] == orderedInts[numberOfRemovals])
{
ints.Clear();
break;
}
else if (ints[i] < orderedInts[numberOfRemovals])
{
ints[i] -= numberOfRemovals;
}
else
{
while (numberOfRemovals < orderedInts.Count && ints[i] > orderedInts[numberOfRemovals])
{
numberOfRemovals++;
}
if (numberOfRemovals < orderedInts.Count && ints[i] == orderedInts[numberOfRemovals])
{
ints.Clear();
break;
}
ints[i] -= numberOfRemovals;
}
}
}
}
#endregion
}
public static class MapDrawableBatchExtensionMethods
{
}
}
| |
using FFImageLoading.Forms;
using FFImageLoading.Work;
using FFImageLoading.Extensions;
using FFImageLoading.Forms.Args;
using System;
using System.ComponentModel;
using Windows.Graphics.Imaging;
using System.Threading.Tasks;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Storage.Streams;
using System.IO;
using System.Threading;
using System.Reflection;
using System.Linq;
using FFImageLoading.Helpers;
using Xamarin.Forms;
using FFImageLoading.Forms.Platform;
#if WINDOWS_UWP
using Xamarin.Forms.Platform.UWP;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Controls;
#else
using Xamarin.Forms.Platform.WinRT;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Controls;
#endif
#if WINDOWS_UWP
namespace FFImageLoading.Forms.WinUWP
#else
namespace FFImageLoading.Forms.WinRT
#endif
{
[Obsolete("Use the same class in FFImageLoading.Forms.Platform namespace")]
public class CachedImageRenderer : FFImageLoading.Forms.Platform.CachedImageRenderer
{
}
}
namespace FFImageLoading.Forms.Platform
{
/// <summary>
/// CachedImage Implementation
/// </summary>
[Preserve(AllMembers = true)]
public class CachedImageRenderer : ViewRenderer<CachedImage, Windows.UI.Xaml.Controls.Image>
{
[RenderWith(typeof(CachedImageRenderer))]
internal class _CachedImageRenderer
{
}
bool _isSizeSet;
private bool _measured;
private IScheduledWork _currentTask;
private ImageSourceBinding _lastImageSource;
private bool _isDisposed = false;
/// <summary>
/// Used for registration with dependency service
/// </summary>
public static void Init()
{
CachedImage.IsRendererInitialized = true;
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
ScaleHelper.InitAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
var bitmapSource = Control.Source as BitmapSource;
if (bitmapSource == null)
return new SizeRequest();
_measured = true;
return new SizeRequest(new Size()
{
Width = bitmapSource.PixelWidth,
Height = bitmapSource.PixelHeight
});
}
protected override void OnElementChanged(ElementChangedEventArgs<CachedImage> e)
{
base.OnElementChanged(e);
if (Control == null && Element != null && !_isDisposed)
{
var control = new Windows.UI.Xaml.Controls.Image()
{
Stretch = GetStretch(Aspect.AspectFill),
};
control.ImageOpened += OnImageOpened;
SetNativeControl(control);
Control.HorizontalAlignment = HorizontalAlignment.Center;
Control.VerticalAlignment = VerticalAlignment.Center;
}
if (e.OldElement != null)
{
e.OldElement.InternalReloadImage = null;
e.OldElement.InternalCancel = null;
e.OldElement.InternalGetImageAsJPG = null;
e.OldElement.InternalGetImageAsPNG = null;
}
if (e.NewElement != null)
{
_isSizeSet = false;
e.NewElement.InternalReloadImage = new Action(ReloadImage);
e.NewElement.InternalCancel = new Action(CancelIfNeeded);
e.NewElement.InternalGetImageAsJPG = new Func<GetImageAsJpgArgs, Task<byte[]>>(GetImageAsJpgAsync);
e.NewElement.InternalGetImageAsPNG = new Func<GetImageAsPngArgs, Task<byte[]>>(GetImageAsPngAsync);
UpdateAspect();
UpdateImage(Control, Element, e.OldElement);
}
}
protected override void Dispose(bool disposing)
{
if (!_isDisposed)
{
_isDisposed = true;
if (Control != null)
{
Control.ImageOpened -= OnImageOpened;
}
CancelIfNeeded();
}
base.Dispose(disposing);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == CachedImage.SourceProperty.PropertyName)
{
UpdateImage(Control, Element, null);
}
else if (e.PropertyName == CachedImage.AspectProperty.PropertyName)
{
UpdateAspect();
}
}
void OnImageOpened(object sender, RoutedEventArgs routedEventArgs)
{
if (_measured)
{
((IVisualElementController)Element)?.InvalidateMeasure(Xamarin.Forms.Internals.InvalidationTrigger.RendererReady);
}
}
async void UpdateImage(Windows.UI.Xaml.Controls.Image imageView, CachedImage image, CachedImage previousImage)
{
CancelIfNeeded();
if (image == null || imageView == null || _isDisposed)
return;
var ffSource = await ImageSourceBinding.GetImageSourceBinding(image.Source, image).ConfigureAwait(false);
if (ffSource == null)
{
if (_lastImageSource == null)
return;
_lastImageSource = null;
imageView.Source = null;
return;
}
if (previousImage != null && !ffSource.Equals(_lastImageSource))
{
_lastImageSource = null;
imageView.Source = null;
}
image.SetIsLoading(true);
var placeholderSource = await ImageSourceBinding.GetImageSourceBinding(image.LoadingPlaceholder, image).ConfigureAwait(false);
var errorPlaceholderSource = await ImageSourceBinding.GetImageSourceBinding(image.ErrorPlaceholder, image).ConfigureAwait(false);
TaskParameter imageLoader;
image.SetupOnBeforeImageLoading(out imageLoader, ffSource, placeholderSource, errorPlaceholderSource);
if (imageLoader != null)
{
var finishAction = imageLoader.OnFinish;
var sucessAction = imageLoader.OnSuccess;
imageLoader.Finish((work) =>
{
finishAction?.Invoke(work);
ImageLoadingSizeChanged(image, false);
});
imageLoader.Success((imageInformation, loadingResult) =>
{
sucessAction?.Invoke(imageInformation, loadingResult);
_lastImageSource = ffSource;
});
imageLoader.LoadingPlaceholderSet(() => ImageLoadingSizeChanged(image, true));
if (!_isDisposed)
_currentTask = imageLoader.Into(imageView);
}
}
void UpdateAspect()
{
if (Control == null || Element == null || _isDisposed)
return;
Control.Stretch = GetStretch(Element.Aspect);
}
static Stretch GetStretch(Aspect aspect)
{
switch (aspect)
{
case Aspect.AspectFill:
return Stretch.UniformToFill;
case Aspect.Fill:
return Stretch.Fill;
default:
return Stretch.Uniform;
}
}
async void ImageLoadingSizeChanged(CachedImage element, bool isLoading)
{
await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(() =>
{
if (element != null && !_isDisposed)
{
if (!isLoading || !_isSizeSet)
{
((IVisualElementController)element)?.InvalidateMeasure(Xamarin.Forms.Internals.InvalidationTrigger.RendererReady);
_isSizeSet = true;
}
if (!isLoading)
element.SetIsLoading(isLoading);
}
});
}
void ReloadImage()
{
UpdateImage(Control, Element, null);
}
void CancelIfNeeded()
{
try
{
_currentTask?.Cancel();
}
catch (Exception) { }
}
Task<byte[]> GetImageAsJpgAsync(GetImageAsJpgArgs args)
{
return GetImageAsByteAsync(BitmapEncoder.JpegEncoderId, args.Quality, args.DesiredWidth, args.DesiredHeight);
}
Task<byte[]> GetImageAsPngAsync(GetImageAsPngArgs args)
{
return GetImageAsByteAsync(BitmapEncoder.PngEncoderId, 90, args.DesiredWidth, args.DesiredHeight);
}
async Task<byte[]> GetImageAsByteAsync(Guid format, int quality, int desiredWidth, int desiredHeight)
{
if (Control == null || Control.Source == null)
return null;
var bitmap = Control.Source as WriteableBitmap;
if (bitmap == null)
return null;
byte[] pixels = null;
uint pixelsWidth = (uint)bitmap.PixelWidth;
uint pixelsHeight = (uint)bitmap.PixelHeight;
if (desiredWidth != 0 || desiredHeight != 0)
{
double widthRatio = (double)desiredWidth / (double)bitmap.PixelWidth;
double heightRatio = (double)desiredHeight / (double)bitmap.PixelHeight;
double scaleRatio = Math.Min(widthRatio, heightRatio);
if (desiredWidth == 0)
scaleRatio = heightRatio;
if (desiredHeight == 0)
scaleRatio = widthRatio;
uint aspectWidth = (uint)((double)bitmap.PixelWidth * scaleRatio);
uint aspectHeight = (uint)((double)bitmap.PixelHeight * scaleRatio);
using (var tempStream = new InMemoryRandomAccessStream())
{
byte[] tempPixels = await GetBytesFromBitmapAsync(bitmap);
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, tempStream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
pixelsWidth, pixelsHeight, 96, 96, tempPixels);
await encoder.FlushAsync();
tempStream.Seek(0);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(tempStream);
BitmapTransform transform = new BitmapTransform()
{
ScaledWidth = aspectWidth,
ScaledHeight = aspectHeight,
InterpolationMode = BitmapInterpolationMode.Cubic
};
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
pixels = pixelData.DetachPixelData();
pixelsWidth = aspectWidth;
pixelsHeight = aspectHeight;
}
}
else
{
pixels = await GetBytesFromBitmapAsync(bitmap);
}
using (var stream = new InMemoryRandomAccessStream())
{
BitmapEncoder encoder;
if (format == BitmapEncoder.JpegEncoderId)
{
var propertySet = new BitmapPropertySet();
var qualityValue = new BitmapTypedValue((double)quality / 100d, Windows.Foundation.PropertyType.Single);
propertySet.Add("ImageQuality", qualityValue);
encoder = await BitmapEncoder.CreateAsync(format, stream, propertySet);
}
else
{
encoder = await BitmapEncoder.CreateAsync(format, stream);
}
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
pixelsWidth, pixelsHeight, 96, 96, pixels);
await encoder.FlushAsync();
stream.Seek(0);
var bytes = new byte[stream.Size];
await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);
return bytes;
}
}
async Task<byte[]> GetBytesFromBitmapAsync(WriteableBitmap bitmap)
{
byte[] tempPixels;
using (var sourceStream = bitmap.PixelBuffer.AsStream())
{
tempPixels = new byte[sourceStream.Length];
await sourceStream.ReadAsync(tempPixels, 0, tempPixels.Length).ConfigureAwait(false);
}
return tempPixels;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Schema
{
using System.Collections;
using System.Text;
using System.Diagnostics;
internal class BaseProcessor
{
private XmlNameTable _nameTable;
private SchemaNames _schemaNames;
private ValidationEventHandler _eventHandler;
private XmlSchemaCompilationSettings _compilationSettings;
private int _errorCount = 0;
private string _nsXml;
public BaseProcessor(XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler)
: this(nameTable, schemaNames, eventHandler, new XmlSchemaCompilationSettings())
{ } //Use the default for XmlSchemaCollection
public BaseProcessor(XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler, XmlSchemaCompilationSettings compilationSettings)
{
Debug.Assert(nameTable != null);
_nameTable = nameTable;
_schemaNames = schemaNames;
_eventHandler = eventHandler;
_compilationSettings = compilationSettings;
_nsXml = nameTable.Add(XmlReservedNs.NsXml);
}
protected XmlNameTable NameTable
{
get { return _nameTable; }
}
protected SchemaNames SchemaNames
{
get
{
if (_schemaNames == null)
{
_schemaNames = new SchemaNames(_nameTable);
}
return _schemaNames;
}
}
protected ValidationEventHandler EventHandler
{
get { return _eventHandler; }
}
protected XmlSchemaCompilationSettings CompilationSettings
{
get { return _compilationSettings; }
}
protected bool HasErrors
{
get { return _errorCount != 0; }
}
protected void AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, XmlSchemaObject item)
{
if (qname.Name.Length == 0)
{
return;
}
XmlSchemaObject existingObject = (XmlSchemaObject)table[qname];
if (existingObject != null)
{
if (existingObject == item)
{
return;
}
string code = SR.Sch_DupGlobalElement;
if (item is XmlSchemaAttributeGroup)
{
string ns = _nameTable.Add(qname.Namespace);
if (Ref.Equal(ns, _nsXml))
{ //Check for xml namespace
XmlSchema schemaForXmlNS = Preprocessor.GetBuildInSchema();
XmlSchemaObject builtInAttributeGroup = schemaForXmlNS.AttributeGroups[qname];
if ((object)existingObject == (object)builtInAttributeGroup)
{
table.Insert(qname, item);
return;
}
else if ((object)item == (object)builtInAttributeGroup)
{ //trying to overwrite customer's component with built-in, ignore built-in
return;
}
}
else if (IsValidAttributeGroupRedefine(existingObject, item, table))
{ //check for redefines
return;
}
code = SR.Sch_DupAttributeGroup;
}
else if (item is XmlSchemaAttribute)
{
string ns = _nameTable.Add(qname.Namespace);
if (Ref.Equal(ns, _nsXml))
{
XmlSchema schemaForXmlNS = Preprocessor.GetBuildInSchema();
XmlSchemaObject builtInAttribute = schemaForXmlNS.Attributes[qname];
if ((object)existingObject == (object)builtInAttribute)
{ //replace built-in one
table.Insert(qname, item);
return;
}
else if ((object)item == (object)builtInAttribute)
{ //trying to overwrite customer's component with built-in, ignore built-in
return;
}
}
code = SR.Sch_DupGlobalAttribute;
}
else if (item is XmlSchemaSimpleType)
{
if (IsValidTypeRedefine(existingObject, item, table))
{
return;
}
code = SR.Sch_DupSimpleType;
}
else if (item is XmlSchemaComplexType)
{
if (IsValidTypeRedefine(existingObject, item, table))
{
return;
}
code = SR.Sch_DupComplexType;
}
else if (item is XmlSchemaGroup)
{
if (IsValidGroupRedefine(existingObject, item, table))
{ //check for redefines
return;
}
code = SR.Sch_DupGroup;
}
else if (item is XmlSchemaNotation)
{
code = SR.Sch_DupNotation;
}
else if (item is XmlSchemaIdentityConstraint)
{
code = SR.Sch_DupIdentityConstraint;
}
else
{
Debug.Assert(item is XmlSchemaElement);
}
SendValidationEvent(code, qname.ToString(), item);
}
else
{
table.Add(qname, item);
}
}
private bool IsValidAttributeGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table)
{
XmlSchemaAttributeGroup attGroup = item as XmlSchemaAttributeGroup;
XmlSchemaAttributeGroup existingAttGroup = existingObject as XmlSchemaAttributeGroup;
if (existingAttGroup == attGroup.Redefined)
{ //attribute group is the redefinition of existingObject
if (existingAttGroup.AttributeUses.Count == 0)
{ //If the existing one is not already compiled, then replace.
table.Insert(attGroup.QualifiedName, attGroup); //Update with redefined entry
return true;
}
}
else if (existingAttGroup.Redefined == attGroup)
{ //Redefined type already exists in the set, original type is added after redefined type, ignore the original type
return true;
}
return false;
}
private bool IsValidGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table)
{
XmlSchemaGroup group = item as XmlSchemaGroup;
XmlSchemaGroup existingGroup = existingObject as XmlSchemaGroup;
if (existingGroup == group.Redefined)
{ //group is the redefinition of existingObject
if (existingGroup.CanonicalParticle == null)
{ //If the existing one is not already compiled, then replace.
table.Insert(group.QualifiedName, group); //Update with redefined entry
return true;
}
}
else if (existingGroup.Redefined == group)
{ //Redefined type already exists in the set, original type is added after redefined type, ignore the original type
return true;
}
return false;
}
private bool IsValidTypeRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table)
{
XmlSchemaType schemaType = item as XmlSchemaType;
XmlSchemaType existingType = existingObject as XmlSchemaType;
if (existingType == schemaType.Redefined)
{ //schemaType is the redefinition of existingObject
if (existingType.ElementDecl == null)
{ //If the existing one is not already compiled, then replace.
table.Insert(schemaType.QualifiedName, schemaType); //Update with redefined entry
return true;
}
}
else if (existingType.Redefined == schemaType)
{ //Redefined type already exists in the set, original type is added after redefined type, ignore the original type
return true;
}
return false;
}
protected void SendValidationEvent(string code, XmlSchemaObject source)
{
SendValidationEvent(new XmlSchemaException(code, source), XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, string msg, XmlSchemaObject source)
{
SendValidationEvent(new XmlSchemaException(code, msg, source), XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, string msg1, string msg2, XmlSchemaObject source)
{
SendValidationEvent(new XmlSchemaException(code, new string[] { msg1, msg2 }, source), XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, string[] args, Exception innerException, XmlSchemaObject source)
{
SendValidationEvent(new XmlSchemaException(code, args, innerException, source.SourceUri, source.LineNumber, source.LinePosition, source), XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, string msg1, string msg2, string sourceUri, int lineNumber, int linePosition)
{
SendValidationEvent(new XmlSchemaException(code, new string[] { msg1, msg2 }, sourceUri, lineNumber, linePosition), XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, XmlSchemaObject source, XmlSeverityType severity)
{
SendValidationEvent(new XmlSchemaException(code, source), severity);
}
protected void SendValidationEvent(XmlSchemaException e)
{
SendValidationEvent(e, XmlSeverityType.Error);
}
protected void SendValidationEvent(string code, string msg, XmlSchemaObject source, XmlSeverityType severity)
{
SendValidationEvent(new XmlSchemaException(code, msg, source), severity);
}
protected void SendValidationEvent(XmlSchemaException e, XmlSeverityType severity)
{
if (severity == XmlSeverityType.Error)
{
_errorCount++;
}
if (_eventHandler != null)
{
_eventHandler(null, new ValidationEventArgs(e, severity));
}
else if (severity == XmlSeverityType.Error)
{
throw e;
}
}
protected void SendValidationEventNoThrow(XmlSchemaException e, XmlSeverityType severity)
{
if (severity == XmlSeverityType.Error)
{
_errorCount++;
}
if (_eventHandler != null)
{
_eventHandler(null, new ValidationEventArgs(e, severity));
}
}
};
} // namespace System.Xml
| |
// Adler32.cs - Computes Adler32 data checksum of a data stream
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace Orvid.Compression.Checksums
{
/// <summary>
/// Computes Adler32 checksum for a stream of data. An Adler32
/// checksum is not as reliable as a CRC32 checksum, but a lot faster to
/// compute.
///
/// The specification for Adler32 may be found in RFC 1950.
/// ZLIB Compressed Data Format Specification version 3.3)
///
///
/// From that document:
///
/// "ADLER32 (Adler-32 checksum)
/// This contains a checksum value of the uncompressed data
/// (excluding any dictionary data) computed according to Adler-32
/// algorithm. This algorithm is a 32-bit extension and improvement
/// of the Fletcher algorithm, used in the ITU-T X.224 / ISO 8073
/// standard.
///
/// Adler-32 is composed of two sums accumulated per byte: s1 is
/// the sum of all bytes, s2 is the sum of all s1 values. Both sums
/// are done modulo 65521. s1 is initialized to 1, s2 to zero. The
/// Adler-32 checksum is stored as s2*65536 + s1 in most-
/// significant-byte first (network) order."
///
/// "8.2. The Adler-32 algorithm
///
/// The Adler-32 algorithm is much faster than the CRC32 algorithm yet
/// still provides an extremely low probability of undetected errors.
///
/// The modulo on unsigned long accumulators can be delayed for 5552
/// bytes, so the modulo operation time is negligible. If the bytes
/// are a, b, c, the second sum is 3a + 2b + c + 3, and so is position
/// and order sensitive, unlike the first sum, which is just a
/// checksum. That 65521 is prime is important to avoid a possible
/// large class of two-byte errors that leave the check unchanged.
/// (The Fletcher checksum uses 255, which is not prime and which also
/// makes the Fletcher check insensitive to single byte changes 0 -
/// 255.)
///
/// The sum s1 is initialized to 1 instead of zero to make the length
/// of the sequence part of s2, so that the length does not have to be
/// checked separately. (Any sequence of zeroes has a Fletcher
/// checksum of zero.)"
/// </summary>
/// <see cref="ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterInputStream"/>
/// <see cref="ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream"/>
public sealed class Adler32
{
/// <summary>
/// largest prime smaller than 65536
/// </summary>
const uint BASE = 65521;
/// <summary>
/// Returns the Adler32 data checksum computed so far.
/// </summary>
public long Value {
get {
return checksum;
}
}
/// <summary>
/// Creates a new instance of the Adler32 class.
/// The checksum starts off with a value of 1.
/// </summary>
public Adler32()
{
Reset();
}
/// <summary>
/// Resets the Adler32 checksum to the initial value.
/// </summary>
public void Reset()
{
checksum = 1;
}
/// <summary>
/// Updates the checksum with a byte value.
/// </summary>
/// <param name="value">
/// The data value to add. The high byte of the int is ignored.
/// </param>
public void Update(int value)
{
// We could make a length 1 byte array and call update again, but I
// would rather not have that overhead
uint s1 = checksum & 0xFFFF;
uint s2 = checksum >> 16;
s1 = (s1 + ((uint)value & 0xFF)) % BASE;
s2 = (s1 + s2) % BASE;
checksum = (s2 << 16) + s1;
}
/// <summary>
/// Updates the checksum with an array of bytes.
/// </summary>
/// <param name="buffer">
/// The source of the data to update with.
/// </param>
public void Update(byte[] buffer)
{
if ( buffer == null ) {
throw new ArgumentNullException("buffer");
}
Update(buffer, 0, buffer.Length);
}
/// <summary>
/// Updates the checksum with the bytes taken from the array.
/// </summary>
/// <param name="buffer">
/// an array of bytes
/// </param>
/// <param name="offset">
/// the start of the data used for this update
/// </param>
/// <param name="count">
/// the number of bytes to use for this update
/// </param>
public void Update(byte[] buffer, int offset, int count)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (offset < 0) {
#if NETCF_1_0
throw new ArgumentOutOfRangeException("offset");
#else
throw new ArgumentOutOfRangeException("offset", "cannot be negative");
#endif
}
if ( count < 0 )
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("count");
#else
throw new ArgumentOutOfRangeException("count", "cannot be negative");
#endif
}
if (offset >= buffer.Length)
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("offset");
#else
throw new ArgumentOutOfRangeException("offset", "not a valid index into buffer");
#endif
}
if (offset + count > buffer.Length)
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("count");
#else
throw new ArgumentOutOfRangeException("count", "exceeds buffer size");
#endif
}
//(By Per Bothner)
uint s1 = checksum & 0xFFFF;
uint s2 = checksum >> 16;
while (count > 0) {
// We can defer the modulo operation:
// s1 maximally grows from 65521 to 65521 + 255 * 3800
// s2 maximally grows by 3800 * median(s1) = 2090079800 < 2^31
int n = 3800;
if (n > count) {
n = count;
}
count -= n;
while (--n >= 0) {
s1 = s1 + (uint)(buffer[offset++] & 0xff);
s2 = s2 + s1;
}
s1 %= BASE;
s2 %= BASE;
}
checksum = (s2 << 16) | s1;
}
#region Instance Fields
uint checksum;
#endregion
}
}
| |
/*
Copyright (c) 2012 Microsoft Corporation. All rights reserved.
Use of this sample source code is subject to the terms of the Microsoft license
agreement under which you licensed this sample source code and is provided AS-IS.
If you did not accept the terms of the license agreement, you are not authorized
to use this sample source code. For the terms of the license, please see the
license agreement between you and Microsoft.
To see all Code Samples for Windows Phone, visit http://go.microsoft.com/fwlink/?LinkID=219604
*/
using System;
using System.Diagnostics;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using IAPMockLibSample.Resources;
#if DEBUG
using MockIAPLib;
using Store = MockIAPLib;
#else
using Windows.ApplicationModel.Store;
using Store = Windows.ApplicationModel.Store;
#endif
namespace IAPMockLibSample
{
public partial class App : Application
{
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public static PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
SetupMockIAP();
}
private void SetupMockIAP()
{
#if DEBUG
MockIAP.Init();
MockIAP.RunInMockMode(true);
MockIAP.SetListingInformation(1, "en-us", "Some description", "1", "TestApp");
// Add some more items manually.
ProductListing p = new ProductListing
{
Name = "img.1",
ImageUri = new Uri("/Res/Image/1.png", UriKind.Relative),
ProductId = "img.1",
ProductType = Windows.ApplicationModel.Store.ProductType.Durable,
Keywords = new string[] { "image" },
Description = "Nice image",
FormattedPrice = "1.0",
Tag = string.Empty
};
MockIAP.AddProductListing("img.1", p);
p = new ProductListing
{
Name = "img.2",
ImageUri = new Uri("/Res/Image/2.png", UriKind.Relative),
ProductId = "img.2",
ProductType = Windows.ApplicationModel.Store.ProductType.Durable,
Keywords = new string[] { "image" },
Description = "Nice image",
FormattedPrice = "1.0",
Tag = string.Empty
};
MockIAP.AddProductListing("img.2", p);
p = new ProductListing
{
Name = "img.3",
ImageUri = new Uri("/Res/Image/3.png", UriKind.Relative),
ProductId = "img.3",
ProductType = Windows.ApplicationModel.Store.ProductType.Durable,
Keywords = new string[] { "image" },
Description = "Nice image",
FormattedPrice = "1.0",
Tag = string.Empty
};
MockIAP.AddProductListing("img.3", p);
p = new ProductListing
{
Name = "img.4",
ImageUri = new Uri("/Res/Image/4.png", UriKind.Relative),
ProductId = "img.4",
ProductType = Windows.ApplicationModel.Store.ProductType.Durable,
Keywords = new string[] { "image" },
Description = "Nice image",
FormattedPrice = "1.0",
Tag = string.Empty
};
MockIAP.AddProductListing("img.4", p);
p = new ProductListing
{
Name = "img.5",
ImageUri = new Uri("/Res/Image/5.png", UriKind.Relative),
ProductId = "img.5",
ProductType = Windows.ApplicationModel.Store.ProductType.Durable,
Keywords = new string[] { "image" },
Description = "Nice image",
FormattedPrice = "1.0",
Tag = string.Empty
};
MockIAP.AddProductListing("img.5", p);
p = new ProductListing
{
Name = "img.6",
ImageUri = new Uri("/Res/Image/6.png", UriKind.Relative),
ProductId = "img.6",
ProductType = Windows.ApplicationModel.Store.ProductType.Durable,
Keywords = new string[] { "image" },
Description = "Nice image",
FormattedPrice = "1.0",
Tag = string.Empty
};
MockIAP.AddProductListing("img.6", p);
#endif
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Handle reset requests for clearing the backstack
RootFrame.Navigated += CheckForResetNavigation;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
private void CheckForResetNavigation(object sender, NavigationEventArgs e)
{
// If the app has received a 'reset' navigation, then we need to check
// on the next navigation to see if the page stack should be reset
if (e.NavigationMode == NavigationMode.Reset)
RootFrame.Navigated += ClearBackStackAfterReset;
}
private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
{
// Unregister the event so it doesn't get called again
RootFrame.Navigated -= ClearBackStackAfterReset;
// Only clear the stack for 'new' (forward) and 'refresh' navigations
if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
return;
// For UI consistency, clear the entire page stack
while (RootFrame.RemoveBackEntry() != null)
{
; // do nothing
}
}
#endregion
// Initialize the app's font and flow direction as defined in its localized resource strings.
//
// To ensure that the font of your application is aligned with its supported languages and that the
// FlowDirection for each of those languages follows its traditional direction, ResourceLanguage
// and ResourceFlowDirection should be initialized in each resx file to match these values with that
// file's culture. For example:
//
// AppResources.es-ES.resx
// ResourceLanguage's value should be "es-ES"
// ResourceFlowDirection's value should be "LeftToRight"
//
// AppResources.ar-SA.resx
// ResourceLanguage's value should be "ar-SA"
// ResourceFlowDirection's value should be "RightToLeft"
//
// For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072.
//
private void InitializeLanguage()
{
try
{
// Set the font to match the display language defined by the
// ResourceLanguage resource string for each supported language.
//
// Fall back to the font of the neutral language if the Display
// language of the phone is not supported.
//
// If a compiler error is hit then ResourceLanguage is missing from
// the resource file.
RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage);
// Set the FlowDirection of all elements under the root frame based
// on the ResourceFlowDirection resource string for each
// supported language.
//
// If a compiler error is hit then ResourceFlowDirection is missing from
// the resource file.
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
RootFrame.FlowDirection = flow;
}
catch
{
// If an exception is caught here it is most likely due to either
// ResourceLangauge not being correctly set to a supported language
// code or ResourceFlowDirection is set to a value other than LeftToRight
// or RightToLeft.
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw;
}
}
}
}
| |
using System;
using System.Globalization;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Xunit;
using Xunit.Abstractions;
using ItemMetadataNames = Microsoft.Build.Tasks.ItemMetadataNames;
namespace Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests
{
/// <summary>
/// Unit tests for the ResolveAssemblyReference task.
/// </summary>
[Trait("Category", "non-mono-tests")]
public sealed class WinMDTests : ResolveAssemblyReferenceTestFixture
{
public WinMDTests(ITestOutputHelper output) : base(output)
{
}
#region AssemblyInformationIsWinMDFile Tests
/// <summary>
/// Verify a null file path passed in return the fact the file is not a winmd file.
/// </summary>
[Fact]
public void IsWinMDFileNullFilePath()
{
string imageRuntime;
bool isManagedWinMD;
Assert.False(AssemblyInformation.IsWinMDFile(null, getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD));
Assert.False(isManagedWinMD);
}
/// <summary>
/// Verify if a empty file path is passed in that the file is not a winmd file.
/// </summary>
[Fact]
public void IsWinMDFileEmptyFilePath()
{
string imageRuntime;
bool isManagedWinMD;
Assert.False(AssemblyInformation.IsWinMDFile(String.Empty, getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD));
Assert.False(isManagedWinMD);
}
/// <summary>
/// If the file does not exist then we should report this is not a winmd file.
/// </summary>
[Fact]
public void IsWinMDFileFileDoesNotExistFilePath()
{
string imageRuntime;
bool isManagedWinMD;
Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleDoesNotExist.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD));
Assert.False(isManagedWinMD);
}
/// <summary>
/// The file exists and has the correct windowsruntime metadata, we should report this is a winmd file.
/// </summary>
[Fact]
public void IsWinMDFileGoodFile()
{
string imageRuntime;
bool isManagedWinMD;
Assert.True(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleWindowsRuntimeOnly.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD));
Assert.False(isManagedWinMD);
}
/// <summary>
/// This file is a mixed file with CLR and windowsruntime metadata we should report this is a winmd file.
/// </summary>
[Fact]
public void IsWinMDFileMixedFile()
{
string imageRuntime;
bool isManagedWinMD;
Assert.True(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleWindowsRuntimeAndCLR.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD));
Assert.True(isManagedWinMD);
}
/// <summary>
/// The file has only CLR metadata we should report this is not a winmd file
/// </summary>
[Fact]
public void IsWinMDFileCLROnlyFile()
{
string imageRuntime;
bool isManagedWinMD;
Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleClrOnly.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD));
Assert.False(isManagedWinMD);
}
/// <summary>
/// The windows runtime string is not correctly formatted, report this is not a winmd file.
/// </summary>
[Fact]
public void IsWinMDFileBadWindowsRuntimeFile()
{
string imageRuntime;
bool isManagedWinMD;
Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleBadWindowsRuntime.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD));
Assert.False(isManagedWinMD);
}
/// <summary>
/// We should report that a regular net assembly is not a winmd file.
/// </summary>
[Fact]
public void IsWinMDFileRegularNetAssemblyFile()
{
string imageRuntime;
bool isManagedWinMD;
Assert.False(AssemblyInformation.IsWinMDFile(@"C:\Framework\Whidbey\System.dll", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD));
Assert.False(isManagedWinMD);
}
/// <summary>
/// When a project to project reference is passed in we want to verify that
/// the winmd references get the correct metadata applied to them
/// </summary>
[Fact]
public void VerifyP2PHaveCorrectMetadataWinMD()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
TaskItem taskItem = new TaskItem(@"C:\WinMD\SampleWindowsRuntimeOnly.Winmd");
ITaskItem[] assemblyFiles = new TaskItem[]
{
taskItem
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.AssemblyFiles = assemblyFiles;
t.TargetProcessorArchitecture = "X86";
t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" };
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
Assert.Equal(2, t.RelatedFiles.Length);
bool dllFound = false;
bool priFound = false;
foreach (ITaskItem item in t.RelatedFiles)
{
if (item.ItemSpec.EndsWith(@"C:\WinMD\SampleWindowsRuntimeOnly.dll"))
{
dllFound = true;
Assert.Empty(item.GetMetadata(ItemMetadataNames.imageRuntime));
Assert.Empty(item.GetMetadata(ItemMetadataNames.winMDFile));
Assert.Empty(item.GetMetadata(ItemMetadataNames.winmdImplmentationFile));
}
if (item.ItemSpec.EndsWith(@"C:\WinMD\SampleWindowsRuntimeOnly.pri"))
{
priFound = true;
Assert.Empty(item.GetMetadata(ItemMetadataNames.imageRuntime));
Assert.Empty(item.GetMetadata(ItemMetadataNames.winMDFile));
Assert.Empty(item.GetMetadata(ItemMetadataNames.winmdImplmentationFile));
}
}
Assert.True(dllFound && priFound); // "Expected to find .dll and .pri related files."
Assert.Empty(t.ResolvedDependencyFiles);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));
Assert.Equal("Native", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFileType));
Assert.Equal("SampleWindowsRuntimeOnly.dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
Assert.Equal("WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
}
/// <summary>
/// When a project to project reference is passed in we want to verify that
/// the winmd references get the correct metadata applied to them
/// </summary>
[Fact]
public void VerifyP2PHaveCorrectMetadataWinMDManaged()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
TaskItem taskItem = new TaskItem(@"C:\WinMD\SampleWindowsRuntimeAndCLR.Winmd");
ITaskItem[] assemblyFiles = new TaskItem[]
{
taskItem
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.AssemblyFiles = assemblyFiles;
t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" };
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
Assert.Empty(t.RelatedFiles);
Assert.Empty(t.ResolvedDependencyFiles);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));
Assert.Equal("Managed", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFileType));
Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
Assert.Equal("WindowsRuntime 1.0, CLR V2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
}
/// <summary>
/// When a project to project reference is passed in we want to verify that
/// the winmd references get the correct metadata applied to them
/// </summary>
[Fact]
public void VerifyP2PHaveCorrectMetadataNonWinMD()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"C:\AssemblyFolder\SomeAssembly.dll")
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.AssemblyFiles = assemblyFiles;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
Assert.Empty(t.ResolvedDependencyFiles);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile));
Assert.Equal("v2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
}
/// <summary>
/// Verify when we reference a winmd file as a reference item make sure we ignore the mscorlib.
/// </summary>
[Fact]
public void IgnoreReferenceToMscorlib()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"SampleWindowsRuntimeOnly"), new TaskItem(@"SampleWindowsRuntimeAndClr")
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.TargetProcessorArchitecture = "X86";
t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" };
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(2, t.ResolvedFiles.Length);
Assert.Empty(t.ResolvedDependencyFiles);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
engine.AssertLogDoesntContain("conflict");
}
/// <summary>
/// Verify when we reference a mixed winmd file that we do resolve the reference to the mscorlib
/// </summary>
[Fact]
public void MixedWinMDGoodReferenceToMscorlib()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"SampleWindowsRuntimeAndClr")
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" };
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
Assert.Empty(t.ResolvedDependencyFiles);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
engine.AssertLogContainsMessageFromResource(resourceDelegate, "ResolveAssemblyReference.Resolved", @"C:\WinMD\v4\mscorlib.dll");
}
/// <summary>
/// Verify when a winmd file depends on another winmd file that we do resolve the dependency
/// </summary>
[Fact]
public void WinMdFileDependsOnAnotherWinMDFile()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"SampleWindowsRuntimeOnly2")
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.TargetProcessorArchitecture = "X86";
t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" };
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
Assert.Single(t.ResolvedDependencyFiles);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly2.winmd", t.ResolvedFiles[0].ItemSpec);
Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));
Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly.winmd", t.ResolvedDependencyFiles[0].ItemSpec);
Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
Assert.True(bool.Parse(t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));
}
/// <summary>
/// We have two dlls which depend on a winmd, the first dll does not have the winmd beside it, the second one does
/// we want to make sure that the winmd file is resolved beside the second dll.
/// </summary>
[Fact]
public void ResolveWinmdBesideDll()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"C:\DirectoryContainsOnlyDll\A.dll"),
new TaskItem(@"C:\DirectoryContainsdllAndWinmd\B.dll"),
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.SearchPaths = new String[] { "{RAWFILENAME}" };
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(2, t.ResolvedFiles.Length);
Assert.Single(t.ResolvedDependencyFiles);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
Assert.Equal(@"C:\DirectoryContainsdllAndWinmd\C.winmd", t.ResolvedDependencyFiles[0].ItemSpec);
}
/// <summary>
/// We have a winmd file and a dll depend on a winmd, there are copies of the winmd beside each of the files.
/// we want to make sure that the winmd file is resolved beside the winmd since that is the first file resolved.
/// </summary>
[Fact]
public void ResolveWinmdBesideDll2()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"C:\DirectoryContainstwoWinmd\A.winmd"),
new TaskItem(@"C:\DirectoryContainsdllAndWinmd\B.dll"),
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.SearchPaths = new String[] { @"{RAWFILENAME}" };
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(2, t.ResolvedFiles.Length);
Assert.Single(t.ResolvedDependencyFiles);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
Assert.Equal(@"C:\DirectoryContainstwoWinmd\C.winmd", t.ResolvedDependencyFiles[0].ItemSpec);
}
/// <summary>
/// Verify when a winmd file depends on another winmd file that itself has framework dependencies that we do not resolve any of the
/// dependencies due to the winmd to winmd reference
/// </summary>
[Fact]
public void WinMdFileDependsOnAnotherWinMDFileWithFrameworkDependencies()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"SampleWindowsRuntimeOnly3")
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.SearchPaths = new String[] { @"{TargetFrameworkDirectory}", @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" };
t.TargetFrameworkDirectories = new string[] { @"c:\WINNT\Microsoft.NET\Framework\v4.0.MyVersion" };
t.TargetProcessorArchitecture = "x86";
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
Assert.Equal(4, t.ResolvedDependencyFiles.Length);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly3.winmd", t.ResolvedFiles[0].ItemSpec);
Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));
}
/// <summary>
/// Make sure when a dot net assembly depends on a WinMDFile that
/// we get the winmd file resolved. Also make sure that if there is Implementation, ImageRuntime, or IsWinMD set on the dll that
/// it does not get propagated to the winmd file dependency.
/// </summary>
[Fact]
public void DotNetAssemblyDependsOnAWinMDFile()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
TaskItem item = new TaskItem(@"DotNetAssemblyDependsOnWinMD");
// This should not be used for anything, it is recalculated in rar, this is to make sure it is not forwarded to child items.
item.SetMetadata(ItemMetadataNames.imageRuntime, "FOO");
// This should not be used for anything, it is recalculated in rar, this is to make sure it is not forwarded to child items.
item.SetMetadata(ItemMetadataNames.winMDFile, "NOPE");
item.SetMetadata(ItemMetadataNames.winmdImplmentationFile, "IMPL");
ITaskItem[] assemblyFiles = new TaskItem[]
{
item
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.TargetProcessorArchitecture = "X86";
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" };
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
Assert.Single(t.ResolvedDependencyFiles);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
Assert.Equal(@"C:\WinMD\DotNetAssemblyDependsOnWinMD.dll", t.ResolvedFiles[0].ItemSpec);
Assert.Equal(@"v2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
Assert.Equal("NOPE", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile));
Assert.Equal("IMPL", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
Assert.Equal(@"C:\WinMD\SampleWindowsRuntimeOnly.winmd", t.ResolvedDependencyFiles[0].ItemSpec);
Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
Assert.True(bool.Parse(t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));
Assert.Equal("SampleWindowsRuntimeOnly.dll", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
}
/// <summary>
/// Resolve a winmd file which depends on a native implementation dll that has an invalid pe header.
/// This will always result in an error since the dll is malformed
/// </summary>
[Fact]
public void ResolveWinmdWithInvalidPENativeDependency()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
TaskItem item = new TaskItem(@"DependsOnInvalidPeHeader");
ITaskItem[] assemblyFiles = new TaskItem[] { item };
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.SearchPaths = new String[] { @"C:\WinMDArchVerification" };
bool succeeded = Execute(t);
// Should fail since PE Header is not valid and this is always an error.
Assert.False(succeeded);
Assert.Equal(1, engine.Errors);
Assert.Equal(0, engine.Warnings);
// The original winmd will resolve but its implementation dll must not be there
Assert.Single(t.ResolvedFiles);
Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
string invalidPEMessage = ResourceUtilities.GetResourceString("ResolveAssemblyReference.ImplementationDllHasInvalidPEHeader");
string fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.ProblemReadingImplementationDll", @"C:\WinMDArchVerification\DependsOnInvalidPeHeader.dll", invalidPEMessage);
engine.AssertLogContains(fullMessage);
}
/// <summary>
/// Resolve a winmd file which depends a native dll that matches the targeted architecture
/// </summary>
[Fact]
public void ResolveWinmdWithArchitectureDependencyMatchingArchitecturesX86()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
TaskItem item = new TaskItem("DependsOnX86");
ITaskItem[] assemblyFiles = new TaskItem[] { item };
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.SearchPaths = new String[] { @"C:\WinMDArchVerification" };
t.TargetProcessorArchitecture = "X86";
t.WarnOrErrorOnTargetArchitectureMismatch = "Error";
bool succeeded = Execute(t);
Assert.Single(t.ResolvedFiles);
Assert.Equal(@"C:\WinMDArchVerification\DependsOnX86.winmd", t.ResolvedFiles[0].ItemSpec);
Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));
Assert.True(succeeded);
Assert.Equal("DependsOnX86.dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
}
/// <summary>
/// Resolve a winmd file which depends a native dll that matches the targeted architecture
/// </summary>
[Fact]
public void ResolveWinmdWithArchitectureDependencyAnyCPUNative()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
// IMAGE_FILE_MACHINE unknown is supposed to work on all machine types
TaskItem item = new TaskItem("DependsOnAnyCPUUnknown");
ITaskItem[] assemblyFiles = new TaskItem[] { item };
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.SearchPaths = new String[] { @"C:\WinMDArchVerification" };
t.TargetProcessorArchitecture = "X86";
t.WarnOrErrorOnTargetArchitectureMismatch = "Error";
bool succeeded = Execute(t);
Assert.Single(t.ResolvedFiles);
Assert.Equal(@"C:\WinMDArchVerification\DependsOnAnyCPUUnknown.winmd", t.ResolvedFiles[0].ItemSpec);
Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));
Assert.True(succeeded);
Assert.Equal("DependsOnAnyCPUUnknown.dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
}
/// <summary>
/// Resolve a winmd file which depends on a native implementation dll that has an invalid pe header.
/// A warning or error is expected in the log depending on the WarnOrErrorOnTargetArchitecture property value.
/// </summary>
[Fact]
public void ResolveWinmdWithArchitectureDependency()
{
VerifyImplementationArchitecture("DependsOnX86", "MSIL", "X86", "Error");
VerifyImplementationArchitecture("DependsOnX86", "MSIL", "X86", "Warning");
VerifyImplementationArchitecture("DependsOnX86", "MSIL", "X86", "None");
VerifyImplementationArchitecture("DependsOnX86", "AMD64", "X86", "Error");
VerifyImplementationArchitecture("DependsOnX86", "AMD64", "X86", "Warning");
VerifyImplementationArchitecture("DependsOnX86", "AMD64", "X86", "None");
VerifyImplementationArchitecture("DependsOnAmd64", "MSIL", "AMD64", "Error");
VerifyImplementationArchitecture("DependsOnAmd64", "MSIL", "AMD64", "Warning");
VerifyImplementationArchitecture("DependsOnAmd64", "MSIL", "AMD64", "None");
VerifyImplementationArchitecture("DependsOnAmd64", "X86", "AMD64", "Error");
VerifyImplementationArchitecture("DependsOnAmd64", "X86", "AMD64", "Warning");
VerifyImplementationArchitecture("DependsOnAmd64", "X86", "AMD64", "None");
VerifyImplementationArchitecture("DependsOnARM", "MSIL", "ARM", "Error");
VerifyImplementationArchitecture("DependsOnARM", "MSIL", "ARM", "Warning");
VerifyImplementationArchitecture("DependsOnARM", "MSIL", "ARM", "None");
VerifyImplementationArchitecture("DependsOnARMV7", "MSIL", "ARM", "Error");
VerifyImplementationArchitecture("DependsOnARMV7", "MSIL", "ARM", "Warning");
VerifyImplementationArchitecture("DependsOnARMv7", "MSIL", "ARM", "None");
VerifyImplementationArchitecture("DependsOnIA64", "MSIL", "IA64", "Error");
VerifyImplementationArchitecture("DependsOnIA64", "MSIL", "IA64", "Warning");
VerifyImplementationArchitecture("DependsOnIA64", "MSIL", "IA64", "None");
VerifyImplementationArchitecture("DependsOnUnknown", "MSIL", "Unknown", "Error");
VerifyImplementationArchitecture("DependsOnUnknown", "MSIL", "Unknown", "Warning");
VerifyImplementationArchitecture("DependsOnUnknown", "MSIL", "Unknown", "None");
}
private void VerifyImplementationArchitecture(string winmdName, string targetProcessorArchitecture, string implementationFileArch, string warnOrErrorOnTargetArchitectureMismatch)
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
TaskItem item = new TaskItem(winmdName);
ITaskItem[] assemblyFiles = new TaskItem[] { item };
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.SearchPaths = new String[] { @"C:\WinMDArchVerification" };
t.TargetProcessorArchitecture = targetProcessorArchitecture;
t.WarnOrErrorOnTargetArchitectureMismatch = warnOrErrorOnTargetArchitectureMismatch;
bool succeeded = Execute(t);
Assert.Single(t.ResolvedFiles);
Assert.Equal(@"C:\WinMDArchVerification\" + winmdName + ".winmd", t.ResolvedFiles[0].ItemSpec);
Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
Assert.True(bool.Parse(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));
string fullMessage = null;
if (implementationFileArch.Equals("Unknown"))
{
fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.UnknownProcessorArchitecture", @"C:\WinMDArchVerification\" + winmdName + ".dll", @"C:\WinMDArchVerification\" + winmdName + ".winmd", NativeMethods.IMAGE_FILE_MACHINE_R4000.ToString("X", CultureInfo.InvariantCulture));
}
else
{
fullMessage = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("ResolveAssemblyReference.MismatchBetweenTargetedAndReferencedArchOfImplementation", targetProcessorArchitecture, implementationFileArch, @"C:\WinMDArchVerification\" + winmdName + ".dll", @"C:\WinMDArchVerification\" + winmdName + ".winmd");
}
if (warnOrErrorOnTargetArchitectureMismatch.Equals("None", StringComparison.OrdinalIgnoreCase))
{
engine.AssertLogDoesntContain(fullMessage);
}
else
{
engine.AssertLogContains(fullMessage);
}
if (warnOrErrorOnTargetArchitectureMismatch.Equals("Warning", StringComparison.OrdinalIgnoreCase))
{
// Should fail since PE Header is not valid and this is always an error.
Assert.True(succeeded);
Assert.Equal(winmdName + ".dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
Assert.Equal(0, engine.Errors);
Assert.Equal(1, engine.Warnings);
}
else if (warnOrErrorOnTargetArchitectureMismatch.Equals("Error", StringComparison.OrdinalIgnoreCase))
{
// Should fail since PE Header is not valid and this is always an error.
Assert.False(succeeded);
Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
Assert.Equal(1, engine.Errors);
Assert.Equal(0, engine.Warnings);
}
else if (warnOrErrorOnTargetArchitectureMismatch.Equals("None", StringComparison.OrdinalIgnoreCase))
{
Assert.True(succeeded);
Assert.Equal(winmdName + ".dll", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winmdImplmentationFile));
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
}
}
/// <summary>
/// Verify when a winmd file depends on another winmd file that we resolve both and that the metadata is correct.
/// </summary>
[Fact]
public void DotNetAssemblyDependsOnAWinMDFileWithVersion255()
{
// Create the engine.
MockEngine engine = new MockEngine(_output);
ITaskItem[] assemblyFiles = new TaskItem[]
{
new TaskItem(@"DotNetAssemblyDependsOn255WinMD")
};
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyFiles;
t.SearchPaths = new String[] { @"C:\WinMD", @"C:\WinMD\v4\", @"C:\WinMD\v255\" };
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Single(t.ResolvedFiles);
Assert.Single(t.ResolvedDependencyFiles);
Assert.Equal(0, engine.Errors);
Assert.Equal(0, engine.Warnings);
Assert.Equal(@"C:\WinMD\DotNetAssemblyDependsOn255WinMD.dll", t.ResolvedFiles[0].ItemSpec);
Assert.Equal(@"v2.0.50727", t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
Assert.Empty(t.ResolvedFiles[0].GetMetadata(ItemMetadataNames.winMDFile));
Assert.Equal(@"C:\WinMD\WinMDWithVersion255.winmd", t.ResolvedDependencyFiles[0].ItemSpec);
Assert.Equal(@"WindowsRuntime 1.0", t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.imageRuntime));
Assert.True(bool.Parse(t.ResolvedDependencyFiles[0].GetMetadata(ItemMetadataNames.winMDFile)));
}
#endregion
}
}
| |
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Build
{
public sealed class TeeCommandManager : TfsVCCommandManager, ITfsVCCommandManager
{
public override TfsVCFeatures Features => TfsVCFeatures.Eula;
protected override string Switch => "-";
public string FilePath => Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.TeeDirectory, "tf");
// 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, "add", localPath);
}
public void CleanupProxySetting()
{
// no-op for TEE.
}
public async Task EulaAsync()
{
await RunCommandAsync(FormatFlags.All, "eula", "-accept");
}
public async Task GetAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunCommandAsync(FormatFlags.OmitCollectionUrl, "get", $"-version:{SourceVersion}", "-recursive", "-overwrite", localPath);
}
public string ResolvePath(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
string localPath = RunPorcelainCommandAsync("resolvePath", $"-workspace:{WorkspaceName}", serverPath).GetAwaiter().GetResult();
localPath = localPath?.Trim();
// Paths outside of the root mapping return empty.
// Paths within a cloaked directory return "null".
if (string.IsNullOrEmpty(localPath) ||
string.Equals(localPath, "null", StringComparison.OrdinalIgnoreCase))
{
return string.Empty;
}
return localPath;
}
public Task ScorchAsync()
{
throw new NotSupportedException();
}
public void SetupProxy(string proxyUrl, string proxyUsername, string proxyPassword)
{
if (!string.IsNullOrEmpty(proxyUrl))
{
Uri proxy = UrlUtil.GetCredentialEmbeddedUrl(new Uri(proxyUrl), proxyUsername, proxyPassword);
AdditionalEnvironmentVariables["http_proxy"] = proxy.AbsoluteUri;
}
}
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, "shelve", $"-workspace:{WorkspaceName}", "-move", "-replace", "-recursive", $"-comment:@{commentFile}", shelveset);
return;
}
await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "shelve", $"-workspace:{WorkspaceName}", "-saved", "-replace", "-recursive", $"-comment:@{commentFile}", shelveset);
}
public async Task<ITfsVCShelveset> ShelvesetsAsync(string shelveset)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
string output = await RunPorcelainCommandAsync("shelvesets", "-format:xml", $"-workspace:{WorkspaceName}", shelveset);
string xml = ExtractXml(output);
// 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(TeeShelvesets));
ArgUtil.NotNullOrEmpty(xml, nameof(xml));
using (var reader = new StringReader(xml))
{
var teeShelvesets = serializer.Deserialize(reader) as TeeShelvesets;
ArgUtil.NotNull(teeShelvesets, nameof(teeShelvesets));
ArgUtil.NotNull(teeShelvesets.Shelvesets, nameof(teeShelvesets.Shelvesets));
ArgUtil.Equal(1, teeShelvesets.Shelvesets.Length, nameof(teeShelvesets.Shelvesets.Length));
return teeShelvesets.Shelvesets[0];
}
}
public async Task<ITfsVCStatus> StatusAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
string output = await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "status", "-recursive", "-nodetect", "-format:xml", localPath);
string xml = ExtractXml(output);
var serializer = new XmlSerializer(typeof(TeeStatus));
using (var reader = new StringReader(xml ?? string.Empty))
{
return serializer.Deserialize(reader) as TeeStatus;
}
}
public bool TestEulaAccepted()
{
Trace.Entering();
// Resolve the path to the XML file containing the EULA-accepted flag.
string homeDirectory = Environment.GetEnvironmentVariable("HOME");
if (!string.IsNullOrEmpty(homeDirectory) && Directory.Exists(homeDirectory))
{
#if OS_OSX
string xmlFile = Path.Combine(
homeDirectory,
"Library",
"Application Support",
"Microsoft",
"Team Foundation",
"4.0",
"Configuration",
"TEE-Mementos",
"com.microsoft.tfs.client.productid.xml");
#else
string xmlFile = Path.Combine(
homeDirectory,
".microsoft",
"Team Foundation",
"4.0",
"Configuration",
"TEE-Mementos",
"com.microsoft.tfs.client.productid.xml");
#endif
if (File.Exists(xmlFile))
{
// Load and deserialize the XML.
string xml = File.ReadAllText(xmlFile, Encoding.UTF8);
XmlSerializer serializer = new XmlSerializer(typeof(ProductIdData));
using (var reader = new StringReader(xml ?? string.Empty))
{
var data = serializer.Deserialize(reader) as ProductIdData;
return string.Equals(data?.Eula?.Value ?? string.Empty, "true", StringComparison.OrdinalIgnoreCase);
}
}
}
return false;
}
public async Task<bool> TryWorkspaceDeleteAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
try
{
await RunCommandAsync("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, "undo", "-recursive", localPath);
}
public async Task UnshelveAsync(string shelveset)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
await RunCommandAsync("unshelve", "-format:detailed", $"-workspace:{WorkspaceName}", shelveset);
}
public async Task WorkfoldCloakAsync(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
await RunCommandAsync("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("workfold", "-map", $"-workspace:{WorkspaceName}", serverPath, localPath);
}
public Task WorkfoldUnmapAsync(string serverPath)
{
throw new NotSupportedException();
}
public async Task WorkspaceDeleteAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
await RunCommandAsync("workspace", "-delete", $"{workspace.Name};{workspace.Owner}");
}
public async Task WorkspaceNewAsync()
{
await RunCommandAsync("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("workspaces");
if (matchWorkspaceNameOnAnyComputer)
{
args.Add(WorkspaceName);
args.Add($"-computer:*");
}
args.Add("-format:xml");
// Run the command.
TfsVCPorcelainCommandResult result = await TryRunPorcelainCommandAsync(FormatFlags.None, args.ToArray());
ArgUtil.NotNull(result, nameof(result));
if (result.Exception != null)
{
// Check if the workspace name was specified and the command returned exit code 1.
if (matchWorkspaceNameOnAnyComputer && result.Exception.ExitCode == 1)
{
// Ignore the error. This condition can indicate the workspace was not found.
return new ITfsVCWorkspace[0];
}
// Dump the output and throw.
result.Output?.ForEach(x => ExecutionContext.Output(x ?? string.Empty));
throw result.Exception;
}
// Note, string.join gracefully handles a null element within the IEnumerable<string>.
string output = string.Join(Environment.NewLine, result.Output ?? new List<string>()) ?? string.Empty;
string xml = ExtractXml(output);
// Deserialize the XML.
var serializer = new XmlSerializer(typeof(TeeWorkspaces));
using (var reader = new StringReader(xml))
{
return (serializer.Deserialize(reader) as TeeWorkspaces)
?.Workspaces
?.Cast<ITfsVCWorkspace>()
.ToArray();
}
}
public async Task WorkspacesRemoveAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
await RunCommandAsync("workspace", $"-remove:{workspace.Name};{workspace.Owner}");
}
private static string ExtractXml(string output)
{
// tf commands that output XML, may contain information messages preceeding the XML content.
//
// For example, the workspaces subcommand returns a non-XML message preceeding the XML when there are no workspaces.
//
// Also for example, when JAVA_TOOL_OPTIONS is set, a message like "Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8"
// may preceed the XML content.
output = output ?? string.Empty;
int xmlIndex = output.IndexOf("<?xml");
if (xmlIndex > 0) {
return output.Substring(xmlIndex);
}
return output;
}
////////////////////////////////////////////////////////////////////////////////
// Product ID data objects (required for testing whether the EULA has been accepted).
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "ProductIdData", Namespace = "")]
public sealed class ProductIdData
{
[XmlElement(ElementName = "eula-14.0", Namespace = "")]
public Eula Eula { get; set; }
}
public sealed class Eula
{
[XmlAttribute(AttributeName = "value", Namespace = "")]
public string Value { get; set; }
}
}
////////////////////////////////////////////////////////////////////////////////
// tf shelvesets data objects
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "shelvesets", Namespace = "")]
public sealed class TeeShelvesets
{
[XmlElement(ElementName = "shelveset", Namespace = "")]
public TeeShelveset[] Shelvesets { get; set; }
}
public sealed class TeeShelveset : ITfsVCShelveset
{
[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; }
[XmlElement(ElementName = "comment", Namespace = "")]
public string Comment { get; set; }
}
////////////////////////////////////////////////////////////////////////////////
// tf status data objects.
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "status", Namespace = "")]
public sealed class TeeStatus : ITfsVCStatus
{
// Elements.
[XmlArray(ElementName = "candidate-pending-changes", Namespace = "")]
[XmlArrayItem(ElementName = "pending-change", Namespace = "")]
public TeePendingChange[] CandidatePendingChanges { get; set; }
[XmlArray(ElementName = "pending-changes", Namespace = "")]
[XmlArrayItem(ElementName = "pending-change", Namespace = "")]
public TeePendingChange[] PendingChanges { get; set; }
// Interface-only properties.
[XmlIgnore]
public IEnumerable<ITfsVCPendingChange> AllAdds
{
get
{
return PendingChanges?.Where(x => string.Equals(x.ChangeType, "add", StringComparison.OrdinalIgnoreCase));
}
}
[XmlIgnore]
public bool HasPendingChanges => PendingChanges?.Any() ?? false;
}
public sealed class TeePendingChange : ITfsVCPendingChange
{
[XmlAttribute(AttributeName = "change-type", Namespace = "")]
public string ChangeType { get; set; }
[XmlAttribute(AttributeName = "computer", Namespace = "")]
public string Computer { get; set; }
[XmlAttribute(AttributeName = "date", Namespace = "")]
public string Date { get; set; }
[XmlAttribute(AttributeName = "file-type", Namespace = "")]
public string FileType { get; set; }
[XmlAttribute(AttributeName = "local-item", Namespace = "")]
public string LocalItem { get; set; }
[XmlAttribute(AttributeName = "lock", Namespace = "")]
public string Lock { get; set; }
[XmlAttribute(AttributeName = "owner", Namespace = "")]
public string Owner { get; set; }
[XmlAttribute(AttributeName = "server-item", Namespace = "")]
public string ServerItem { get; set; }
[XmlAttribute(AttributeName = "version", Namespace = "")]
public string Version { get; set; }
[XmlAttribute(AttributeName = "workspace", Namespace = "")]
public string Workspace { get; set; }
}
////////////////////////////////////////////////////////////////////////////////
// tf workspaces data objects.
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "workspaces", Namespace = "")]
public sealed class TeeWorkspaces
{
[XmlElement(ElementName = "workspace", Namespace = "")]
public TeeWorkspace[] Workspaces { get; set; }
}
public sealed class TeeWorkspace : ITfsVCWorkspace
{
// Attributes.
[XmlAttribute(AttributeName = "server", Namespace = "")]
public string CollectionUrl { get; set; }
[XmlAttribute(AttributeName = "comment", Namespace = "")]
public string Comment { get; set; }
[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; }
// Elements.
[XmlElement(ElementName = "working-folder", Namespace = "")]
public TeeMapping[] TeeMappings { get; set; }
// Interface-only properties.
[XmlIgnore]
public ITfsVCMapping[] Mappings => TeeMappings?.Cast<ITfsVCMapping>().ToArray();
}
public sealed class TeeMapping : ITfsVCMapping
{
[XmlIgnore]
public bool Cloak => string.Equals(MappingType, "cloak", StringComparison.OrdinalIgnoreCase);
[XmlAttribute(AttributeName = "depth", Namespace = "")]
public string Depth { get; set; }
[XmlAttribute(AttributeName = "local-item", Namespace = "")]
public string LocalPath { get; set; }
[XmlAttribute(AttributeName = "type", Namespace = "")]
public string MappingType { get; set; }
[XmlIgnore]
public bool Recursive => string.Equals(Depth, "full", StringComparison.OrdinalIgnoreCase);
[XmlAttribute(AttributeName = "server-item")]
public string ServerPath { get; set; }
}
}
| |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using PurdueIo.CatalogSync;
using PurdueIo.Database;
using PurdueIo.Scraper;
using PurdueIo.Tests.Mocks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using DaysOfWeek = PurdueIo.Scraper.Models.DaysOfWeek;
using ScrapedMeeting = PurdueIo.Scraper.Models.Meeting;
using ScrapedSection = PurdueIo.Scraper.Models.Section;
using ScrapedSubject = PurdueIo.Scraper.Models.Subject;
using ScrapedTerm = PurdueIo.Scraper.Models.Term;
namespace PurdueIo.Tests
{
public class SynchronizerTests
{
private readonly ILoggerFactory loggerFactory;
public SynchronizerTests()
{
this.loggerFactory = new NullLoggerFactory();
}
[Fact]
public async Task BasicSectionSyncTest()
{
var dbContextFactory = GetDbContextFactory();
var testSection = GenerateSection();
var testMeeting = testSection.Section.Meetings.FirstOrDefault();
var scraper = GetScraper(testSection.Section);
var term = (await scraper.GetTermsAsync()).FirstOrDefault();
var subject = (await scraper.GetSubjectsAsync(term.Id)).FirstOrDefault();
using (var dbContext = dbContextFactory())
{
await FastSync.SynchronizeAsync(scraper, dbContext,
loggerFactory.CreateLogger<FastSync>());
}
using (var dbContext = dbContextFactory())
{
// Ensure the section and all related entities are properly persisted in the DB
// Term
Assert.NotNull(dbContext.Terms.SingleOrDefault(t => t.Code == term.Id));
Assert.Equal(testMeeting.StartDate,
dbContext.Terms.SingleOrDefault(t => t.Code == term.Id).StartDate);
Assert.Equal(testMeeting.EndDate,
dbContext.Terms.SingleOrDefault(t => t.Code == term.Id).EndDate);
// Subject
Assert.NotNull(dbContext.Subjects.SingleOrDefault(s =>
(s.Abbreviation == subject.Code) && (s.Name == subject.Name)));
// Course
Assert.NotNull(dbContext.Courses.SingleOrDefault(c =>
(c.Number == testSection.Course.Number) &&
(c.Title == testSection.Course.Name) &&
(c.CreditHours == testSection.Course.CreditHours) &&
(c.Description == testSection.Course.Description) &&
(c.Subject.Abbreviation == subject.Code)));
// Campus
Assert.NotNull(dbContext.Campuses.SingleOrDefault(c =>
(c.Code == testSection.Campus.Code) &&
(c.Name == testSection.Campus.Name)));
// Class
Assert.NotNull(dbContext.Classes.SingleOrDefault(c =>
(c.Term.Code == term.Id) &&
(c.Campus.Code == testSection.Campus.Code) &&
(c.Course.Number == testSection.Course.Number) &&
(c.Course.Title == testSection.Course.Name) &&
(c.Course.Subject.Abbreviation == subject.Code)));
// Building
Assert.NotNull(dbContext.Buildings.SingleOrDefault(b =>
(b.Name == testSection.Room.Building.Name) &&
(b.ShortCode == testSection.Room.Building.Code)));
// Room
Assert.NotNull(dbContext.Rooms.SingleOrDefault(r =>
(r.Building.ShortCode == testSection.Room.Building.Code) &&
(r.Number == testSection.Room.Number)));
// Section
Assert.NotNull(dbContext.Sections.SingleOrDefault(s =>
(s.Crn == testSection.Section.Crn) &&
(s.Type == testSection.Section.Type) &&
(s.StartDate == testMeeting.StartDate) &&
(s.EndDate == testMeeting.EndDate) &&
(s.Capacity == testSection.Section.Capacity) &&
(s.Enrolled == testSection.Section.Enrolled) &&
(s.RemainingSpace == testSection.Section.RemainingSpace) &&
(s.WaitListCapacity == testSection.Section.WaitListCapacity) &&
(s.WaitListCount == testSection.Section.WaitListCount) &&
(s.WaitListSpace == testSection.Section.WaitListSpace)));
// Instructor
Assert.NotNull(dbContext.Instructors.SingleOrDefault(i =>
(i.Email == testMeeting.Instructors.First().email) &&
(i.Name == testMeeting.Instructors.First().name)));
// Meeting
Assert.NotNull(dbContext.Meetings.SingleOrDefault(m =>
(m.Section.Crn == testSection.Section.Crn) &&
(m.Instructors.First().Email == testMeeting.Instructors.First().email) &&
(m.Type == testMeeting.Type) &&
(m.StartDate == testMeeting.StartDate) &&
(m.EndDate == testMeeting.EndDate) &&
((DaysOfWeek)m.DaysOfWeek == testMeeting.DaysOfWeek) &&
(m.StartTime == testMeeting.StartTime) &&
(m.Duration == testMeeting.EndTime.Subtract(testMeeting.StartTime)) &&
(m.Room.Number == testSection.Room.Number) &&
(m.Room.Building.ShortCode == testSection.Room.Building.Code)));
}
}
[Fact]
public async Task MultipleSectionClassSyncTest()
{
var dbContextFactory = GetDbContextFactory();
var lectureSection = GenerateSection(type: "Lecture", linkSelf: "A0",
linkOther: "A1");
var recitationSection = GenerateSection(course: lectureSection.Course,
campus: lectureSection.Campus, type: "Recitation", linkSelf: "A1",
linkOther: "A2");
var labSection = GenerateSection(course: lectureSection.Course,
campus: lectureSection.Campus, type: "Laboratory", linkSelf: "A2",
linkOther: "A0");
var scraper = GetScraper(new List<ScrapedSection>() {
lectureSection.Section, recitationSection.Section, labSection.Section });
using (var dbContext = dbContextFactory())
{
await FastSync.SynchronizeAsync(scraper, dbContext,
loggerFactory.CreateLogger<FastSync>());
}
using (var dbContext = dbContextFactory())
{
Assert.NotNull(dbContext.Courses.SingleOrDefault(c =>
(c.Number == lectureSection.Course.Number) &&
(c.Title == lectureSection.Course.Name)));
Assert.NotNull(dbContext.Classes.SingleOrDefault(c =>
(c.Course.Number == lectureSection.Course.Number) &&
(c.Course.Title == lectureSection.Course.Name) &&
(c.Sections.Any(s => (s.Crn == lectureSection.Section.Crn))) &&
(c.Sections.Any(s => (s.Crn == recitationSection.Section.Crn))) &&
(c.Sections.Any(s => (s.Crn == labSection.Section.Crn)))));
}
}
[Fact]
public async Task InstructorAddRemoveSyncTest()
{
var dbContextFactory = GetDbContextFactory();
var instructors = new List<TestInstructor>()
{
GenerateInstructor(),
GenerateInstructor(),
GenerateInstructor(),
};
var section = GenerateSection(instructors: instructors);
var scraper = GetScraper(section.Section);
using (var dbContext = dbContextFactory())
{
await FastSync.SynchronizeAsync(scraper, dbContext,
loggerFactory.CreateLogger<FastSync>());
}
// Confirm that all instructors were synchronized
using (var dbContext = dbContextFactory())
{
var dbSection = dbContext.Sections
.Include(s => s.Meetings)
.ThenInclude(m => m.Instructors)
.SingleOrDefault(s => s.Crn == section.Section.Crn);
Assert.NotNull(dbSection);
var dbMeeting = dbSection.Meetings.FirstOrDefault();
Assert.NotNull(dbMeeting);
foreach (var instructor in instructors)
{
Assert.Single(dbMeeting.Instructors, i => (i.Email == instructor.Email));
}
}
// Remove an instructor and sync again
var removedInstructor = instructors.LastOrDefault();
instructors.RemoveAt(instructors.Count - 1);
section.Section.Meetings[0] = section.Section.Meetings[0] with {
Instructors = section.Section.Meetings[0].Instructors
.Where(i => (i.email != removedInstructor.Email)).ToArray() };
scraper = GetScraper(section.Section);
using (var dbContext = dbContextFactory())
{
await FastSync.SynchronizeAsync(scraper, dbContext,
loggerFactory.CreateLogger<FastSync>());
}
// Confirm that the instructor was removed
using (var dbContext = dbContextFactory())
{
var dbSection = dbContext.Sections
.Include(s => s.Meetings)
.ThenInclude(m => m.Instructors)
.SingleOrDefault(s => s.Crn == section.Section.Crn);
Assert.NotNull(dbSection);
var dbMeeting = dbSection.Meetings.FirstOrDefault();
Assert.NotNull(dbMeeting);
Assert.Equal(instructors.Count, dbMeeting.Instructors.Count);
foreach (var instructor in instructors)
{
Assert.Single(dbMeeting.Instructors, i => (i.Email == instructor.Email));
}
Assert.DoesNotContain(dbMeeting.Instructors,
i => (i.Email == removedInstructor.Email));
}
// Add a new instructor and sync again
var newInstructor = GenerateInstructor();
instructors.Add(newInstructor);
section.Section.Meetings[0] = section.Section.Meetings[0] with {
Instructors = section.Section.Meetings[0].Instructors
.Concat(new (string name, string email)[] {
(newInstructor.Name, newInstructor.Email) }).ToArray() };
scraper = GetScraper(section.Section);
using (var dbContext = dbContextFactory())
{
await FastSync.SynchronizeAsync(scraper, dbContext,
loggerFactory.CreateLogger<FastSync>());
}
// Confirm all the expected instructors were synchronized
using (var dbContext = dbContextFactory())
{
var dbSection = dbContext.Sections
.Include(s => s.Meetings)
.ThenInclude(m => m.Instructors)
.SingleOrDefault(s => s.Crn == section.Section.Crn);
Assert.NotNull(dbSection);
var dbMeeting = dbSection.Meetings.FirstOrDefault();
Assert.NotNull(dbMeeting);
Assert.Equal(instructors.Count, dbMeeting.Instructors.Count);
foreach (var instructor in instructors)
{
Assert.Single(dbMeeting.Instructors, i => (i.Email == instructor.Email));
}
}
}
[Fact]
public async Task SectionAddRemoveSyncTest()
{
var dbContextFactory = GetDbContextFactory();
// Sync a class with two sections
var lectureSection = GenerateSection(type: "Lecture", linkSelf: "A0",
linkOther: "A1");
var recitationSection = GenerateSection(course: lectureSection.Course,
campus: lectureSection.Campus, type: "Recitation", linkSelf: "A1",
linkOther: "A0");
var scraper = GetScraper(new List<ScrapedSection>() {
lectureSection.Section, recitationSection.Section });
using (var dbContext = dbContextFactory())
{
await FastSync.SynchronizeAsync(scraper, dbContext,
loggerFactory.CreateLogger<FastSync>());
}
// Confirm class w/ two sections was properly synced
using (var dbContext = dbContextFactory())
{
Assert.NotNull(dbContext.Courses.SingleOrDefault(c =>
(c.Number == lectureSection.Course.Number) &&
(c.Title == lectureSection.Course.Name)));
Assert.NotNull(dbContext.Classes.SingleOrDefault(c =>
(c.Course.Number == lectureSection.Course.Number) &&
(c.Course.Title == lectureSection.Course.Name) &&
(c.Sections.Count == 2) &&
(c.Sections.Any(s => (s.Crn == lectureSection.Section.Crn))) &&
(c.Sections.Any(s => (s.Crn == recitationSection.Section.Crn)))));
}
// Add a new section to the class and sync again
var labSection = GenerateSection(course: lectureSection.Course,
campus: lectureSection.Campus, type: "Laboratory", linkSelf: "A2",
linkOther: "A0");
recitationSection.Section = recitationSection.Section with { LinkOther = "A2" };
scraper = GetScraper(new List<ScrapedSection>() {
lectureSection.Section, recitationSection.Section, labSection.Section });
using (var dbContext = dbContextFactory())
{
await FastSync.SynchronizeAsync(scraper, dbContext,
loggerFactory.CreateLogger<FastSync>());
}
// Confirm all three sections are synced
using (var dbContext = dbContextFactory())
{
Assert.NotNull(dbContext.Classes.SingleOrDefault(c =>
(c.Course.Number == lectureSection.Course.Number) &&
(c.Course.Title == lectureSection.Course.Name) &&
(c.Sections.Count == 3) &&
(c.Sections.Any(s => (s.Crn == lectureSection.Section.Crn))) &&
(c.Sections.Any(s => (s.Crn == recitationSection.Section.Crn))) &&
(c.Sections.Any(s => (s.Crn == labSection.Section.Crn)))));
}
// Remove a section and sync again
labSection.Section = labSection.Section with { LinkSelf = "A1", LinkOther = "A0" };
scraper = GetScraper(new List<ScrapedSection>() {
lectureSection.Section, labSection.Section });
using (var dbContext = dbContextFactory())
{
await FastSync.SynchronizeAsync(scraper, dbContext,
loggerFactory.CreateLogger<FastSync>());
}
// Confirm only two sections are now part of the class, and that the third has
// been removed.
using (var dbContext = dbContextFactory())
{
Assert.NotNull(dbContext.Classes.SingleOrDefault(c =>
(c.Course.Number == lectureSection.Course.Number) &&
(c.Course.Title == lectureSection.Course.Name) &&
(c.Sections.Count == 2) &&
(c.Sections.Any(s => (s.Crn == lectureSection.Section.Crn))) &&
(c.Sections.Any(s => (s.Crn == labSection.Section.Crn)))));
Assert.Null(dbContext.Sections
.SingleOrDefault(s => (s.Crn == recitationSection.Section.Crn)));
}
// Remove all sections and sync again
scraper = GetScraper(new List<ScrapedSection>() { });
using (var dbContext = dbContextFactory())
{
await FastSync.SynchronizeAsync(scraper, dbContext,
loggerFactory.CreateLogger<FastSync>());
}
// Confirm that there are no more sections, and the class has been removed
using (var dbContext = dbContextFactory())
{
Assert.Equal(0, dbContext.Sections.Count());
Assert.Equal(0, dbContext.Meetings.Count());
Assert.Null(dbContext.Classes.SingleOrDefault(c =>
(c.Course.Number == lectureSection.Course.Number) &&
(c.Course.Title == lectureSection.Course.Name)));
}
}
private class TestSubject
{
public string Code;
public string Name;
}
private class TestCourse
{
public TestSubject Subject;
public string Number;
public string Name;
public string Description;
public double CreditHours;
}
private class TestInstructor
{
public string Name;
public string Email;
}
private class TestSection
{
public ICollection<TestInstructor> Instructors;
public TestCourse Course;
public TestCampus Campus;
public TestRoom Room;
public ScrapedSection Section;
}
private class TestCampus
{
public string Name;
public string Code;
}
private class TestBuilding
{
public string Name;
public string Code;
}
private class TestRoom
{
public string Number;
public TestBuilding Building;
}
private char lastGeneratedSubjectCodeSuffix = 'A';
private int lastGeneratedCourseNumber = 0;
private int lastGeneratedCrnNumber = 0;
private char lastGeneratedInstructorSuffix = 'A';
private char lastGeneratedCampusSuffix = 'A';
private char lastGeneratedBuildingSuffix = 'A';
private int lastGeneratedRoomNumber = 0;
private readonly (string name, string code) DefaultTerm = ("Fall 2021", "202210");
private readonly (string name, string code) DefaultSubject = ("Test Subject", "TEST");
private readonly TimeZoneInfo timeZone =
TimeZoneInfo.GetSystemTimeZones().Any(t => (t.Id == "Eastern Standard Time"))
? TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
: TimeZoneInfo.FindSystemTimeZoneById("America/Indianapolis");
private Func<ApplicationDbContext> GetDbContextFactory(string path = "")
{
if (path == "")
{
path = Path.GetTempFileName();
}
var loggerFactory = new LoggerFactory(new[] {
new Microsoft.Extensions.Logging.Debug.DebugLoggerProvider()
});
var dbOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseSqlite($"Data Source={path}",
s => s.MigrationsAssembly("Database.Migrations.Sqlite"))
.UseLoggerFactory(loggerFactory)
.Options;
return () => {
var retVal = new ApplicationDbContext(dbOptions);
retVal.Database.Migrate();
return retVal;
};
}
private IScraper GetScraper(ScrapedSection section)
{
return GetScraper(new List<ScrapedSection>() { section });
}
private IScraper GetScraper(ICollection<ScrapedSection> sections)
{
return new MockScraper(
new List<ScrapedTerm>()
{
new ScrapedTerm()
{
Id = DefaultTerm.code,
Name = DefaultTerm.name,
}
},
new List<ScrapedSubject>()
{
new ScrapedSubject()
{
Code = DefaultSubject.code,
Name = DefaultSubject.name,
}
},
sections);
}
private TestSubject GenerateSubject()
{
var subjectCodeSuffix = lastGeneratedSubjectCodeSuffix++;
return new TestSubject()
{
Code = $"T{subjectCodeSuffix}",
Name = $"Test Subject {subjectCodeSuffix}",
};
}
private TestCourse GenerateCourse(TestSubject subject = null, double creditHours = 3.14)
{
if (subject == null)
{
subject = GenerateSubject();
}
var courseNum = lastGeneratedCourseNumber++;
return new TestCourse()
{
Subject = subject,
Number = $"{courseNum}",
Name = $"Test Course {courseNum}",
Description = $"This is test course number {courseNum}",
CreditHours = creditHours,
};
}
private TestInstructor GenerateInstructor()
{
var instructorSuffix = lastGeneratedInstructorSuffix++;
return new TestInstructor()
{
Name = $"Instructor {instructorSuffix}",
Email = $"instructor{instructorSuffix}@university.edu",
};
}
private TestCampus GenerateCampus()
{
var campusSuffix = lastGeneratedCampusSuffix++;
return new TestCampus()
{
Name = $"Campus {campusSuffix}",
Code = $"C{campusSuffix}",
};
}
private TestBuilding GenerateBuilding()
{
var buildingSuffix = lastGeneratedBuildingSuffix++;
return new TestBuilding()
{
Name = $"Test Building {buildingSuffix}",
Code = $"B{buildingSuffix}",
};
}
private TestRoom GenerateRoom(TestBuilding building = null)
{
var roomNumber = lastGeneratedRoomNumber++;
if (building == null)
{
building = GenerateBuilding();
}
return new TestRoom()
{
Number = $"{roomNumber}",
Building = building,
};
}
private TestSection GenerateSection(ICollection<TestInstructor> instructors = null,
TestCourse course = null, TestCampus campus = null, string type = "Lecture",
TestRoom room = null, string linkSelf = "", string linkOther = "")
{
var crn = lastGeneratedCrnNumber++;
if (instructors == null)
{
instructors = new List<TestInstructor>()
{
GenerateInstructor(),
};
}
if (course == null)
{
course = GenerateCourse();
}
if (campus == null)
{
campus = GenerateCampus();
}
if (room == null)
{
room = GenerateRoom();
}
return new TestSection()
{
Instructors = instructors,
Course = course,
Campus = campus,
Room = room,
Section = new ScrapedSection()
{
Crn = $"{crn}",
SectionCode = "000",
Meetings = new ScrapedMeeting[]
{
new ScrapedMeeting()
{
Type = type,
Instructors =
instructors.Select(i => (name: i.Name, email: i.Email)).ToArray(),
StartDate = new DateTimeOffset(2021, 8, 23, 0, 0, 0, 0,
timeZone.BaseUtcOffset),
EndDate = new DateTimeOffset(2021, 12, 11, 0, 0, 0, 0,
timeZone.BaseUtcOffset),
DaysOfWeek =
(DaysOfWeek.Monday | DaysOfWeek.Wednesday),
StartTime = new DateTimeOffset(2021, 8, 30, 7, 30, 0, 0,
timeZone.BaseUtcOffset),
EndTime = new DateTimeOffset(2021, 8, 30, 8, 20, 0, 0,
timeZone.BaseUtcOffset),
BuildingCode = room.Building.Code,
BuildingName = room.Building.Name,
RoomNumber = room.Number,
},
},
SubjectCode = course.Subject.Code,
CourseNumber = course.Number,
Type = type,
CourseTitle = course.Name,
Description = course.Description,
CreditHours = course.CreditHours,
LinkSelf = linkSelf,
LinkOther = linkOther,
CampusCode = campus.Code,
CampusName = campus.Name,
Capacity = 32,
Enrolled = 16,
RemainingSpace = 16,
WaitListCapacity = 8,
WaitListCount = 4,
WaitListSpace = 4,
},
};
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Internal.TypeSystem;
namespace Internal.TypeSystem.Ecma
{
public partial class EcmaModule : ModuleDesc
{
private PEReader _peReader;
protected MetadataReader _metadataReader;
internal interface IEntityHandleObject
{
EntityHandle Handle
{
get;
}
}
private sealed class EcmaObjectLookupWrapper : IEntityHandleObject
{
private EntityHandle _handle;
private object _obj;
public EcmaObjectLookupWrapper(EntityHandle handle, object obj)
{
_obj = obj;
_handle = handle;
}
public EntityHandle Handle
{
get
{
return _handle;
}
}
public object Object
{
get
{
return _obj;
}
}
}
internal class EcmaObjectLookupHashtable : LockFreeReaderHashtable<EntityHandle, IEntityHandleObject>
{
private EcmaModule _module;
public EcmaObjectLookupHashtable(EcmaModule module)
{
_module = module;
}
protected override int GetKeyHashCode(EntityHandle key)
{
return key.GetHashCode();
}
protected override int GetValueHashCode(IEntityHandleObject value)
{
return value.Handle.GetHashCode();
}
protected override bool CompareKeyToValue(EntityHandle key, IEntityHandleObject value)
{
return key.Equals(value.Handle);
}
protected override bool CompareValueToValue(IEntityHandleObject value1, IEntityHandleObject value2)
{
if (Object.ReferenceEquals(value1, value2))
return true;
else
return value1.Handle.Equals(value2.Handle);
}
protected override IEntityHandleObject CreateValueFromKey(EntityHandle handle)
{
object item;
switch (handle.Kind)
{
case HandleKind.TypeDefinition:
item = new EcmaType(_module, (TypeDefinitionHandle)handle);
break;
case HandleKind.MethodDefinition:
{
MethodDefinitionHandle methodDefinitionHandle = (MethodDefinitionHandle)handle;
TypeDefinitionHandle typeDefinitionHandle = _module._metadataReader.GetMethodDefinition(methodDefinitionHandle).GetDeclaringType();
EcmaType type = (EcmaType)_module.GetObject(typeDefinitionHandle);
item = new EcmaMethod(type, methodDefinitionHandle);
}
break;
case HandleKind.FieldDefinition:
{
FieldDefinitionHandle fieldDefinitionHandle = (FieldDefinitionHandle)handle;
TypeDefinitionHandle typeDefinitionHandle = _module._metadataReader.GetFieldDefinition(fieldDefinitionHandle).GetDeclaringType();
EcmaType type = (EcmaType)_module.GetObject(typeDefinitionHandle);
item = new EcmaField(type, fieldDefinitionHandle);
}
break;
case HandleKind.TypeReference:
item = _module.ResolveTypeReference((TypeReferenceHandle)handle);
break;
case HandleKind.MemberReference:
item = _module.ResolveMemberReference((MemberReferenceHandle)handle);
break;
case HandleKind.AssemblyReference:
item = _module.ResolveAssemblyReference((AssemblyReferenceHandle)handle);
break;
case HandleKind.TypeSpecification:
item = _module.ResolveTypeSpecification((TypeSpecificationHandle)handle);
break;
case HandleKind.MethodSpecification:
item = _module.ResolveMethodSpecification((MethodSpecificationHandle)handle);
break;
case HandleKind.ExportedType:
item = _module.ResolveExportedType((ExportedTypeHandle)handle);
break;
case HandleKind.StandaloneSignature:
item = _module.ResolveStandaloneSignature((StandaloneSignatureHandle)handle);
break;
// TODO: Resolve other tokens
default:
throw new BadImageFormatException("Unknown metadata token type: " + handle.Kind);
}
switch (handle.Kind)
{
case HandleKind.TypeDefinition:
case HandleKind.MethodDefinition:
case HandleKind.FieldDefinition:
// type/method/field definitions directly correspond to their target item.
return (IEntityHandleObject)item;
default:
// Everything else is some form of reference which cannot be self-describing
return new EcmaObjectLookupWrapper(handle, item);
}
}
}
private LockFreeReaderHashtable<EntityHandle, IEntityHandleObject> _resolvedTokens;
internal EcmaModule(TypeSystemContext context, PEReader peReader, MetadataReader metadataReader)
: base(context)
{
_peReader = peReader;
_metadataReader = metadataReader;
_resolvedTokens = new EcmaObjectLookupHashtable(this);
}
public static EcmaModule Create(TypeSystemContext context, PEReader peReader)
{
MetadataReader metadataReader = CreateMetadataReader(context, peReader);
if (metadataReader.IsAssembly)
return new EcmaAssembly(context, peReader, metadataReader);
else
return new EcmaModule(context, peReader, metadataReader);
}
private static MetadataReader CreateMetadataReader(TypeSystemContext context, PEReader peReader)
{
var stringDecoderProvider = context as IMetadataStringDecoderProvider;
MetadataReader metadataReader = peReader.GetMetadataReader(MetadataReaderOptions.None /* MetadataReaderOptions.ApplyWindowsRuntimeProjections */,
(stringDecoderProvider != null) ? stringDecoderProvider.GetMetadataStringDecoder() : null);
return metadataReader;
}
public PEReader PEReader
{
get
{
return _peReader;
}
}
public MetadataReader MetadataReader
{
get
{
return _metadataReader;
}
}
/// <summary>
/// Gets the managed entrypoint method of this module or null if the module has no managed entrypoint.
/// </summary>
public MethodDesc EntryPoint
{
get
{
CorHeader corHeader = _peReader.PEHeaders.CorHeader;
if ((corHeader.Flags & CorFlags.NativeEntryPoint) != 0)
{
// Entrypoint is an RVA to an unmanaged method
return null;
}
int entryPointToken = corHeader.EntryPointTokenOrRelativeVirtualAddress;
if (entryPointToken == 0)
{
// No entrypoint
return null;
}
EntityHandle handle = MetadataTokens.EntityHandle(entryPointToken);
if (handle.Kind == HandleKind.MethodDefinition)
{
return GetMethod(handle);
}
else if (handle.Kind == HandleKind.AssemblyFile)
{
// Entrypoint not in the manifest assembly
throw new NotImplementedException();
}
// Bad metadata
throw new BadImageFormatException();
}
}
public sealed override MetadataType GetType(string nameSpace, string name, bool throwIfNotFound = true)
{
var stringComparer = _metadataReader.StringComparer;
// TODO: More efficient implementation?
foreach (var typeDefinitionHandle in _metadataReader.TypeDefinitions)
{
var typeDefinition = _metadataReader.GetTypeDefinition(typeDefinitionHandle);
if (stringComparer.Equals(typeDefinition.Name, name) &&
stringComparer.Equals(typeDefinition.Namespace, nameSpace))
{
return (MetadataType)GetType((EntityHandle)typeDefinitionHandle);
}
}
foreach (var exportedTypeHandle in _metadataReader.ExportedTypes)
{
var exportedType = _metadataReader.GetExportedType(exportedTypeHandle);
if (stringComparer.Equals(exportedType.Name, name) &&
stringComparer.Equals(exportedType.Namespace, nameSpace))
{
if (exportedType.IsForwarder)
{
Object implementation = GetObject(exportedType.Implementation);
if (implementation is ModuleDesc)
{
return ((ModuleDesc)(implementation)).GetType(nameSpace, name);
}
// TODO
throw new NotImplementedException();
}
// TODO:
throw new NotImplementedException();
}
}
if (throwIfNotFound)
throw CreateTypeLoadException(nameSpace + "." + name);
return null;
}
public Exception CreateTypeLoadException(string fullTypeName)
{
return new TypeLoadException(String.Format("Could not load type '{0}' from assembly '{1}'.", fullTypeName, this.ToString()));
}
public TypeDesc GetType(EntityHandle handle)
{
TypeDesc type = GetObject(handle) as TypeDesc;
if (type == null)
throw new BadImageFormatException("Type expected");
return type;
}
public MethodDesc GetMethod(EntityHandle handle)
{
MethodDesc method = GetObject(handle) as MethodDesc;
if (method == null)
throw new BadImageFormatException("Method expected");
return method;
}
public FieldDesc GetField(EntityHandle handle)
{
FieldDesc field = GetObject(handle) as FieldDesc;
if (field == null)
throw new BadImageFormatException("Field expected");
return field;
}
public Object GetObject(EntityHandle handle)
{
IEntityHandleObject obj = _resolvedTokens.GetOrCreateValue(handle);
if (obj is EcmaObjectLookupWrapper)
{
return ((EcmaObjectLookupWrapper)obj).Object;
}
else
{
return obj;
}
}
private Object ResolveMethodSpecification(MethodSpecificationHandle handle)
{
MethodSpecification methodSpecification = _metadataReader.GetMethodSpecification(handle);
MethodDesc methodDef = GetMethod(methodSpecification.Method);
BlobReader signatureReader = _metadataReader.GetBlobReader(methodSpecification.Signature);
EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader);
TypeDesc[] instantiation = parser.ParseMethodSpecSignature();
return Context.GetInstantiatedMethod(methodDef, new Instantiation(instantiation));
}
private Object ResolveStandaloneSignature(StandaloneSignatureHandle handle)
{
StandaloneSignature signature = _metadataReader.GetStandaloneSignature(handle);
BlobReader signatureReader = _metadataReader.GetBlobReader(signature.Signature);
EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader);
MethodSignature methodSig = parser.ParseMethodSignature();
return methodSig;
}
private Object ResolveTypeSpecification(TypeSpecificationHandle handle)
{
TypeSpecification typeSpecification = _metadataReader.GetTypeSpecification(handle);
BlobReader signatureReader = _metadataReader.GetBlobReader(typeSpecification.Signature);
EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader);
return parser.ParseType();
}
private Object ResolveMemberReference(MemberReferenceHandle handle)
{
MemberReference memberReference = _metadataReader.GetMemberReference(handle);
Object parent = GetObject(memberReference.Parent);
TypeDesc parentTypeDesc = parent as TypeDesc;
if (parentTypeDesc != null)
{
BlobReader signatureReader = _metadataReader.GetBlobReader(memberReference.Signature);
EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader);
string name = _metadataReader.GetString(memberReference.Name);
if (parser.IsFieldSignature)
{
FieldDesc field = parentTypeDesc.GetField(name);
if (field != null)
return field;
// TODO: Better error message
throw new MissingMemberException("Field not found " + parent.ToString() + "." + name);
}
else
{
MethodSignature sig = parser.ParseMethodSignature();
TypeDesc typeDescToInspect = parentTypeDesc;
// Try to resolve the name and signature in the current type, or any of the base types.
do
{
// TODO: handle substitutions
MethodDesc method = typeDescToInspect.GetMethod(name, sig);
if (method != null)
{
// If this resolved to one of the base types, make sure it's not a constructor.
// Instance constructors are not inherited.
if (typeDescToInspect != parentTypeDesc && method.IsConstructor)
break;
return method;
}
typeDescToInspect = typeDescToInspect.BaseType;
} while (typeDescToInspect != null);
// TODO: Better error message
throw new MissingMemberException("Method not found " + parent.ToString() + "." + name);
}
}
else if (parent is MethodDesc)
{
throw new NotSupportedException("Vararg methods not supported in .NET Core.");
}
else if (parent is ModuleDesc)
{
throw new NotImplementedException("MemberRef to a global function or variable.");
}
throw new BadImageFormatException();
}
private Object ResolveTypeReference(TypeReferenceHandle handle)
{
TypeReference typeReference = _metadataReader.GetTypeReference(handle);
Object resolutionScope = GetObject(typeReference.ResolutionScope);
if (resolutionScope is ModuleDesc)
{
return ((ModuleDesc)(resolutionScope)).GetType(_metadataReader.GetString(typeReference.Namespace), _metadataReader.GetString(typeReference.Name));
}
else
if (resolutionScope is MetadataType)
{
return ((MetadataType)(resolutionScope)).GetNestedType(_metadataReader.GetString(typeReference.Name));
}
// TODO
throw new NotImplementedException();
}
private Object ResolveAssemblyReference(AssemblyReferenceHandle handle)
{
AssemblyReference assemblyReference = _metadataReader.GetAssemblyReference(handle);
AssemblyName an = new AssemblyName();
an.Name = _metadataReader.GetString(assemblyReference.Name);
an.Version = assemblyReference.Version;
var publicKeyOrToken = _metadataReader.GetBlobBytes(assemblyReference.PublicKeyOrToken);
if ((an.Flags & AssemblyNameFlags.PublicKey) != 0)
{
an.SetPublicKey(publicKeyOrToken);
}
else
{
an.SetPublicKeyToken(publicKeyOrToken);
}
an.CultureName = _metadataReader.GetString(assemblyReference.Culture);
an.ContentType = GetContentTypeFromAssemblyFlags(assemblyReference.Flags);
return Context.ResolveAssembly(an);
}
private Object ResolveExportedType(ExportedTypeHandle handle)
{
ExportedType exportedType = _metadataReader.GetExportedType(handle);
var implementation = GetObject(exportedType.Implementation);
if (implementation is ModuleDesc)
{
var module = (ModuleDesc)implementation;
string nameSpace = _metadataReader.GetString(exportedType.Namespace);
string name = _metadataReader.GetString(exportedType.Name);
return module.GetType(nameSpace, name);
}
else
if (implementation is MetadataType)
{
var type = (MetadataType)implementation;
string name = _metadataReader.GetString(exportedType.Name);
var nestedType = type.GetNestedType(name);
// TODO: Better error message
if (nestedType == null)
throw new TypeLoadException("Nested type not found " + type.ToString() + "." + name);
return nestedType;
}
else
{
throw new BadImageFormatException("Unknown metadata token type for exported type");
}
}
public sealed override IEnumerable<MetadataType> GetAllTypes()
{
foreach (var typeDefinitionHandle in _metadataReader.TypeDefinitions)
{
yield return (MetadataType)GetType(typeDefinitionHandle);
}
}
public sealed override TypeDesc GetGlobalModuleType()
{
int typeDefinitionsCount = _metadataReader.TypeDefinitions.Count;
if (typeDefinitionsCount == 0)
return null;
return GetType(MetadataTokens.EntityHandle(0x02000001 /* COR_GLOBAL_PARENT_TOKEN */));
}
protected static AssemblyContentType GetContentTypeFromAssemblyFlags(AssemblyFlags flags)
{
return (AssemblyContentType)(((int)flags & 0x0E00) >> 9);
}
public string GetUserString(UserStringHandle userStringHandle)
{
// String literals are not cached
return _metadataReader.GetUserString(userStringHandle);
}
public override string ToString()
{
ModuleDefinition moduleDefinition = _metadataReader.GetModuleDefinition();
return _metadataReader.GetString(moduleDefinition.Name);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class Is
{
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public static ConstraintExpression Not
{
get { return new ConstraintExpression().Not; }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public static ConstraintExpression All
{
get { return new ConstraintExpression().All; }
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public static NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public static TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public static FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public static GreaterThanConstraint Positive
{
get { return new GreaterThanConstraint(0); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public static LessThanConstraint Negative
{
get { return new LessThanConstraint(0); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public static NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public static EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public static UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#region BinarySerializable
#if !NETCF && !SILVERLIGHT
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public static BinarySerializableConstraint BinarySerializable
{
get { return new BinarySerializableConstraint(); }
}
#endif
#endregion
#region XmlSerializable
#if !SILVERLIGHT
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in xml format.
/// </summary>
public static XmlSerializableConstraint XmlSerializable
{
get { return new XmlSerializableConstraint(); }
}
#endif
#endregion
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public static EqualConstraint EqualTo(object expected)
{
return new EqualConstraint(expected);
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public static SameAsConstraint SameAs(object expected)
{
return new SameAsConstraint(expected);
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the suppled argument
/// </summary>
public static GreaterThanConstraint GreaterThan(object expected)
{
return new GreaterThanConstraint(expected);
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public static GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public static GreaterThanOrEqualConstraint AtLeast(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the suppled argument
/// </summary>
public static LessThanConstraint LessThan(object expected)
{
return new LessThanConstraint(expected);
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public static LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public static LessThanOrEqualConstraint AtMost(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public static ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public static ExactTypeConstraint TypeOf<T>()
{
return new ExactTypeConstraint(typeof(T));
}
#endif
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public static InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public static InstanceOfTypeConstraint InstanceOf<T>()
{
return new InstanceOfTypeConstraint(typeof(T));
}
#endif
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableFromConstraint AssignableFrom<T>()
{
return new AssignableFromConstraint(typeof(T));
}
#endif
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableToConstraint AssignableTo<T>()
{
return new AssignableToConstraint(typeof(T));
}
#endif
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public static CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return new CollectionEquivalentConstraint(expected);
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public static CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public static CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public static SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region StringStarting
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public static StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region StringEnding
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public static EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region StringMatching
#if !NETCF
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public static RegexConstraint StringMatching(string pattern)
{
return new RegexConstraint(pattern);
}
#endif
#endregion
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public static SamePathConstraint SamePath(string expected)
{
return new SamePathConstraint(expected);
}
#endregion
#region SubPath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is under an expected path after canonicalization.
/// </summary>
public static SubPathConstraint SubPath(string expected)
{
return new SubPathConstraint(expected);
}
#endregion
#region SamePathOrUnder
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public static SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return new SamePathOrUnderConstraint(expected);
}
#endregion
#region InRange
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public static RangeConstraint<T> InRange<T>(T from, T to) where T : IComparable<T>
{
return new RangeConstraint<T>(from, to);
}
#else
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public static RangeConstraint InRange(IComparable from, IComparable to)
{
return new RangeConstraint(from, to);
}
#endif
#endregion
}
}
| |
using System;
using System.Drawing;
using DotNet.Highcharts.Enums;
using DotNet.Highcharts.Attributes;
using DotNet.Highcharts.Helpers;
namespace DotNet.Highcharts.Options
{
/// <summary>
/// The legend is a box containing a symbol and name for each series item or point item in the chart.
/// </summary>
public class Legend
{
/// <summary>
/// The horizontal alignment of the legend box within the chart area. Valid values are <code>'left'</code>, <code>'center'</code> and <code>'right'</code>.
/// Default: center
/// </summary>
public HorizontalAligns? Align { get; set; }
/// <summary>
/// The background color of the legend.
/// </summary>
[JsonFormatter(addPropertyName: true, useCurlyBracketsForObject: false)]
public BackColorOrGradient BackgroundColor { get; set; }
/// <summary>
/// The color of the drawn border around the legend.
/// Default: #909090
/// </summary>
public Color? BorderColor { get; set; }
/// <summary>
/// The border corner radius of the legend.
/// Default: 0
/// </summary>
public Number? BorderRadius { get; set; }
/// <summary>
/// The width of the drawn border around the legend.
/// Default: 0
/// </summary>
public Number? BorderWidth { get; set; }
/// <summary>
/// Enable or disable the legend.
/// Default: true
/// </summary>
public bool? Enabled { get; set; }
/// <summary>
/// When the legend is floating, the plot area ignores it and is allowed to be placed below it.
/// Default: false
/// </summary>
public bool? Floating { get; set; }
/// <summary>
/// In a legend with horizontal layout, the itemDistance defines the pixel distance between each item.
/// Default: 20
/// </summary>
public Number? ItemDistance { get; set; }
/// <summary>
/// CSS styles for each legend item when the corresponding series or point is hidden. Only a subset of CSS is supported, notably those options related to text. Properties are inherited from <code>style</code> unless overridden here. Defaults to:<pre>itemHiddenStyle: { color: '#CCC'}</pre>
/// </summary>
[JsonFormatter("{{ {0} }}")]
public string ItemHiddenStyle { get; set; }
/// <summary>
/// CSS styles for each legend item in hover mode. Only a subset of CSS is supported, notably those options related to text. Properties are inherited from <code>style</code> unless overridden here. Defaults to:<pre>itemHoverStyle: { color: '#000'}</pre>
/// </summary>
[JsonFormatter("{{ {0} }}")]
public string ItemHoverStyle { get; set; }
/// <summary>
/// The pixel bottom margin for each legend item.
/// Default: 0
/// </summary>
public Number? ItemMarginBottom { get; set; }
/// <summary>
/// The pixel top margin for each legend item.
/// Default: 0
/// </summary>
public Number? ItemMarginTop { get; set; }
/// <summary>
/// CSS styles for each legend item. Only a subset of CSS is supported, notably those options related to text.
/// Default: { "color": "#333333", "cursor": "pointer", "fontSize": "12px", "fontWeight": "bold" }
/// </summary>
[JsonFormatter("{{ {0} }}")]
public string ItemStyle { get; set; }
/// <summary>
/// The width for each legend item. This is useful in a horizontal layout with many items when you want the items to align vertically. .
/// </summary>
public Number? ItemWidth { get; set; }
/// <summary>
/// A <a href='http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting'>format string</a> for each legend label. Available variables relates to properties on the series, or the point in case of pies.
/// Default: {name}
/// </summary>
public string LabelFormat { get; set; }
/// <summary>
/// Callback function to format each of the series' labels. The <em>this</em> keyword refers to the series object, or the point object in case of pie charts. By default the series or point name is printed.
/// </summary>
[JsonFormatter("{0}")]
public string LabelFormatter { get; set; }
/// <summary>
/// The layout of the legend items. Can be one of 'horizontal' or 'vertical'.
/// Default: horizontal
/// </summary>
public Layouts? Layout { get; set; }
/// <summary>
/// Line height for the legend items. Deprecated as of 2.1. Instead, the line height for each item can be set using itemStyle.lineHeight, and the padding between items using itemMarginTop and itemMarginBottom.
/// Default: 16
/// </summary>
public Number? LineHeight { get; set; }
/// <summary>
/// If the plot area sized is calculated automatically and the legend is not floating, the legend margin is the space between the legend and the axis labels or plot area.
/// Default: 15
/// </summary>
public Number? Margin { get; set; }
/// <summary>
/// Maximum pixel height for the legend. When the maximum height is extended, navigation will show.
/// </summary>
public Number? MaxHeight { get; set; }
/// <summary>
/// Options for the paging or navigation appearing when the legend is overflown. When <a href='#legend.useHTML'>legend.useHTML</a> is enabled, navigation is disabled.
/// </summary>
public LegendNavigation Navigation { get; set; }
/// <summary>
/// The inner padding of the legend box.
/// Default: 8
/// </summary>
public Number? Padding { get; set; }
/// <summary>
/// Whether to reverse the order of the legend items compared to the order of the series or points as defined in the configuration object.
/// Default: false
/// </summary>
public bool? Reversed { get; set; }
/// <summary>
/// Whether to show the symbol on the right side of the text rather than the left side. This is common in Arabic and Hebraic.
/// Default: false
/// </summary>
public bool? Rtl { get; set; }
/// <summary>
/// Whether to apply a drop shadow to the legend. A <code>backgroundColor</code> also needs to be applied for this to take effect. Since 2.3 the shadow can be an object configuration containing <code>color</code>, <code>offsetX</code>, <code>offsetY</code>, <code>opacity</code> and <code>width</code>.
/// Default: false
/// </summary>
public bool? Shadow { get; set; }
[Obsolete("CSS styles for the legend area. In the 1.x versions the position of the legend area was determined by CSS. In 2.x, the position is determined by properties like <code>align</code>, <code>verticalAlign</code>, <code>x</code> and <code>y</code>, but the styles are still parsed for backwards compatibility.")]
[JsonFormatter("{{ {0} }}")]
public string Style { get; set; }
/// <summary>
/// The pixel height of the symbol for series types that use a rectangle in the legend.
/// Default: 12
/// </summary>
public Number? SymbolHeight { get; set; }
/// <summary>
/// The pixel padding between the legend item symbol and the legend item text.
/// Default: 5
/// </summary>
public Number? SymbolPadding { get; set; }
/// <summary>
/// The border radius of the symbol for series types that use a rectangle in the legend.
/// Default: 2
/// </summary>
public Number? SymbolRadius { get; set; }
/// <summary>
/// The pixel width of the legend item symbol.
/// Default: 16
/// </summary>
public Number? SymbolWidth { get; set; }
/// <summary>
/// A title to be added on top of the legend.
/// </summary>
public LegendTitle Title { get; set; }
/// <summary>
/// <p>Whether to <a href='http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html'>use HTML</a> to render the legend item texts. When using HTML, <a href='#legend.navigation'>legend.navigation</a> is disabled.</p>
/// Default: false
/// </summary>
public bool? UseHTML { get; set; }
/// <summary>
/// The vertical alignment of the legend box. Can be one of 'top', 'middle' or 'bottom'. Vertical position can be further determined by the <code>y</code> option.
/// Default: bottom
/// </summary>
public VerticalAligns? VerticalAlign { get; set; }
/// <summary>
/// The width of the legend box.
/// </summary>
public Number? Width { get; set; }
/// <summary>
/// The x offset of the legend relative to its horizontal alignment <code>align</code> within chart.spacingLeft and chart.spacingRight. Negative x moves it to the left, positive x moves it to the right.
/// Default: 0
/// </summary>
public Number? X { get; set; }
/// <summary>
/// The vertical offset of the legend relative to it's vertical alignment <code>verticalAlign</code> within chart.spacingTop and chart.spacingBottom. Negative y moves it up, positive y moves it down.
/// Default: 0
/// </summary>
public Number? Y { get; set; }
}
}
| |
/*
* 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>
/// Container for the parameters to the PutLifecycleHook operation.
/// Creates or updates a lifecycle hook for the specified Auto Scaling Group.
///
///
/// <para>
/// A lifecycle hook tells Auto Scaling that you want to perform an action on an instance
/// that is not actively in service; for example, either when the instance launches or
/// before the instance terminates.
/// </para>
///
/// <para>
/// This operation is a part of the basic sequence for adding a lifecycle hook to an Auto
/// Scaling group:
/// </para>
/// <ol> <li>Create a notification target. A target can be either an Amazon SQS queue
/// or an Amazon SNS topic.</li> <li>Create an IAM role. This role allows Auto Scaling
/// to publish lifecycle notifications to the designated SQS queue or SNS topic.</li>
/// <li><b>Create the lifecycle hook. You can create a hook that acts when instances launch
/// or when instances terminate.</b></li> <li>If necessary, record the lifecycle action
/// heartbeat to keep the instance in a pending state.</li> <li>Complete the lifecycle
/// action.</li> </ol>
/// <para>
/// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/AutoScalingPendingState.html">Auto
/// Scaling Pending State</a> and <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/AutoScalingTerminatingState.html">Auto
/// Scaling Terminating State</a> in the <i>Auto Scaling Developer Guide</i>.
/// </para>
///
/// <para>
/// If you exceed your maximum limit of lifecycle hooks, which by default is 50 per region,
/// the call fails. For information about updating this limit, see <a href="http://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html">AWS
/// Service Limits</a> in the <i>Amazon Web Services General Reference</i>.
/// </para>
/// </summary>
public partial class PutLifecycleHookRequest : AmazonAutoScalingRequest
{
private string _autoScalingGroupName;
private string _defaultResult;
private int? _heartbeatTimeout;
private string _lifecycleHookName;
private string _lifecycleTransition;
private string _notificationMetadata;
private string _notificationTargetARN;
private string _roleARN;
/// <summary>
/// Gets and sets the property AutoScalingGroupName.
/// <para>
/// The name of the Auto Scaling group to which you want to assign the lifecycle hook.
/// </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 DefaultResult.
/// <para>
/// Defines the action the Auto Scaling group should take when the lifecycle hook timeout
/// elapses or if an unexpected failure occurs. The value for this parameter can be either
/// <code>CONTINUE</code> or <code>ABANDON</code>. The default value for this parameter
/// is <code>ABANDON</code>.
/// </para>
/// </summary>
public string DefaultResult
{
get { return this._defaultResult; }
set { this._defaultResult = value; }
}
// Check to see if DefaultResult property is set
internal bool IsSetDefaultResult()
{
return this._defaultResult != null;
}
/// <summary>
/// Gets and sets the property HeartbeatTimeout.
/// <para>
/// Defines the amount of time, in seconds, that can elapse before the lifecycle hook
/// times out. When the lifecycle hook times out, Auto Scaling performs the action defined
/// in the <code>DefaultResult</code> parameter. You can prevent the lifecycle hook from
/// timing out by calling <a>RecordLifecycleActionHeartbeat</a>. The default value for
/// this parameter is 3600 seconds (1 hour).
/// </para>
/// </summary>
public int HeartbeatTimeout
{
get { return this._heartbeatTimeout.GetValueOrDefault(); }
set { this._heartbeatTimeout = value; }
}
// Check to see if HeartbeatTimeout property is set
internal bool IsSetHeartbeatTimeout()
{
return this._heartbeatTimeout.HasValue;
}
/// <summary>
/// Gets and sets the property LifecycleHookName.
/// <para>
/// The name of the lifecycle hook.
/// </para>
/// </summary>
public string LifecycleHookName
{
get { return this._lifecycleHookName; }
set { this._lifecycleHookName = value; }
}
// Check to see if LifecycleHookName property is set
internal bool IsSetLifecycleHookName()
{
return this._lifecycleHookName != null;
}
/// <summary>
/// Gets and sets the property LifecycleTransition.
/// <para>
/// The instance state to which you want to attach the lifecycle hook. For a list of lifecycle
/// hook types, see <a>DescribeLifecycleHookTypes</a>.
/// </para>
///
/// <para>
/// This parameter is required for new lifecycle hooks, but optional when updating existing
/// hooks.
/// </para>
/// </summary>
public string LifecycleTransition
{
get { return this._lifecycleTransition; }
set { this._lifecycleTransition = value; }
}
// Check to see if LifecycleTransition property is set
internal bool IsSetLifecycleTransition()
{
return this._lifecycleTransition != null;
}
/// <summary>
/// Gets and sets the property NotificationMetadata.
/// <para>
/// Contains additional information that you want to include any time Auto Scaling sends
/// a message to the notification target.
/// </para>
/// </summary>
public string NotificationMetadata
{
get { return this._notificationMetadata; }
set { this._notificationMetadata = value; }
}
// Check to see if NotificationMetadata property is set
internal bool IsSetNotificationMetadata()
{
return this._notificationMetadata != null;
}
/// <summary>
/// Gets and sets the property NotificationTargetARN.
/// <para>
/// The ARN of the notification target that Auto Scaling will use to notify you when an
/// instance is in the transition state for the lifecycle hook. This ARN target can be
/// either an SQS queue or an SNS topic.
/// </para>
///
/// <para>
/// This parameter is required for new lifecycle hooks, but optional when updating existing
/// hooks.
/// </para>
///
/// <para>
/// The notification message sent to the target will include:
/// </para>
/// <ul> <li> <b>LifecycleActionToken</b>. The Lifecycle action token.</li> <li> <b>AccountId</b>.
/// The user account ID.</li> <li> <b>AutoScalingGroupName</b>. The name of the Auto Scaling
/// group.</li> <li> <b>LifecycleHookName</b>. The lifecycle hook name.</li> <li> <b>EC2InstanceId</b>.
/// The EC2 instance ID.</li> <li> <b>LifecycleTransition</b>. The lifecycle transition.</li>
/// <li> <b>NotificationMetadata</b>. The notification metadata.</li> </ul>
/// <para>
/// This operation uses the JSON format when sending notifications to an Amazon SQS queue,
/// and an email key/value pair format when sending notifications to an Amazon SNS topic.
/// </para>
///
/// <para>
/// When you call this operation, a test message is sent to the notification target. This
/// test message contains an additional key/value pair: <code>Event:autoscaling:TEST_NOTIFICATION</code>.
/// </para>
/// </summary>
public string NotificationTargetARN
{
get { return this._notificationTargetARN; }
set { this._notificationTargetARN = value; }
}
// Check to see if NotificationTargetARN property is set
internal bool IsSetNotificationTargetARN()
{
return this._notificationTargetARN != null;
}
/// <summary>
/// Gets and sets the property RoleARN.
/// <para>
/// The ARN of the IAM role that allows the Auto Scaling group to publish to the specified
/// notification target.
/// </para>
///
/// <para>
/// This parameter is required for new lifecycle hooks, but optional when updating existing
/// hooks.
/// </para>
/// </summary>
public string RoleARN
{
get { return this._roleARN; }
set { this._roleARN = value; }
}
// Check to see if RoleARN property is set
internal bool IsSetRoleARN()
{
return this._roleARN != null;
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using EnvDTE;
using VSLangProj;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// Represents an automation friendly version of a language-specific project.
/// </summary>
[ComVisible(true), CLSCompliant(false)]
public class OAVSProject : VSProject
{
#region fields
private ProjectNode project;
private OAVSProjectEvents events;
#endregion
#region ctors
internal OAVSProject(ProjectNode project)
{
this.project = project;
}
#endregion
#region VSProject Members
public virtual ProjectItem AddWebReference(string bstrUrl)
{
throw new NotImplementedException();
}
public virtual BuildManager BuildManager
{
get
{
return null;
}
}
public virtual void CopyProject(string bstrDestFolder, string bstrDestUNCPath, prjCopyProjectOption copyProjectOption, string bstrUsername, string bstrPassword)
{
throw new NotImplementedException();
}
public virtual ProjectItem CreateWebReferencesFolder()
{
throw new NotImplementedException();
}
public virtual DTE DTE
{
get
{
return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE));
}
}
public virtual VSProjectEvents Events
{
get
{
if (events == null)
events = new OAVSProjectEvents(this);
return events;
}
}
public virtual void Exec(prjExecCommand command, int bSuppressUI, object varIn, out object pVarOut)
{
throw new NotImplementedException(); ;
}
public virtual void GenerateKeyPairFiles(string strPublicPrivateFile, string strPublicOnlyFile)
{
throw new NotImplementedException(); ;
}
public virtual string GetUniqueFilename(object pDispatch, string bstrRoot, string bstrDesiredExt)
{
throw new NotImplementedException(); ;
}
public virtual Imports Imports
{
get
{
throw new NotImplementedException();
}
}
public virtual EnvDTE.Project Project
{
get
{
return this.project.GetAutomationObject() as EnvDTE.Project;
}
}
public virtual References References
{
get
{
ReferenceContainerNode references = project.GetReferenceContainer() as ReferenceContainerNode;
if (null == references)
{
return new OAReferences(null, project);
}
return references.Object as References;
}
}
public virtual void Refresh()
{
}
public virtual string TemplatePath
{
get
{
throw new NotImplementedException();
}
}
public virtual ProjectItem WebReferencesFolder
{
get
{
throw new NotImplementedException();
}
}
public virtual bool WorkOffline
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
}
/// <summary>
/// Provides access to language-specific project events
/// </summary>
[ComVisible(true), CLSCompliant(false)]
public class OAVSProjectEvents : VSProjectEvents
{
#region fields
private OAVSProject vsProject;
#endregion
#region ctors
public OAVSProjectEvents(OAVSProject vsProject)
{
this.vsProject = vsProject;
}
#endregion
#region VSProjectEvents Members
public virtual BuildManagerEvents BuildManagerEvents
{
get
{
return vsProject.BuildManager as BuildManagerEvents;
}
}
public virtual ImportsEvents ImportsEvents
{
get
{
throw new NotImplementedException();
}
}
public virtual ReferencesEvents ReferencesEvents
{
get
{
return vsProject.References as ReferencesEvents;
}
}
#endregion
}
}
| |
using Castle.DynamicProxy;
using FluentAssertions;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Errors;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.UnitTests.ResourceGraph;
public sealed class ResourceGraphBuilderTests
{
[Fact]
public void Resource_without_public_name_gets_pluralized_with_naming_convention_applied()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
// Act
builder.Add<ResourceWithAttribute, int>();
// Assert
IResourceGraph resourceGraph = builder.Build();
ResourceType resourceType = resourceGraph.GetResourceType<ResourceWithAttribute>();
resourceType.PublicName.Should().Be("resourceWithAttributes");
}
[Fact]
public void Attribute_without_public_name_gets_naming_convention_applied()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
// Act
builder.Add<ResourceWithAttribute, int>();
// Assert
IResourceGraph resourceGraph = builder.Build();
ResourceType resourceType = resourceGraph.GetResourceType<ResourceWithAttribute>();
AttrAttribute attribute = resourceType.GetAttributeByPropertyName(nameof(ResourceWithAttribute.PrimaryValue));
attribute.PublicName.Should().Be("primaryValue");
}
[Fact]
public void HasOne_relationship_without_public_name_gets_naming_convention_applied()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
// Act
builder.Add<ResourceWithAttribute, int>();
// Assert
IResourceGraph resourceGraph = builder.Build();
ResourceType resourceType = resourceGraph.GetResourceType<ResourceWithAttribute>();
RelationshipAttribute relationship = resourceType.GetRelationshipByPropertyName(nameof(ResourceWithAttribute.PrimaryChild));
relationship.PublicName.Should().Be("primaryChild");
}
[Fact]
public void HasMany_relationship_without_public_name_gets_naming_convention_applied()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
// Act
builder.Add<ResourceWithAttribute, int>();
// Assert
IResourceGraph resourceGraph = builder.Build();
ResourceType resourceType = resourceGraph.GetResourceType<ResourceWithAttribute>();
RelationshipAttribute relationship = resourceType.GetRelationshipByPropertyName(nameof(ResourceWithAttribute.TopLevelChildren));
relationship.PublicName.Should().Be("topLevelChildren");
}
[Fact]
public void Cannot_use_duplicate_resource_name()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
builder.Add<ResourceWithHasOneRelationship, int>("duplicate");
// Act
Action action = () => builder.Add<ResourceWithAttribute, int>("duplicate");
// Assert
action.Should().ThrowExactly<InvalidConfigurationException>().WithMessage(
$"Resource '{typeof(ResourceWithHasOneRelationship)}' and '{typeof(ResourceWithAttribute)}' both use public name 'duplicate'.");
}
[Fact]
public void Cannot_use_duplicate_attribute_name()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
// Act
Action action = () => builder.Add<ResourceWithDuplicateAttrPublicName, int>();
// Assert
action.Should().ThrowExactly<InvalidConfigurationException>().WithMessage($"Properties '{typeof(ResourceWithDuplicateAttrPublicName)}.Value1' and " +
$"'{typeof(ResourceWithDuplicateAttrPublicName)}.Value2' both use public name 'duplicate'.");
}
[Fact]
public void Cannot_use_duplicate_relationship_name()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
// Act
Action action = () => builder.Add<ResourceWithDuplicateRelationshipPublicName, int>();
// Assert
action.Should().ThrowExactly<InvalidConfigurationException>().WithMessage(
$"Properties '{typeof(ResourceWithDuplicateRelationshipPublicName)}.PrimaryChild' and " +
$"'{typeof(ResourceWithDuplicateRelationshipPublicName)}.Children' both use public name 'duplicate'.");
}
[Fact]
public void Cannot_use_duplicate_attribute_and_relationship_name()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
// Act
Action action = () => builder.Add<ResourceWithDuplicateAttrRelationshipPublicName, int>();
// Assert
action.Should().ThrowExactly<InvalidConfigurationException>().WithMessage(
$"Properties '{typeof(ResourceWithDuplicateAttrRelationshipPublicName)}.Value' and " +
$"'{typeof(ResourceWithDuplicateAttrRelationshipPublicName)}.Children' both use public name 'duplicate'.");
}
[Fact]
public void Cannot_add_resource_that_implements_only_non_generic_IIdentifiable()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
// Act
Action action = () => builder.Add(typeof(ResourceWithoutId));
// Assert
action.Should().ThrowExactly<InvalidConfigurationException>()
.WithMessage($"Resource type '{typeof(ResourceWithoutId)}' implements 'IIdentifiable', but not 'IIdentifiable<TId>'.");
}
[Fact]
public void Cannot_build_graph_with_missing_related_HasOne_resource()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
builder.Add<ResourceWithHasOneRelationship, int>();
// Act
Action action = () => builder.Build();
// Assert
action.Should().ThrowExactly<InvalidConfigurationException>().WithMessage($"Resource type '{typeof(ResourceWithHasOneRelationship)}' " +
$"depends on '{typeof(ResourceWithAttribute)}', which was not added to the resource graph.");
}
[Fact]
public void Cannot_build_graph_with_missing_related_HasMany_resource()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
builder.Add<ResourceWithHasManyRelationship, int>();
// Act
Action action = () => builder.Build();
// Assert
action.Should().ThrowExactly<InvalidConfigurationException>().WithMessage($"Resource type '{typeof(ResourceWithHasManyRelationship)}' " +
$"depends on '{typeof(ResourceWithAttribute)}', which was not added to the resource graph.");
}
[Fact]
public void Logs_warning_when_adding_non_resource_type()
{
// Arrange
var options = new JsonApiOptions();
var loggerFactory = new FakeLoggerFactory(LogLevel.Warning);
var builder = new ResourceGraphBuilder(options, loggerFactory);
// Act
builder.Add(typeof(NonResource));
// Assert
loggerFactory.Logger.Messages.ShouldHaveCount(1);
FakeLoggerFactory.FakeLogMessage message = loggerFactory.Logger.Messages.ElementAt(0);
message.LogLevel.Should().Be(LogLevel.Warning);
message.Text.Should().Be($"Skipping: Type '{typeof(NonResource)}' does not implement 'IIdentifiable'. Add [NoResource] to suppress this warning.");
}
[Fact]
public void Logs_no_warning_when_adding_non_resource_type_with_suppression()
{
// Arrange
var options = new JsonApiOptions();
var loggerFactory = new FakeLoggerFactory(LogLevel.Warning);
var builder = new ResourceGraphBuilder(options, loggerFactory);
// Act
builder.Add(typeof(NonResourceWithSuppression));
// Assert
loggerFactory.Logger.Messages.Should().BeEmpty();
}
[Fact]
public void Logs_warning_when_adding_resource_without_attributes()
{
// Arrange
var options = new JsonApiOptions();
var loggerFactory = new FakeLoggerFactory(LogLevel.Warning);
var builder = new ResourceGraphBuilder(options, loggerFactory);
// Act
builder.Add<ResourceWithHasOneRelationship, int>();
// Assert
loggerFactory.Logger.Messages.ShouldHaveCount(1);
FakeLoggerFactory.FakeLogMessage message = loggerFactory.Logger.Messages.ElementAt(0);
message.LogLevel.Should().Be(LogLevel.Warning);
message.Text.Should().Be($"Type '{typeof(ResourceWithHasOneRelationship)}' does not contain any attributes.");
}
[Fact]
public void Logs_warning_on_empty_graph()
{
// Arrange
var options = new JsonApiOptions();
var loggerFactory = new FakeLoggerFactory(LogLevel.Warning);
var builder = new ResourceGraphBuilder(options, loggerFactory);
// Act
builder.Build();
// Assert
loggerFactory.Logger.Messages.ShouldHaveCount(1);
FakeLoggerFactory.FakeLogMessage message = loggerFactory.Logger.Messages.ElementAt(0);
message.LogLevel.Should().Be(LogLevel.Warning);
message.Text.Should().Be("The resource graph is empty.");
}
[Fact]
public void Resolves_correct_type_for_lazy_loading_proxy()
{
// Arrange
var options = new JsonApiOptions();
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
builder.Add<ResourceOfInt32, int>();
IResourceGraph resourceGraph = builder.Build();
var proxyGenerator = new ProxyGenerator();
var proxy = proxyGenerator.CreateClassProxy<ResourceOfInt32>();
// Act
ResourceType resourceType = resourceGraph.GetResourceType(proxy.GetType());
// Assert
resourceType.ClrType.Should().Be(typeof(ResourceOfInt32));
}
[Fact]
public void Can_override_capabilities_on_Id_property()
{
// Arrange
var options = new JsonApiOptions
{
DefaultAttrCapabilities = AttrCapabilities.None
};
var builder = new ResourceGraphBuilder(options, NullLoggerFactory.Instance);
// Act
builder.Add<ResourceWithIdOverride, long>();
// Assert
IResourceGraph resourceGraph = builder.Build();
ResourceType resourceType = resourceGraph.GetResourceType<ResourceWithIdOverride>();
AttrAttribute idAttribute = resourceType.Attributes.Single(attr => attr.Property.Name == nameof(Identifiable<object>.Id));
idAttribute.Capabilities.Should().Be(AttrCapabilities.AllowFilter);
}
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
private sealed class ResourceWithHasOneRelationship : Identifiable<int>
{
[HasOne]
public ResourceWithAttribute? PrimaryChild { get; set; }
}
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
private sealed class ResourceWithHasManyRelationship : Identifiable<int>
{
[HasMany]
public ISet<ResourceWithAttribute> Children { get; set; } = new HashSet<ResourceWithAttribute>();
}
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
private sealed class ResourceWithAttribute : Identifiable<int>
{
[Attr]
public string? PrimaryValue { get; set; }
[HasOne]
public ResourceWithAttribute? PrimaryChild { get; set; }
[HasMany]
public ISet<ResourceWithAttribute> TopLevelChildren { get; set; } = new HashSet<ResourceWithAttribute>();
}
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
private sealed class ResourceWithDuplicateAttrPublicName : Identifiable<int>
{
[Attr(PublicName = "duplicate")]
public string? Value1 { get; set; }
[Attr(PublicName = "duplicate")]
public string? Value2 { get; set; }
}
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
private sealed class ResourceWithDuplicateRelationshipPublicName : Identifiable<int>
{
[HasOne(PublicName = "duplicate")]
public ResourceWithHasOneRelationship? PrimaryChild { get; set; }
[HasMany(PublicName = "duplicate")]
public ISet<ResourceWithAttribute> Children { get; set; } = new HashSet<ResourceWithAttribute>();
}
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
private sealed class ResourceWithDuplicateAttrRelationshipPublicName : Identifiable<int>
{
[Attr(PublicName = "duplicate")]
public string? Value { get; set; }
[HasMany(PublicName = "duplicate")]
public ISet<ResourceWithAttribute> Children { get; set; } = new HashSet<ResourceWithAttribute>();
}
private sealed class ResourceWithoutId : IIdentifiable
{
public string? StringId { get; set; }
public string? LocalId { get; set; }
}
[UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)]
private sealed class NonResource
{
}
[UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)]
[NoResource]
private sealed class NonResourceWithSuppression
{
}
// ReSharper disable once ClassCanBeSealed.Global
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
public class ResourceOfInt32 : Identifiable<int>
{
[Attr]
public string? StringValue { get; set; }
[HasOne]
public ResourceOfInt32? PrimaryChild { get; set; }
[HasMany]
public IList<ResourceOfInt32> Children { get; set; } = new List<ResourceOfInt32>();
}
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
public sealed class ResourceWithIdOverride : Identifiable<long>
{
[Attr(Capabilities = AttrCapabilities.AllowFilter)]
public override long Id { get; set; }
}
}
| |
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 hair salon.
/// </summary>
public class HairSalon_Core : TypeCore, IHealthAndBeautyBusiness
{
public HairSalon_Core()
{
this._TypeId = 121;
this._Id = "HairSalon";
this._Schema_Org_Url = "http://schema.org/HairSalon";
string label = "";
GetLabel(out label, "HairSalon", typeof(HairSalon_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,123};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{123};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <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 larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <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>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <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>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <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>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <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>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <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>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <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>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <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);
}
}
}
}
| |
namespace Lex
{
/*
* Class: Spec
*/
using System;
using System.Collections;
public class Spec
{
/*
* Member Variables
*/
/* Lexical States. */
public Hashtable states; /* Hashtable taking state indices (Integer)
to state name (String). */
/* Regular Expression Macros. */
public Hashtable macros; /* Hashtable taking macro name (String)
to corresponding char buffer that
holds macro definition. */
/* NFA Machine. */
public Nfa nfa_start; /* Start state of NFA machine. */
public ArrayList nfa_states; /* List of states, with index
corresponding to label. */
public ArrayList[] state_rules; /* An array of Lists of Integers.
The ith Vector represents the lexical state
with index i. The contents of the ith
List are the indices of the NFA start
states that can be matched while in
the ith lexical state. */
public int[] state_dtrans;
/* DFA Machine. */
public ArrayList dfa_states; /* List of states, with index
corresponding to label. */
public Hashtable dfa_sets; /* Hashtable taking set of NFA states
to corresponding DFA state,
if the latter exists. */
/* Accept States and Corresponding Anchors. */
public ArrayList accept_list;
public int[] anchor_array;
/* Transition Table. */
public ArrayList dtrans_list;
public int dtrans_ncols;
public int[] row_map;
public int[] col_map;
/* Special pseudo-characters for beginning-of-line and end-of-file. */
public const int NUM_PSEUDO=2;
public int BOL; // beginning-of-line
public int EOF; // end-of-file
/* NFA character class minimization map. */
public int[] ccls_map;
/* Regular expression token variables. */
public int current_token;
public char lexeme;
public bool in_quote;
public bool in_ccl;
/* Verbose execution flag. */
public bool verbose;
/* directives flags. */
public bool integer_type;
public bool intwrap_type;
public bool yyeof;
public bool count_chars;
public bool count_lines;
public bool cup_compatible;
public bool lex_public;
public bool ignorecase;
public String init_code;
public String class_code;
public String eof_code;
public String eof_value_code;
/* Class, function, type names. */
public String class_name = "Yylex";
public String implements_name;
public String function_name = "yylex";
public String type_name = "Yytoken";
public String namespace_name = "YyNameSpace";
/*
* Constants
*/
public const int NONE = 0;
public const int START = 1;
public const int END = 2;
class StrHCode : IHashCodeProvider
{
/*
* Provides a hashkey for string, for use with Hashtable.
*
* The First 100,008 Primes
* (the 10,000th is 104,729)
* (the 100,008th is 1,299,827)
* For more information on primes see http://www.utm.edu/research/primes
*/
const int prime = 1299827;
public int GetHashCode(Object o)
{
if (o.GetType() != Type.GetType("System.String"))
throw new ApplicationException("Argument must be a String, found ["
+ o.GetType().ToString()+"]");
String s = (String) o;
int h = prime;
for (int i = 0; i < s.Length; i++)
{
Char c = s[i];
h ^= Convert.ToInt32(c);
}
return h%prime;
}
}
class StrHComp : IComparer
{
/*
* Provides a compare function for a String, for use with Hashtable.
*/
public int Compare(Object o1, Object o2)
{
if (o1.GetType() != Type.GetType("System.String") ||
o2.GetType() != Type.GetType("System.String"))
throw new ApplicationException("Argument must be a String");
String s1 = (String) o1;
String s2 = (String) o2;
return (String.Compare(s1, s2));
}
}
/*
* Function: Spec
* Description: Constructor.
*/
public Spec()
{
/* Initialize regular expression token variables. */
current_token = Gen.EOS;
lexeme = '\0';
in_quote = false;
in_ccl = false;
/* Initialize hashtable for lexer states. */
states = new Hashtable(new StrHCode(), new StrHComp());
states["YYINITIAL"] = (int) states.Count;
/* Initialize hashtable for lexical macros. */
macros = new Hashtable(new StrHCode(), new StrHComp());
/* Initialize variables for lexer options. */
integer_type = false;
intwrap_type = false;
count_lines = false;
count_chars = false;
cup_compatible = false;
lex_public = false;
yyeof = false;
ignorecase = false;
/* Initialize variables for Lex runtime options. */
verbose = true;
nfa_start = null;
nfa_states = new ArrayList();
dfa_states = new ArrayList();
dfa_sets = new Hashtable(); // uses BitSet
dtrans_list = new ArrayList();
dtrans_ncols = Utility.MAX_SEVEN_BIT + 1;
row_map = null;
col_map = null;
accept_list = null;
anchor_array = null;
init_code = null;
class_code = null;
eof_code = null;
eof_value_code = null;
state_dtrans = null;
state_rules = null;
}
private int unmarked_dfa;
public void InitUnmarkedDFA()
{
unmarked_dfa = 0;
}
/*
* Function: GetNextUnmarkedDFA
* Description: Returns next unmarked DFA state from spec
*/
public Dfa GetNextUnmarkedDFA()
{
int size;
Dfa dfa;
size = dfa_states.Count;
while (unmarked_dfa < size)
{
dfa = (Dfa) dfa_states[unmarked_dfa];
if (!dfa.IsMarked())
{
#if OLD_DUMP_DEBUG
Console.Write("*");
Console.WriteLine("---------------");
Console.Write("working on DFA state "
+ unmarked_dfa
+ " = NFA states: ");
Nfa2Dfa.Print_Set(dfa.GetNFASet());
Console.WriteLine("");
#endif
return dfa;
}
unmarked_dfa++;
}
return null;
}
}
}
| |
/* **********************************************************************************************************
* The MIT License (MIT) *
* *
* Copyright (c) 2016 Hypermediasystems Ges. f. Software mbH *
* Web: http://www.hypermediasystems.de *
* This file is part of hmssp *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
************************************************************************************************************ */
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using Newtonsoft.Json;
namespace HMS.SP{
/// <summary>
/// <para>https://msdn.microsoft.com/en-us/library/office/jj244790.aspx#properties</para>
/// </summary>
public class WebInformation : SPBase{
[JsonProperty("__HMSError")]
public HMS.Util.__HMSError __HMSError_ { set; get; }
[JsonProperty("__status")]
public SP.__status __status_ { set; get; }
[JsonProperty("__deferred")]
public SP.__deferred __deferred_ { set; get; }
[JsonProperty("__metadata")]
public SP.__metadata __metadata_ { set; get; }
public Dictionary<string, string> __rest;
/// <summary>
/// <para>Configuration identifier of the SharePoint Web site.(s. https://msdn.microsoft.com/en-us/library/office/jj838495.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Configuration")]
public Int16 Configuration_ { set; get; }
/// <summary>
/// <para>(s. https://msdn.microsoft.com/en-us/library/office/jj245711.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Created")]
public Object Created_ { set; get; }
/// <summary>
/// <para>Description of the SharePoint Web site.(s. https://msdn.microsoft.com/en-us/library/office/jj246343.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Description")]
public String Description_ { set; get; }
/// <summary>
/// <para>Description of the SharePoint Web site.(s. https://msdn.microsoft.com/en-us/library/office/jj246343.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("DescriptionResource")]
public SP.__deferred DescriptionResource_ { set; get; }
// undefined class Undefined : Object { }
/// <summary>
/// <para>A unique identifier of the SharePoint Web site.(s. https://msdn.microsoft.com/en-us/library/office/jj245809.aspx)[Undefined]</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Id")]
public Object Id_ { set; get; }
/// <summary>
/// <para>A 32-bit unsigned integer that indicates the locale identifier for the language.(s. https://msdn.microsoft.com/en-us/library/office/jj246110.aspx) [Number]</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Language")]
public Int32 Language_ { set; get; }
// undefined class Undefined : Object { }
/// <summary>
/// <para>Date when the last item of the Web site was changed.(s. https://msdn.microsoft.com/en-us/library/office/jj244877.aspx)[Undefined]</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("LastItemModifiedDate")]
public Object LastItemModifiedDate_ { set; get; }
/// <summary>
/// <para>A DateTime representing the last time a Web site item was changed.(s. https://msdn.microsoft.com/en-us/library/office/jj838569.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("ServerRelativeUrl")]
public String ServerRelativeUrl_ { set; get; }
/// <summary>
/// <para>Title of the Web site.(s. https://msdn.microsoft.com/en-us/library/office/jj245739.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Title")]
public String Title_ { set; get; }
/// <summary>
/// <para>Title of the Web site.(s. https://msdn.microsoft.com/en-us/library/office/jj245739.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("TitleResource")]
public SP.__deferred TitleResource_ { set; get; }
/// <summary>
/// <para>(s. https://msdn.microsoft.com/en-us/library/office/jj850931.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("WebTemplate")]
public Object WebTemplate_ { set; get; }
/// <summary>
/// <para>An identifier indicating the Web site template.(s. https://msdn.microsoft.com/en-us/library/office/jj246216.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("WebTemplateId")]
public Int32 WebTemplateId_ { set; get; }
/// <summary>
/// <para> Endpoints </para>
/// </summary>
static string[] endpoints = {
};
public WebInformation(ExpandoObject expObj)
{
try
{
var use_EO = ((dynamic)expObj).entry.content.properties;
HMS.SP.SPUtil.expando2obj(use_EO, this, typeof(WebInformation));
}
catch (Exception ex)
{
}
}
// used by Newtonsoft.JSON
public WebInformation()
{
}
public WebInformation(string json)
{
if( json == String.Empty )
return;
dynamic jobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
dynamic refObj = jobject;
if (jobject.d != null)
refObj = jobject.d;
string errInfo = "";
if (refObj.results != null)
{
if (refObj.results.Count > 1)
errInfo = "Result is Collection, only 1. entry displayed.";
refObj = refObj.results[0];
}
List<string> usedFields = new List<string>();
usedFields.Add("__HMSError");
HMS.SP.SPUtil.dyn_ValueSet("__HMSError", refObj, this);
usedFields.Add("__deferred");
this.__deferred_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.__deferred));
usedFields.Add("__metadata");
this.__metadata_ = new SP.__metadata(HMS.SP.SPUtil.dyn_toString(refObj.__metadata));
usedFields.Add("Configuration");
HMS.SP.SPUtil.dyn_ValueSet("Configuration", refObj, this);
usedFields.Add("Created");
HMS.SP.SPUtil.dyn_ValueSet("Created", refObj, this);
usedFields.Add("Description");
HMS.SP.SPUtil.dyn_ValueSet("Description", refObj, this);
usedFields.Add("DescriptionResource");
this.DescriptionResource_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.DescriptionResource));
usedFields.Add("Id");
HMS.SP.SPUtil.dyn_ValueSet("Id", refObj, this);
usedFields.Add("Language");
HMS.SP.SPUtil.dyn_ValueSet("Language", refObj, this);
usedFields.Add("LastItemModifiedDate");
HMS.SP.SPUtil.dyn_ValueSet("LastItemModifiedDate", refObj, this);
usedFields.Add("ServerRelativeUrl");
HMS.SP.SPUtil.dyn_ValueSet("ServerRelativeUrl", refObj, this);
usedFields.Add("Title");
HMS.SP.SPUtil.dyn_ValueSet("Title", refObj, this);
usedFields.Add("TitleResource");
this.TitleResource_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.TitleResource));
usedFields.Add("WebTemplate");
HMS.SP.SPUtil.dyn_ValueSet("WebTemplate", refObj, this);
usedFields.Add("WebTemplateId");
HMS.SP.SPUtil.dyn_ValueSet("WebTemplateId", refObj, this);
this.__rest = new Dictionary<string, string>();
var dyn = ((Newtonsoft.Json.Linq.JContainer)refObj).First;
while (dyn != null)
{
string Name = ((Newtonsoft.Json.Linq.JProperty)dyn).Name;
string Value = ((Newtonsoft.Json.Linq.JProperty)dyn).Value.ToString();
if ( !usedFields.Contains( Name ))
this.__rest.Add( Name, Value);
dyn = dyn.Next;
}
if( errInfo != "")
this.__HMSError_.info = errInfo;
}
}
}
| |
// 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;
namespace System.Data
{
internal sealed class RecordManager
{
private readonly DataTable _table;
private int _lastFreeRecord;
private int _minimumCapacity = 50;
private int _recordCapacity = 0;
private readonly List<int> _freeRecordList = new List<int>();
private DataRow[] _rows;
internal RecordManager(DataTable table)
{
if (table == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(table));
}
_table = table;
}
private void GrowRecordCapacity()
{
RecordCapacity = NewCapacity(_recordCapacity) < NormalizedMinimumCapacity(_minimumCapacity) ?
NormalizedMinimumCapacity(_minimumCapacity) :
NewCapacity(_recordCapacity);
// set up internal map : record --> row
DataRow[] newRows = _table.NewRowArray(_recordCapacity);
if (_rows != null)
{
Array.Copy(_rows, 0, newRows, 0, Math.Min(_lastFreeRecord, _rows.Length));
}
_rows = newRows;
}
internal int LastFreeRecord => _lastFreeRecord;
internal int MinimumCapacity
{
get { return _minimumCapacity; }
set
{
if (_minimumCapacity != value)
{
if (value < 0)
{
throw ExceptionBuilder.NegativeMinimumCapacity();
}
_minimumCapacity = value;
}
}
}
internal int RecordCapacity
{
get { return _recordCapacity; }
set
{
if (_recordCapacity != value)
{
for (int i = 0; i < _table.Columns.Count; i++)
{
_table.Columns[i].SetCapacity(value);
}
_recordCapacity = value;
}
}
}
internal static int NewCapacity(int capacity) =>
(capacity < 128) ? 128 : (capacity + capacity);
// Normalization: 64, 256, 1024, 2k, 3k, ....
private int NormalizedMinimumCapacity(int capacity)
{
if (capacity < 1024 - 10)
{
if (capacity < 256 - 10)
{
if (capacity < 54)
return 64;
return 256;
}
return 1024;
}
return (((capacity + 10) >> 10) + 1) << 10;
}
internal int NewRecordBase()
{
int record;
if (_freeRecordList.Count != 0)
{
record = _freeRecordList[_freeRecordList.Count - 1];
_freeRecordList.RemoveAt(_freeRecordList.Count - 1);
}
else
{
if (_lastFreeRecord >= _recordCapacity)
{
GrowRecordCapacity();
}
record = _lastFreeRecord;
_lastFreeRecord++;
}
Debug.Assert(record >= 0 && record < _recordCapacity, "NewRecord: Invalid record");
return record;
}
internal void FreeRecord(ref int record)
{
Debug.Assert(-1 <= record && record < _recordCapacity, "invalid record");
// Debug.Assert(record < lastFreeRecord, "Attempt to Free() <outofbounds> record");
if (-1 != record)
{
this[record] = null;
int count = _table._columnCollection.Count;
for (int i = 0; i < count; ++i)
{
_table._columnCollection[i].FreeRecord(record);
}
// if freeing the last record, recycle it
if (_lastFreeRecord == record + 1)
{
_lastFreeRecord--;
}
else if (record < _lastFreeRecord)
{
_freeRecordList.Add(record);
}
record = -1;
}
}
internal void Clear(bool clearAll)
{
if (clearAll)
{
for (int record = 0; record < _recordCapacity; ++record)
{
_rows[record] = null;
}
int count = _table._columnCollection.Count;
for (int i = 0; i < count; ++i)
{
// this improves performance by caching the column instead of obtaining it for each row
DataColumn column = _table._columnCollection[i];
for (int record = 0; record < _recordCapacity; ++record)
{
column.FreeRecord(record);
}
}
_lastFreeRecord = 0;
_freeRecordList.Clear();
}
else
{ // just clear attached rows
_freeRecordList.Capacity = _freeRecordList.Count + _table.Rows.Count;
for (int record = 0; record < _recordCapacity; ++record)
{
if (_rows[record] != null && _rows[record].rowID != -1)
{
int tempRecord = record;
FreeRecord(ref tempRecord);
}
}
}
}
internal DataRow this[int record]
{
get
{
Debug.Assert(record >= 0 && record < _rows.Length, "Invalid record number");
return _rows[record];
}
set
{
Debug.Assert(record >= 0 && record < _rows.Length, "Invalid record number");
_rows[record] = value;
}
}
internal void SetKeyValues(int record, DataKey key, object[] keyValues)
{
for (int i = 0; i < keyValues.Length; i++)
{
key.ColumnsReference[i][record] = keyValues[i];
}
}
// Increases AutoIncrementCurrent
internal int ImportRecord(DataTable src, int record)
{
return CopyRecord(src, record, -1);
}
// No impact on AutoIncrementCurrent if over written
internal int CopyRecord(DataTable src, int record, int copy)
{
Debug.Assert(src != null, "Can not Merge record without a table");
if (record == -1)
{
return copy;
}
int newRecord = -1;
try
{
newRecord = copy == -1 ?
_table.NewUninitializedRecord() :
copy;
int count = _table.Columns.Count;
for (int i = 0; i < count; ++i)
{
DataColumn dstColumn = _table.Columns[i];
DataColumn srcColumn = src.Columns[dstColumn.ColumnName];
if (null != srcColumn)
{
object value = srcColumn[record];
ICloneable cloneableObject = value as ICloneable;
if (null != cloneableObject)
{
dstColumn[newRecord] = cloneableObject.Clone();
}
else
{
dstColumn[newRecord] = value;
}
}
else if (-1 == copy)
{
dstColumn.Init(newRecord);
}
}
}
catch (Exception e) when (Common.ADP.IsCatchableOrSecurityExceptionType(e))
{
if (-1 == copy)
{
FreeRecord(ref newRecord);
}
throw;
}
return newRecord;
}
internal void SetRowCache(DataRow[] newRows)
{
_rows = newRows;
_lastFreeRecord = _rows.Length;
_recordCapacity = _lastFreeRecord;
}
[Conditional("DEBUG")]
internal void VerifyRecord(int record)
{
Debug.Assert((record < _lastFreeRecord) && (-1 == _freeRecordList.IndexOf(record)), "accesing free record");
Debug.Assert((null == _rows[record]) ||
(record == _rows[record]._oldRecord) ||
(record == _rows[record]._newRecord) ||
(record == _rows[record]._tempRecord), "record of a different row");
}
[Conditional("DEBUG")]
internal void VerifyRecord(int record, DataRow row)
{
Debug.Assert((record < _lastFreeRecord) && (-1 == _freeRecordList.IndexOf(record)), "accesing free record");
Debug.Assert((null == _rows[record]) || (row == _rows[record]), "record of a different row");
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Configuration;
using System.Data;
using System.Net;
using System.Net.Mail;
using ASC.Common.Data;
using ASC.Mail.Server.Core.Dao;
using ASC.Mail.Server.Core.Entities;
using ASC.Mail.Server.Utils;
using Newtonsoft.Json.Linq;
using RestSharp;
namespace ASC.Mail.Server.Core
{
public class ServerEngine
{
private readonly string _csName;
private readonly ServerApi _serverApi;
public ServerEngine(int serverId, string connectionString)
{
var serverDbConnection = string.Format("postfixserver{0}", serverId);
var connectionStringParser = new PostfixConnectionStringParser(connectionString);
var cs = new ConnectionStringSettings(serverDbConnection,
connectionStringParser.PostfixAdminDbConnectionString, "MySql.Data.MySqlClient");
if (!DbRegistry.IsDatabaseRegistered(cs.Name))
{
DbRegistry.RegisterDatabase(cs.Name, cs);
}
_csName = cs.Name;
var json = JObject.Parse(connectionString);
if (json["Api"] != null)
{
_serverApi = new ServerApi
{
server_ip = json["Api"]["Server"].ToString(),
port = Convert.ToInt32(json["Api"]["Port"].ToString()),
protocol = json["Api"]["Protocol"].ToString(),
version = json["Api"]["Version"].ToString(),
token = json["Api"]["Token"].ToString()
};
}
}
public int SaveDomain(Domain domain)
{
using (var db = DbManager.FromHttpContext(_csName))
{
var domainDao = new DomainDao(db);
return domainDao.Save(domain);
}
}
public int SaveDkim(Dkim dkim)
{
using (var db = DbManager.FromHttpContext(_csName))
{
var dkimDao = new DkimDao(db);
return dkimDao.Save(dkim);
}
}
public int SaveAlias(Alias alias)
{
using (var db = DbManager.FromHttpContext(_csName))
{
var aliasDao = new AliasDao(db);
return aliasDao.Save(alias);
}
}
public int RemoveAlias(string alias)
{
using (var db = DbManager.FromHttpContext(_csName))
{
var aliasDao = new AliasDao(db);
return aliasDao.Remove(alias);
}
}
public void ChangePassword(string username, string newPassword)
{
using (var db = DbManager.FromHttpContext(_csName))
{
var mailboxDao = new MailboxDao(db);
var res = mailboxDao.ChangePassword(username, newPassword);
if (res < 1)
throw new Exception(string.Format("Server mailbox \"{0}\" not found", username));
}
}
public void SaveMailbox(Mailbox mailbox, Alias address, bool deliver = true)
{
using (var db = DbManager.FromHttpContext(_csName))
{
using (var tx = db.BeginTransaction(IsolationLevel.ReadUncommitted))
{
var mailboxDao = new MailboxDao(db);
mailboxDao.Save(mailbox, deliver);
var aliasDao = new AliasDao(db);
aliasDao.Save(address);
tx.Commit();
}
}
}
public void RemoveMailbox(string address)
{
var mailAddress = new MailAddress(address);
ClearMailboxStorageSpace(mailAddress.User, mailAddress.Host);
using (var db = DbManager.FromHttpContext(_csName))
{
using (var tx = db.BeginTransaction(IsolationLevel.ReadUncommitted))
{
var mailboxDao = new MailboxDao(db);
mailboxDao.Remove(address);
var aliasDao = new AliasDao(db);
aliasDao.Remove(address);
tx.Commit();
}
}
}
public void RemoveDomain(string domain, bool withStorageClean = true)
{
if (withStorageClean)
ClearDomainStorageSpace(domain);
using (var db = DbManager.FromHttpContext(_csName))
{
using (var tx = db.BeginTransaction(IsolationLevel.ReadUncommitted))
{
var aliasDao = new AliasDao(db);
aliasDao.RemoveByDomain(domain);
var mailboxDao = new MailboxDao(db);
mailboxDao.RemoveByDomain(domain);
var domainDao = new DomainDao(db);
domainDao.Remove(domain);
var dkimDao = new DkimDao(db);
dkimDao.Remove(domain);
tx.Commit();
}
}
}
public string GetVersion()
{
if (_serverApi == null)
return null;
var client = GetApiClient();
var request = GetApiRequest("version", Method.GET);
var response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NotFound)
throw new Exception("MailServer->GetVersion() Response code = " + response.StatusCode, response.ErrorException);
var json = JObject.Parse(response.Content);
if (json == null) return null;
var globalVars = json["global_vars"];
if (globalVars == null) return null;
var version = globalVars["value"];
return version == null ? null : version.ToString();
}
private void ClearDomainStorageSpace(string domain)
{
if (_serverApi == null) return;
var client = GetApiClient();
var request = GetApiRequest("domains/{domain_name}", Method.DELETE);
request.AddUrlSegment("domain_name", domain);
// execute the request
var response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NotFound)
throw new Exception("MailServer->ClearDomainStorageSpace(). Response code = " + response.StatusCode, response.ErrorException);
}
private void ClearMailboxStorageSpace(string mailboxLocalpart, string domainName)
{
if (_serverApi == null) return; // Skip if api not presented
var client = GetApiClient();
var request = GetApiRequest("domains/{domain_name}/mailboxes/{mailbox_localpart}", Method.DELETE);
request.AddUrlSegment("domain_name", domainName);
request.AddUrlSegment("mailbox_localpart", mailboxLocalpart);
// execute the request
var response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NotFound)
throw new Exception("MailServer->ClearMailboxStorageSpace(). Response code = " + response.StatusCode, response.ErrorException);
}
private RestClient GetApiClient()
{
return _serverApi == null ? null : new RestClient(string.Format("{0}://{1}:{2}/", _serverApi.protocol, _serverApi.server_ip, _serverApi.port));
}
private RestRequest GetApiRequest(string apiUrl, Method method)
{
return _serverApi == null ? null : new RestRequest(string.Format("/api/{0}/{1}?auth_token={2}", _serverApi.version, apiUrl, _serverApi.token), method);
}
}
}
| |
using System;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading.Tasks;
using Moq;
using Shouldly;
using Xunit;
namespace Postal
{
public class EmailParserTests
{
[Fact]
public async Task Parse_creates_MailMessage_with_headers_and_body()
{
var input = @"
To: test1@test.com
From: test2@test.com
CC: test3@test.com
Bcc: test4@test.com
Reply-To: test5@test.com
Sender: test6@test.com
Priority: high
X-Test: test
Subject: Test Subject
Hello, World!";
var renderer = new Mock<IEmailViewRender>();
var parser = new EmailParser(renderer.Object);
using (var message = await parser.ParseAsync(input, new Email("Test")))
{
message.To[0].Address.ShouldBe("test1@test.com");
message.From.Address.ShouldBe("test2@test.com");
message.CC[0].Address.ShouldBe("test3@test.com");
message.Bcc[0].Address.ShouldBe("test4@test.com");
message.ReplyToList[0].Address.ShouldBe("test5@test.com");
message.Subject.ShouldBe("Test Subject");
message.Sender.Address.ShouldBe("test6@test.com");
message.Priority.ShouldBe(MailPriority.High);
message.Headers["X-Test"].ShouldBe("test");
message.Body.ShouldBe("Hello, World!");
message.IsBodyHtml.ShouldBeFalse();
}
renderer.Verify();
}
[Fact]
public async Task Parse_creates_email_addresses_with_display_name()
{
var input = @"
To: John H Smith test1@test.com
From: test2@test.com
Subject: Test Subject
Hello, World!";
var renderer = new Mock<IEmailViewRender>();
var parser = new EmailParser(renderer.Object);
using (var message = await parser.ParseAsync(input, new Email("Test")))
{
message.To[0].Address.ShouldBe("test1@test.com");
message.To[0].DisplayName.ShouldBe("John H Smith");
}
renderer.Verify();
}
[Fact]
public async Task Repeating_CC_adds_each_email_address_to_list()
{
var input = @"
To: test1@test.com
From: test2@test.com
CC: test3@test.com
CC: test4@test.com
CC: test5@test.com
Subject: Test Subject
Hello, World!";
var renderer = new Mock<IEmailViewRender>();
var parser = new EmailParser(renderer.Object);
using (var message = await parser.ParseAsync(input, new Email("Test")))
{
message.CC[0].Address.ShouldBe("test3@test.com");
message.CC[1].Address.ShouldBe("test4@test.com");
message.CC[2].Address.ShouldBe("test5@test.com");
}
}
[Fact]
public async Task Can_parse_multiple_email_addresses_in_header()
{
var input = @"
To: test1@test.com
From: test2@test.com
CC: test3@test.com, test4@test.com, test5@test.com
Subject: Test Subject
Hello, World!";
var renderer = new Mock<IEmailViewRender>();
var parser = new EmailParser(renderer.Object);
using (var message = await parser.ParseAsync(input, new Email("Test")))
{
message.CC[0].Address.ShouldBe("test3@test.com");
message.CC[1].Address.ShouldBe("test4@test.com");
message.CC[2].Address.ShouldBe("test5@test.com");
}
renderer.Verify();
}
[Fact]
public async Task Can_detect_HTML_body()
{
var input = @"
To: test1@test.com
From: test2@test.com
Subject: Test Subject
<p>Hello, World!</p>";
var renderer = new Mock<IEmailViewRender>();
var parser = new EmailParser(renderer.Object);
using (var message = await parser.ParseAsync(input, new Email("Test")))
{
message.Body.ShouldBe("<p>Hello, World!</p>");
message.IsBodyHtml.ShouldBeTrue();
}
}
[Fact]
public async Task Can_detect_HTML_body_with_leading_whitespace()
{
var input = @"
To: test1@test.com
From: test2@test.com
Subject: Test Subject
<p>Hello, World!</p>";
var renderer = new Mock<IEmailViewRender>();
var parser = new EmailParser(renderer.Object);
using (var message = await parser.ParseAsync(input, new Email("Test")))
{
message.Body.ShouldBe("<p>Hello, World!</p>");
message.IsBodyHtml.ShouldBeTrue();
}
renderer.Verify();
}
[Fact]
public async Task Alternative_views_are_added_to_MailMessage()
{
var input = @"
To: test1@test.com
From: test2@test.com
Subject: Test Subject
Views: Text, Html";
var text = @"Content-Type: text/plain
Hello, World!";
var html = @"Content-Type: text/html
<p>Hello, World!</p>";
var email = new Email("Test");
var renderer = new Mock<IEmailViewRender>();
renderer.Setup(r => r.RenderAsync(email, "Test.Text")).Returns(Task.FromResult(text));
renderer.Setup(r => r.RenderAsync(email, "Test.Html")).Returns(Task.FromResult(html));
var parser = new EmailParser(renderer.Object);
using (var message = await parser.ParseAsync(input, email))
{
message.AlternateViews[0].ContentType.ShouldBe(new ContentType("text/plain; charset=utf-16"));
var textContent = new StreamReader(message.AlternateViews[0].ContentStream).ReadToEnd();
textContent.ShouldBe("Hello, World!");
message.AlternateViews[1].ContentType.ShouldBe(new ContentType("text/html; charset=utf-16"));
var htmlContent = new StreamReader(message.AlternateViews[1].ContentStream).ReadToEnd();
htmlContent.ShouldBe("<p>Hello, World!</p>");
}
renderer.Verify();
}
[Fact]
public async Task Given_base_view_is_full_path_Then_alternative_views_are_correctly_looked_up()
{
var input = @"
To: test1@test.com
From: test2@test.com
Subject: Test Subject
Views: Text, Html";
var text = @"Content-Type: text/plain
Hello, World!";
var html = @"Content-Type: text/html
<p>Hello, World!</p>";
var email = new Email("~/Views/Emails/Test.cshtml");
var renderer = new Mock<IEmailViewRender>();
renderer.Setup(r => r.RenderAsync(email, "~/Views/Emails/Test.Text.cshtml")).Returns(Task.FromResult(text));
renderer.Setup(r => r.RenderAsync(email, "~/Views/Emails/Test.Html.cshtml")).Returns(Task.FromResult(html));
var parser = new EmailParser(renderer.Object);
using (var message = await parser.ParseAsync(input, email))
{
message.AlternateViews[0].ContentType.ShouldBe(new ContentType("text/plain; charset=utf-16"));
var textContent = new StreamReader(message.AlternateViews[0].ContentStream).ReadToEnd();
textContent.ShouldBe("Hello, World!");
message.AlternateViews[1].ContentType.ShouldBe(new ContentType("text/html; charset=utf-16"));
var htmlContent = new StreamReader(message.AlternateViews[1].ContentStream).ReadToEnd();
htmlContent.ShouldBe("<p>Hello, World!</p>");
}
renderer.Verify();
}
[Fact]
public async Task Attachments_are_added_to_MailMessage()
{
var input = @"
To: test1@test.com
From: test2@test.com
Subject: Test Subject
Hello, World!";
var email = new Email("Test");
email.Attach(new Attachment(new MemoryStream(), "name"));
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
var message = await parser.ParseAsync(input, email);
message.Attachments.Count.ShouldBe(1);
}
[Fact]
public async Task ContentType_determined_by_view_name_when_alternative_view_is_missing_Content_Type_header()
{
var input = @"
To: test1@test.com
From: test2@test.com
Subject: Test Subject
Views: Text, Html";
var text = @"
Hello, World!";
var html = @"
<p>Hello, World!</p>";
var email = new Email("Test");
var renderer = new Mock<IEmailViewRender>();
renderer.Setup(r => r.RenderAsync(email, "Test.Text")).Returns(Task.FromResult(text));
renderer.Setup(r => r.RenderAsync(email, "Test.Html")).Returns(Task.FromResult(html));
var parser = new EmailParser(renderer.Object);
using (var message = await parser.ParseAsync(input, email))
{
message.AlternateViews[0].ContentType.MediaType.ShouldBe("text/plain");
message.AlternateViews[1].ContentType.MediaType.ShouldBe("text/html");
}
renderer.Verify();
}
[Fact]
public async Task To_header_can_be_set_automatically()
{
dynamic email = new Email("Test");
email.To = "test@test.com";
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
using (var message = await parser.ParseAsync("body", (Email)email))
{
message.To[0].Address.ShouldBe("test@test.com");
}
}
[Fact]
public async Task Subject_header_can_be_set_automatically()
{
dynamic email = new Email("Test");
email.Subject = "test";
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
using (var message = await parser.ParseAsync("body", (Email)email))
{
message.Subject.ShouldBe("test");
}
}
[Fact]
public async Task From_header_can_be_set_automatically()
{
dynamic email = new Email("Test");
email.From = "test@test.com";
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
using (var message = await parser.ParseAsync("body", (Email)email))
{
message.From.Address.ShouldBe("test@test.com");
}
}
[Fact]
public async Task From_header_can_be_set_automatically_as_MailAddress()
{
dynamic email = new Email("Test");
email.From = new MailAddress("test@test.com");
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
using (var message = await parser.ParseAsync("body", (Email)email))
{
message.From.ShouldBe(new MailAddress("test@test.com"));
}
}
[Fact]
public async Task ReplyTo_header_can_be_set_automatically()
{
dynamic email = new Email("Test");
email.ReplyTo = "test@test.com";
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
using (var message = await parser.ParseAsync("body", (Email)email))
{
message.ReplyToList[0].Address.ShouldBe("test@test.com");
}
}
[Fact]
public async Task Priority_header_can_be_set_automatically()
{
dynamic email = new Email("Test");
email.Priority = "high";
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
using (var message = await parser.ParseAsync("body", (Email)email))
{
message.Priority = MailPriority.High;
}
}
[Fact]
public async Task Priority_header_can_be_set_automatically_from_MailPriorityEnum()
{
dynamic email = new Email("Test");
email.Priority = MailPriority.High;
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
using (var message = await parser.ParseAsync("body", (Email)email))
{
message.Priority = MailPriority.High;
}
}
[Fact]
public async Task Email_address_can_include_display_name()
{
var input = @"To: ""John Smith"" <test@test.com>
From: test2@test.com
Subject: test
message";
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
var email = new Email("Test");
using (var message = await parser.ParseAsync(input, email))
{
message.To[0].Address.ShouldBe("test@test.com");
message.To[0].DisplayName.ShouldBe("John Smith");
}
}
[Fact]
public async Task Can_parse_empty_header_fields()
{
var input = @"To: test@test.com
From: test2@test.com
CC:
Bcc:
Reply-To:
Subject: test
message";
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
var email = new Email("Test");
using (var message = await parser.ParseAsync(input, email))
{
message.To.Count.ShouldBe(1);
message.To[0].Address.ShouldBe("test@test.com");
}
}
[Fact]
public async Task Can_parse_reply_to()
{
var input = @"To: test@test.com
From: test2@test.com
Reply-To: other@test.com
Subject: test
message";
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
var email = new Email("Test");
using (var message = await parser.ParseAsync(input, email))
{
message.ReplyToList[0].Address.ShouldBe("other@test.com");
// Check for bug reported here: http://aboutcode.net/2010/11/17/going-postal-generating-email-with-aspnet-mvc-view-engines.html#comment-153486994
// Should not add anything extra to the 'To' list.
message.To.Count.ShouldBe(1);
message.To[0].Address.ShouldBe("test@test.com");
}
}
[Fact]
public async Task Do_not_implicitly_add_To_from_model_when_set_in_view()
{
var input = @"To: test@test.com
From: test2@test.com
Subject: test
message";
var parser = new EmailParser(Mock.Of<IEmailViewRender>());
dynamic email = new Email("Test");
email.To = "test@test.com";
using (var message = await parser.ParseAsync(input, (Email)email))
{
// Check for bug reported here: http://aboutcode.net/2010/11/17/going-postal-generating-email-with-aspnet-mvc-view-engines.html#comment-153486994
// Should not add anything extra to the 'To' list.
message.To.Count.ShouldBe(1);
message.To[0].Address.ShouldBe("test@test.com");
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ShowCommandHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Implements ShowCommandHelper
// </summary>
//-----------------------------------------------------------------------
namespace Microsoft.PowerShell.Commands.ShowCommandInternal
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Microsoft.Management.UI;
using Microsoft.Management.UI.Internal;
using Microsoft.Management.UI.Internal.ShowCommand;
using Microsoft.PowerShell.Commands.ShowCommandExtension;
/// <summary>
/// Implements the WPF window part of the show-command cmdlet
/// </summary>
internal class ShowCommandHelper : IDisposable
{
#region fields
internal const string CommandTypeSegment = " -CommandType Cmdlet, Function, Script, ExternalScript, Workflow";
/// <summary>
/// Method that will return the dialog from ShowAllModulesWindow or ShowCommandWindow.
/// This is necessary because the PlainInvokeAndShowDialog thread starter cannot receive parameters
/// </summary>
private DispatcherOperationCallback methodThatReturnsDialog;
/// <summary>
/// Event set when the window is closed
/// </summary>
private AutoResetEvent windowClosed = new AutoResetEvent(false);
/// <summary>
/// Event set when help is needed
/// </summary>
private AutoResetEvent helpNeeded = new AutoResetEvent(false);
/// <summary>
/// Event set when it is necessary to import a module
/// </summary>
private AutoResetEvent importModuleNeeded = new AutoResetEvent(false);
/// <summary>
/// Event set when the window is loaded
/// </summary>
private AutoResetEvent windowLoaded = new AutoResetEvent(false);
/// <summary>
/// String with the command that needs help set when helpNeeded is set
/// </summary>
private string commandNeedingHelp;
/// <summary>
/// String with the command name that needs to import a module
/// </summary>
private string commandNeedingImportModule;
/// <summary>
/// String with the module name that needs to be imported
/// </summary>
private string parentModuleNeedingImportModule;
/// <summary>
/// String with the selected module at the time a module needs to be imported
/// </summary>
private string selectedModuleNeedingImportModule;
/// <summary>
/// Keeps the window for the implementation of CloseWindow
/// </summary>
private Window window;
/// <summary>
/// host window, if any
/// </summary>
private Window hostWindow;
/// <summary>
/// ViewModel when showing all modules
/// </summary>
private AllModulesViewModel allModulesViewModel;
/// <summary>
/// ViewModel when showing a single command
/// </summary>
private CommandViewModel commandViewModel;
/// <summary>
/// true when the window is closed with cancel
/// </summary>
private bool dialogCanceled = true;
#endregion fields
#region GetSerializedCommand script
private const string ScriptGetSerializedCommand = @"
Function PSGetSerializedShowCommandInfo
{
Function GetParameterType
{
param (
[Type] $parameterType)
$returnParameterType = new-object PSObject
$returnParameterType | Add-Member -MemberType NoteProperty -Name ""FullName"" -Value $parameterType.FullName
$returnParameterType | Add-Member -MemberType NoteProperty -Name ""IsEnum"" -Value $parameterType.IsEnum
$returnParameterType | Add-Member -MemberType NoteProperty -Name ""IsArray"" -Value $parameterType.IsArray
if ($parameterType.IsEnum)
{
$enumValues = [System.Enum]::GetValues($parameterType)
}
else
{
$enumValues = [string[]] @()
}
$returnParameterType | Add-Member -MemberType NoteProperty -Name ""EnumValues"" -Value $enumValues
if ($parameterType.IsArray)
{
$hasFlagAttribute = ($parameterType.GetCustomAttributes([System.FlagsAttribute], $true).Length -gt 0)
# Recurse into array elements.
$elementType = GetParameterType($parameterType.GetElementType())
}
else
{
$hasFlagAttribute = $false
$elementType = $null
}
$returnParameterType | Add-Member -MemberType NoteProperty -Name ""HasFlagAttribute"" -Value $hasFlagAttribute
$returnParameterType | Add-Member -MemberType NoteProperty -Name ""ElementType"" -Value $elementType
if (!($parameterType.IsEnum) -and !($parameterType.IsArray))
{
$implementsDictionary = [System.Collections.IDictionary].IsAssignableFrom($parameterType)
}
else
{
$implementsDictionary = $false
}
$returnParameterType | Add-Member -MemberType NoteProperty -Name ""ImplementsDictionary"" -Value $implementsDictionary
return $returnParameterType
}
Function GetParameterInfo
{
param (
$parameters)
[PSObject[]] $parameterInfos = @()
foreach ($parameter in $parameters)
{
$parameterInfo = new-object PSObject
$parameterInfo | Add-Member -MemberType NoteProperty -Name ""Name"" -Value $parameter.Name
$parameterInfo | Add-Member -MemberType NoteProperty -Name ""IsMandatory"" -Value $parameter.IsMandatory
$parameterInfo | Add-Member -MemberType NoteProperty -Name ""ValueFromPipeline"" -Value $parameter.ValueFromPipeline
$parameterInfo | Add-Member -MemberType NoteProperty -Name ""Position"" -Value $parameter.Position
$parameterInfo | Add-Member -MemberType NoteProperty -Name ""ParameterType"" -Value (GetParameterType($parameter.ParameterType))
$hasParameterSet = $false
[string[]] $validValues = @()
if ($PSVersionTable.PSVersion.Major -gt 2)
{
$validateSetAttributes = $parameter.Attributes | Where {
[ValidateSet].IsAssignableFrom($_.GetType())
}
if (($validateSetAttributes -ne $null) -and ($validateSetAttributes.Count -gt 0))
{
$hasParameterSet = $true
$validValues = $validateSetAttributes[0].ValidValues
}
}
$parameterInfo | Add-Member -MemberType NoteProperty -Name ""HasParameterSet"" -Value $hasParameterSet
$parameterInfo | Add-Member -MemberType NoteProperty -Name ""ValidParamSetValues"" -Value $validValues
$parameterInfos += $parameterInfo
}
return (,$parameterInfos)
}
Function GetParameterSets
{
param (
[System.Management.Automation.CommandInfo] $cmdInfo
)
$parameterSets = $null
try
{
$parameterSets = $cmdInfo.ParameterSets
}
catch [System.InvalidOperationException] { }
catch [System.Management.Automation.PSNotSupportedException] { }
catch [System.Management.Automation.PSNotImplementedException] { }
if (($parameterSets -eq $null) -or ($parameterSets.Count -eq 0))
{
return (,@())
}
[PSObject[]] $returnParameterSets = @()
foreach ($parameterSet in $parameterSets)
{
$parameterSetInfo = new-object PSObject
$parameterSetInfo | Add-Member -MemberType NoteProperty -Name ""Name"" -Value $parameterSet.Name
$parameterSetInfo | Add-Member -MemberType NoteProperty -Name ""IsDefault"" -Value $parameterSet.IsDefault
$parameterSetInfo | Add-Member -MemberType NoteProperty -Name ""Parameters"" -Value (GetParameterInfo($parameterSet.Parameters))
$returnParameterSets += $parameterSetInfo
}
return (,$returnParameterSets)
}
Function GetModuleInfo
{
param (
[System.Management.Automation.CommandInfo] $cmdInfo
)
if ($cmdInfo.ModuleName -ne $null)
{
$moduleName = $cmdInfo.ModuleName
}
else
{
$moduleName = """"
}
$moduleInfo = new-object PSObject
$moduleInfo | Add-Member -MemberType NoteProperty -Name ""Name"" -Value $moduleName
return $moduleInfo
}
Function ConvertToShowCommandInfo
{
param (
[System.Management.Automation.CommandInfo] $cmdInfo
)
$showCommandInfo = new-object PSObject
$showCommandInfo | Add-Member -MemberType NoteProperty -Name ""Name"" -Value $cmdInfo.Name
$showCommandInfo | Add-Member -MemberType NoteProperty -Name ""ModuleName"" -Value $cmdInfo.ModuleName
$showCommandInfo | Add-Member -MemberType NoteProperty -Name ""Module"" -Value (GetModuleInfo($cmdInfo))
$showCommandInfo | Add-Member -MemberType NoteProperty -Name ""CommandType"" -Value $cmdInfo.CommandType
$showCommandInfo | Add-Member -MemberType NoteProperty -Name ""Definition"" -Value $cmdInfo.Definition
$showCommandInfo | Add-Member -MemberType NoteProperty -Name ""ParameterSets"" -Value (GetParameterSets($cmdInfo))
return $showCommandInfo
}
$commandList = @(""Cmdlet"", ""Function"", ""Script"", ""ExternalScript"")
if ($PSVersionTable.PSVersion.Major -gt 2)
{
$commandList += ""Workflow""
}
foreach ($command in @(Get-Command -CommandType $commandList))
{
Write-Output (ConvertToShowCommandInfo($command))
}
}";
#endregion
#region constructor and destructor
/// <summary>
/// Prevents a default instance of the ShowCommandHelper class from being created
/// </summary>
private ShowCommandHelper()
{
}
/// <summary>
/// Finalizes an instance of the ShowCommandHelper class
/// </summary>
~ShowCommandHelper()
{
this.Dispose(false);
}
#endregion constructor and destructor
#region properties called using reflection
/// <summary>
/// Gets the Screen Width
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private static double ScreenWidth
{
get
{
return System.Windows.SystemParameters.PrimaryScreenWidth;
}
}
/// <summary>
/// Gets the Screen Height
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private static double ScreenHeight
{
get
{
return System.Windows.SystemParameters.PrimaryScreenHeight;
}
}
/// <summary>
/// Gets the event set when the show-command window is closed
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private AutoResetEvent WindowClosed
{
get
{
return this.windowClosed;
}
}
/// <summary>
/// Gets the event set when help is needed for a command
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private AutoResetEvent HelpNeeded
{
get
{
return this.helpNeeded;
}
}
/// <summary>
/// Gets the event set when it is necessary to import a module
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private AutoResetEvent ImportModuleNeeded
{
get
{
return this.importModuleNeeded;
}
}
/// <summary>
/// Gets the event set when the window is loaded
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private AutoResetEvent WindowLoaded
{
get
{
return this.windowLoaded;
}
}
/// <summary>
/// Gets the command needing help when HelpNeeded is set
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private string CommandNeedingHelp
{
get
{
return this.commandNeedingHelp;
}
}
/// <summary>
/// Gets the module we want to import
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private string ParentModuleNeedingImportModule
{
get
{
return this.parentModuleNeedingImportModule;
}
}
/// <summary>
/// Gets a value indicating whether there is a host window
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private bool HasHostWindow
{
get
{
return this.hostWindow != null;
}
}
#endregion properties called using reflection
#region public Dispose
/// <summary>
/// Dispose method in IDisposable
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion public Dispose
#region internal static methods called using reflection from show-command and directly from ISE
/// <summary>
/// Sets the text in the clipboard
/// </summary>
/// <param name="text">text to set the clipboard to</param>
internal static void SetClipboardText(string text)
{
try
{
Clipboard.SetText(text);
}
catch (System.Runtime.InteropServices.COMException)
{
// This is the recommended way to set clipboard text
System.Threading.Thread.Sleep(0);
try
{
Clipboard.SetText(text);
}
catch (System.Runtime.InteropServices.COMException)
{
}
}
}
/// <summary>
/// Gets the command to be run to get commands and imported modules
/// </summary>
/// <param name="isRemoteRunspace">Boolean flag determining whether Show-Command is queried in the local or remote runspace scenario </param>
/// <param name="isFirstChance">Boolean flag to indicate that it is the second attempt to query Show-Command data </param>
/// <returns>the command to be run to get commands and imported modules</returns>
internal static string GetShowAllModulesCommand(bool isRemoteRunspace = false, bool isFirstChance = true)
{
string scriptBase;
if (isRemoteRunspace)
{
if (isFirstChance)
{
// Return command to run.
scriptBase = "@(Get-Command " + ShowCommandHelper.CommandTypeSegment + @" -ShowCommandInfo)";
}
else
{
// Return script to run.
scriptBase = GetSerializedCommandScript();
}
}
else
{
scriptBase = "@(Get-Command " + ShowCommandHelper.CommandTypeSegment + ")";
}
scriptBase += ShowCommandHelper.GetGetModuleSuffix();
return scriptBase;
}
/// <summary>
/// Retrieves the script for Get-SerializedCommand from local machine
/// </summary>
/// <returns>String representation of the script for Get-SerializedCommand</returns>
private static string GetSerializedCommandScript()
{
return string.Format(CultureInfo.InvariantCulture, "@({0};{1};{2})",
ScriptGetSerializedCommand,
@"PSGetSerializedShowCommandInfo",
@"Remove-Item -Path 'function:\PSGetSerializedShowCommandInfo' -Force");
}
/// <summary>
/// Gets the command to be run to in order to import a module and refresh the command data
/// </summary>
/// <param name="module">module we want to import</param>
/// <param name="isRemoteRunspace">Boolean flag determining whether Show-Command is queried in the local or remote runspace scenario </param>
/// <param name="isFirstChance">Boolean flag to indicate that it is the second attempt to query Show-Command data </param>
/// <returns>the command to be run to in order to import a module and refresh the command data</returns>
internal static string GetImportModuleCommand(string module, bool isRemoteRunspace = false, bool isFirstChance = true)
{
string scriptBase = "Import-Module " + ShowCommandHelper.SingleQuote(module);
if (isRemoteRunspace)
{
if (isFirstChance)
{
scriptBase += ";@(Get-Command " + ShowCommandHelper.CommandTypeSegment + @" -ShowCommandInfo )";
}
else
{
scriptBase += GetSerializedCommandScript();
}
}
else
{
scriptBase += ";@(Get-Command " + ShowCommandHelper.CommandTypeSegment + ")";
}
scriptBase += ShowCommandHelper.GetGetModuleSuffix();
return scriptBase;
}
/// <summary>
/// gets the command to be run in order to show help for a command
/// </summary>
/// <param name="command">command we want to get help from</param>
/// <returns>the command to be run in order to show help for a command</returns>
internal static string GetHelpCommand(string command)
{
return "Get-Help " + ShowCommandHelper.SingleQuote(command);
}
/// <summary>
/// Constructs a dictionary of imported modules based on the module names
/// </summary>
/// <param name="moduleObjects">the imported modules</param>
/// <returns>a dictionary of imported modules based on the module names</returns>
internal static Dictionary<string, ShowCommandModuleInfo> GetImportedModulesDictionary(object[] moduleObjects)
{
Dictionary<string, ShowCommandModuleInfo> returnValue = new Dictionary<string, ShowCommandModuleInfo>(StringComparer.OrdinalIgnoreCase);
foreach (PSObject rawModule in moduleObjects)
{
ShowCommandModuleInfo wrappedModule = null;
PSModuleInfo module = rawModule.BaseObject as PSModuleInfo;
if (module != null)
{
wrappedModule = new ShowCommandModuleInfo(module);
}
else
{
wrappedModule = new ShowCommandModuleInfo(rawModule);
}
// It is probably an issue somewhere else that a module would show up twice in the list, but we want to avoid
// throwing an exception regarding that in returnValue.Add
if(!returnValue.ContainsKey(wrappedModule.Name))
{
returnValue.Add(wrappedModule.Name, wrappedModule);
}
}
return returnValue;
}
/// <summary>
/// Constructs a list of commands out of <paramref name="commandObjects"/>
/// </summary>
/// <param name="commandObjects">the results of a get-command command</param>
/// <returns>a list of commands out of <paramref name="commandObjects"/></returns>
internal static List<ShowCommandCommandInfo> GetCommandList(object[] commandObjects)
{
List<ShowCommandCommandInfo> returnValue = new List<ShowCommandCommandInfo>();
foreach (PSObject rawCommand in commandObjects)
{
CommandInfo command = rawCommand.BaseObject as CommandInfo;
if(command != null)
{
returnValue.Add(new ShowCommandCommandInfo(command));
}
else
{
PSObject obj = rawCommand as PSObject;
if(obj != null)
{
returnValue.Add(new ShowCommandCommandInfo(obj));
}
}
}
return returnValue;
}
/// <summary>
/// Constructs an array of objects out of <paramref name="commandObjects"/>
/// </summary>
/// <param name="commandObjects">The result of a get-command command</param>
/// <returns>An array of objects out of <paramref name="commandObjects"/></returns>
internal static object[] ObjectArrayFromObjectCollection(object commandObjects)
{
object[] objectArray = commandObjects as object[];
if(objectArray == null)
{
objectArray = ((System.Collections.ArrayList)commandObjects).ToArray();
}
return objectArray;
}
/// <summary>
/// Called after a module in <paramref name="oldViewModel"/> is imported to refresh the view model.
/// Gets a new AllModulesViewModel populated with <paramref name="importedModules"/> and <paramref name="commands"/>.
/// The <paramref name="oldViewModel"/> is used to cleanup event listening in the old view model and to copy NoCommonParameters.
/// The new ViewModel will have the command selected according to <paramref name="selectedModuleNeedingImportModule"/>,
/// <paramref name="parentModuleNeedingImportModule"/> and <paramref name="commandNeedingImportModule"/>.
/// </summary>
/// <param name="oldViewModel">the viewModel before the module was imported</param>
/// <param name="importedModules">the list of imported modules</param>
/// <param name="commands">the list of commands</param>
/// <param name="selectedModuleNeedingImportModule">the name of the module that was selected in <paramref name="oldViewModel"/></param>
/// <param name="parentModuleNeedingImportModule">the name of the module that was imported</param>
/// <param name="commandNeedingImportModule">the name of the command that was selected in <paramref name="oldViewModel"/></param>
/// <returns>The new ViewModel based on <paramref name="importedModules"/> and <paramref name="commands"/>.</returns>
internal static AllModulesViewModel GetNewAllModulesViewModel(AllModulesViewModel oldViewModel, Dictionary<string, ShowCommandModuleInfo> importedModules, IEnumerable<ShowCommandCommandInfo> commands, string selectedModuleNeedingImportModule, string parentModuleNeedingImportModule, string commandNeedingImportModule)
{
string oldFilter = null;
if (oldViewModel.SelectedModule != null)
{
// this will allow the old view model to stop listening for events before we
// replace it with a new view model
oldViewModel.SelectedModule.SelectedCommand = null;
oldViewModel.SelectedModule = null;
oldFilter = oldViewModel.CommandNameFilter;
}
AllModulesViewModel returnValue = new AllModulesViewModel(importedModules, commands, oldViewModel.NoCommonParameter);
if (!String.IsNullOrEmpty(oldFilter))
{
returnValue.CommandNameFilter = oldFilter;
}
if (selectedModuleNeedingImportModule == null || parentModuleNeedingImportModule == null)
{
return returnValue;
}
ModuleViewModel moduleToSelect = returnValue.Modules.Find(
new Predicate<ModuleViewModel>(delegate(ModuleViewModel module)
{
return module.Name.Equals(selectedModuleNeedingImportModule, StringComparison.OrdinalIgnoreCase) ? true : false;
}));
if (moduleToSelect == null)
{
return returnValue;
}
returnValue.SelectedModule = moduleToSelect;
CommandViewModel commandToSelect = moduleToSelect.Commands.Find(
new Predicate<CommandViewModel>(delegate(CommandViewModel command)
{
return command.ModuleName.Equals(parentModuleNeedingImportModule, StringComparison.OrdinalIgnoreCase) &&
command.Name.Equals(commandNeedingImportModule, StringComparison.OrdinalIgnoreCase) ? true : false;
}));
if (commandToSelect == null)
{
return returnValue;
}
moduleToSelect.SelectedCommand = commandToSelect;
return returnValue;
}
/// <summary>
/// Gets an error message to be displayed when failed to import a module
/// </summary>
/// <param name="command">command belonging to the module to import</param>
/// <param name="module">module to import</param>
/// <param name="error">error importing the module</param>
/// <returns>an error message to be displayed when failed to import a module</returns>
internal static string GetImportModuleFailedMessage(string command, string module, string error)
{
return String.Format(
CultureInfo.CurrentUICulture,
ShowCommandResources.ImportModuleFailedFormat,
command,
module,
error);
}
/// <summary>
/// Single quotes <paramref name="str"/>
/// </summary>
/// <param name="str">string to quote</param>
/// <returns><paramref name="str"/> single quoted</returns>
internal static string SingleQuote(string str)
{
if (str == null)
{
str = String.Empty;
}
return "\'" + System.Management.Automation.Language.CodeGeneration.EscapeSingleQuotedStringContent(str) + "\'";
}
#endregion internal static methods called using reflection from show-command and directly from ISE
#region internal static methods used internally in this assembly
/// <summary>
/// Gets the host window, if it is present or null if it is not
/// </summary>
/// <param name="cmdlet">cmdlet calling this method</param>
/// <returns>the host window, if it is present or null if it is not</returns>
internal static Window GetHostWindow(PSCmdlet cmdlet)
{
PSPropertyInfo windowProperty = cmdlet.Host.PrivateData.Properties["Window"];
if (windowProperty == null)
{
return null;
}
try
{
return windowProperty.Value as Window;
}
catch (ExtendedTypeSystemException)
{
return null;
}
}
#endregion internal static methods used internally in this assembly
#region static private methods used only on this file
/// <summary>
/// Gets a property value using reflection
/// </summary>
/// <param name="type">type containing the property</param>
/// <param name="obj">object containing the property (null for a static property)</param>
/// <param name="propertyName">name of property to get</param>
/// <param name="bindingFlags">flags passed to reflection</param>
/// <returns>
/// property value or null if it was not able to retrieve it. This method is not suitable to return a property value that might be null.
/// </returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from a method called using reflection")]
private static object GetPropertyValue(Type type, object obj, string propertyName, BindingFlags bindingFlags)
{
PropertyInfo property = type.GetProperty(propertyName, bindingFlags);
if (property == null)
{
return null;
}
try
{
return property.GetValue(obj, new object[] { });
}
catch (ArgumentException)
{
return null;
}
catch (TargetException)
{
return null;
}
catch (TargetParameterCountException)
{
return null;
}
catch (MethodAccessException)
{
return null;
}
catch (TargetInvocationException)
{
return null;
}
}
/// <summary>
/// Sets a property value using reflection
/// </summary>
/// <param name="type">type containing the property</param>
/// <param name="obj">object containing the property (null for a static property)</param>
/// <param name="propertyName">name of property to set</param>
/// <param name="value">value to set the property with</param>
/// <param name="bindingFlags">flags passed to reflection</param>
/// <returns>true if it was able to set</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from a method called using reflection")]
private static bool SetPropertyValue(Type type, object obj, string propertyName, object value, BindingFlags bindingFlags)
{
PropertyInfo property = type.GetProperty(propertyName, bindingFlags);
if (property == null)
{
return false;
}
try
{
property.SetValue(obj, value, new object[] { });
}
catch (ArgumentException)
{
return false;
}
catch (TargetException)
{
return false;
}
catch (TargetParameterCountException)
{
return false;
}
catch (MethodAccessException)
{
return false;
}
catch (TargetInvocationException)
{
return false;
}
return true;
}
/// <summary>
/// Gets the suffix that adds imported modules to a command
/// </summary>
/// <returns>the suffix that adds imported modules to a command</returns>
private static string GetGetModuleSuffix()
{
return ",@(get-module)";
}
#endregion static private methods used only on this file
#region private methods called using reflection from show-command
/// <summary>
/// Gets the command to be run when calling show-command for a particular command
/// </summary>
/// <param name="commandName">the particular command we are running show-command on</param>
/// <param name="includeAliasAndModules">true if we want to include aliases and retrieve modules</param>
/// <returns>the command to be run when calling show-command for a particular command</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private static string GetShowCommandCommand(string commandName, bool includeAliasAndModules)
{
string quotedCommandName = ShowCommandHelper.SingleQuote(commandName);
return "@(get-command " + quotedCommandName + " " + ShowCommandHelper.CommandTypeSegment +
(includeAliasAndModules ? ",Alias" : String.Empty) + ")" +
(includeAliasAndModules ? ShowCommandHelper.GetGetModuleSuffix() : String.Empty);
}
/// <summary>
/// Gets a CommandViewModel of a CommandInfo
/// </summary>
/// <param name="command">command we want to get a CommandViewModel of</param>
/// <param name="noCommonParameter">true if we do not want common parameters</param>
/// <param name="importedModules">the loaded modules</param>
/// <param name="moduleQualify">True to qualify command with module name in GetScript</param>
/// <returns>a CommandViewModel of a CommandInfo</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private static object GetCommandViewModel(ShowCommandCommandInfo command, bool noCommonParameter, Dictionary<string, ShowCommandModuleInfo> importedModules, bool moduleQualify)
{
CommandViewModel returnValue = CommandViewModel.GetCommandViewModel(new ModuleViewModel(command.ModuleName, importedModules), command, noCommonParameter);
returnValue.ModuleQualifyCommandName = moduleQualify;
return returnValue;
}
/// <summary>
/// Dispatches a message to the window for it to activate
/// </summary>
/// <param name="window">window to be activated</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from ActivateWindow() which is called using reflection")]
private static void ActivateWindow(Window window)
{
window.Dispatcher.Invoke(
new SendOrPostCallback(
delegate(object ignored)
{
window.Activate();
}),
String.Empty);
}
/// <summary>
/// Sets a property in ISE that will allow the command to be run
/// </summary>
/// <param name="command">command to be run</param>
/// <returns>true if it was possible to set the pending ISE command</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private bool SetPendingISECommand(string command)
{
Diagnostics.Assert(this.hostWindow != null, "The caller checks that");
Type internalHostType = this.hostWindow.GetType().Assembly.GetType("Microsoft.Windows.PowerShell.Gui.Internal.PSGInternalHost");
if (internalHostType == null)
{
return false;
}
object current = GetPropertyValue(internalHostType, null, "Current", BindingFlags.Public | BindingFlags.Static);
if (current == null)
{
return false;
}
object powerShellTabs = GetPropertyValue(current.GetType(), current, "PowerShellTabs", BindingFlags.Public | BindingFlags.Instance);
if (powerShellTabs == null)
{
return false;
}
object selectedPowerShellTab = GetPropertyValue(powerShellTabs.GetType(), powerShellTabs, "SelectedPowerShellTab", BindingFlags.Public | BindingFlags.Instance);
if (selectedPowerShellTab == null)
{
return false;
}
return SetPropertyValue(selectedPowerShellTab.GetType(), selectedPowerShellTab, "PendingCommand", command, BindingFlags.NonPublic | BindingFlags.Instance);
}
/// <summary>
/// Shows the window listing cmdlets
/// </summary>
/// <param name="cmdlet">cmdlet calling this method</param>
/// <param name="importedModules">All loaded modules</param>
/// <param name="commands">commands to be listed</param>
/// <param name="noCommonParameter">true if we should not show common parameters</param>
/// <param name="windowWidth">window width</param>
/// <param name="windowHeight">window height</param>
/// <param name="passThrough">true if the GUI should mention ok instead of run</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private void ShowAllModulesWindow(PSCmdlet cmdlet, Dictionary<string, ShowCommandModuleInfo> importedModules, IEnumerable<ShowCommandCommandInfo> commands, bool noCommonParameter, double windowWidth, double windowHeight, bool passThrough)
{
this.methodThatReturnsDialog = new DispatcherOperationCallback(delegate(object ignored)
{
Diagnostics.Assert(commands.GetEnumerator().MoveNext(), "there is always at least one command");
ShowAllModulesWindow allModulesWindow = new ShowAllModulesWindow();
this.allModulesViewModel = new AllModulesViewModel(importedModules, commands, noCommonParameter);
this.SetupButtonEvents(allModulesWindow.Run, allModulesWindow.Copy, allModulesWindow.Cancel, passThrough);
this.SetupWindow(allModulesWindow);
this.SetupViewModel();
CommonHelper.SetStartingPositionAndSize(
allModulesWindow,
ShowCommandSettings.Default.ShowCommandsTop,
ShowCommandSettings.Default.ShowCommandsLeft,
windowWidth != 0.0 && windowWidth > allModulesWindow.MinWidth ? windowWidth : ShowCommandSettings.Default.ShowCommandsWidth,
windowHeight != 0.0 && windowHeight > allModulesWindow.MinHeight ? windowHeight : ShowCommandSettings.Default.ShowCommandsHeight,
allModulesWindow.Width,
allModulesWindow.Height,
ShowCommandSettings.Default.ShowCommandsWindowMaximized);
return allModulesWindow;
});
this.CallShowDialog(cmdlet);
}
/// <summary>
/// Calls ShowsDialog on methodThatReturnsDialog either in a separate thread or dispatched
/// to the hostWindow thread if there is a hostWindow
/// </summary>
/// <param name="cmdlet">cmdlet used to retrieve the host window</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from a method called using reflection")]
private void CallShowDialog(PSCmdlet cmdlet)
{
this.hostWindow = ShowCommandHelper.GetHostWindow(cmdlet);
if (this.hostWindow == null)
{
Thread guiThread = new Thread(new ThreadStart(this.PlainInvokeAndShowDialog));
guiThread.SetApartmentState(ApartmentState.STA);
guiThread.Start();
return;
}
this.hostWindow.Dispatcher.Invoke(
new SendOrPostCallback(
delegate(object ignored)
{
Window childWindow = (Window)this.methodThatReturnsDialog.Invoke(null);
childWindow.Owner = this.hostWindow;
childWindow.Show();
}),
String.Empty);
}
/// <summary>
/// Called from CallMethodThatShowsDialog as the thread start when there is no host window
/// </summary>
private void PlainInvokeAndShowDialog()
{
((Window)this.methodThatReturnsDialog.Invoke(null)).ShowDialog();
}
/// <summary>
/// Shows the window for the cmdlet
/// </summary>
/// <param name="cmdlet">cmdlet calling this method</param>
/// <param name="commandViewModelObj">command to show in the window</param>
/// <param name="windowWidth">window width</param>
/// <param name="windowHeight">window height</param>
/// <param name="passThrough">true if the GUI should mention ok instead of run</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private void ShowCommandWindow(PSCmdlet cmdlet, object commandViewModelObj, double windowWidth, double windowHeight, bool passThrough)
{
this.methodThatReturnsDialog = new DispatcherOperationCallback(delegate(object ignored)
{
Diagnostics.Assert(commandViewModelObj != null, "verified by caller");
this.commandViewModel = (CommandViewModel)commandViewModelObj;
ShowCommandWindow showCommandWindow = new ShowCommandWindow();
this.commandViewModel.HelpNeeded += new EventHandler<HelpNeededEventArgs>(this.CommandNeedsHelp);
showCommandWindow.DataContext = this.commandViewModel;
this.SetupButtonEvents(showCommandWindow.Run, showCommandWindow.Copy, showCommandWindow.Cancel, passThrough);
this.SetupWindow(showCommandWindow);
CommonHelper.SetStartingPositionAndSize(
showCommandWindow,
ShowCommandSettings.Default.ShowOneCommandTop,
ShowCommandSettings.Default.ShowOneCommandLeft,
windowWidth != 0.0 && windowWidth > showCommandWindow.MinWidth ? windowWidth : ShowCommandSettings.Default.ShowOneCommandWidth,
windowHeight != 0.0 && windowHeight > showCommandWindow.MinHeight ? windowHeight : ShowCommandSettings.Default.ShowOneCommandHeight,
showCommandWindow.Width,
showCommandWindow.Height,
ShowCommandSettings.Default.ShowOneCommandWindowMaximized);
return showCommandWindow;
});
this.CallShowDialog(cmdlet);
}
/// <summary>
/// Called when the module importation is done
/// </summary>
/// <param name="importedModules">all modules currently imported</param>
/// <param name="commands">commands to be displayed</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private void ImportModuleDone(Dictionary<string, ShowCommandModuleInfo> importedModules, IEnumerable<ShowCommandCommandInfo> commands)
{
this.allModulesViewModel.WaitMessageDisplayed = false;
if (this.window != null)
{
this.window.Dispatcher.Invoke(
new SendOrPostCallback(
delegate(object ignored)
{
this.allModulesViewModel = ShowCommandHelper.GetNewAllModulesViewModel(
this.allModulesViewModel,
importedModules,
commands,
this.selectedModuleNeedingImportModule,
this.parentModuleNeedingImportModule,
this.commandNeedingImportModule);
this.SetupViewModel();
}),
String.Empty);
}
}
/// <summary>
/// Called when the module importation has failed
/// </summary>
/// <param name="reason">reason why the module importation failed</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private void ImportModuleFailed(Exception reason)
{
this.allModulesViewModel.WaitMessageDisplayed = false;
if (this.window != null)
{
this.window.Dispatcher.Invoke(
new SendOrPostCallback(
delegate(object ignored)
{
string message = ShowCommandHelper.GetImportModuleFailedMessage(
this.commandNeedingImportModule,
this.parentModuleNeedingImportModule,
reason.Message);
MessageBox.Show(this.window, message, ShowCommandResources.ShowCommandError, MessageBoxButton.OK, MessageBoxImage.Error);
}),
String.Empty);
}
}
/// <summary>
/// Called when the results or get-help are ready in order to display the help window for a command
/// </summary>
/// <param name="getHelpResults">results of a get-help call</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private void DisplayHelp(Collection<PSObject> getHelpResults)
{
if (this.window != null && getHelpResults != null && getHelpResults.Count > 0)
{
this.window.Dispatcher.Invoke(
new SendOrPostCallback(
delegate(object ignored)
{
HelpWindow help = new HelpWindow(getHelpResults[0]);
help.Owner = this.window;
help.Show();
}),
String.Empty);
}
}
/// <summary>
/// Activates this.window
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private void ActivateWindow()
{
if (this.window != null)
{
ShowCommandHelper.ActivateWindow(this.window);
}
}
/// <summary>
/// returns the script to execute if dialog has not been canceled
/// </summary>
/// <returns>the script to execute if dialog has not been canceled</returns>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")]
private string GetScript()
{
if (this.dialogCanceled)
{
return null;
}
return this.InternalGetScript();
}
#endregion private methods called using reflection from show-command
#region instance private methods used only on this file
/// <summary>
/// Sets up window settings common between the two flavors of show-command
/// </summary>
/// <param name="commandWindow">the window being displayed</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from ShowAllModulesWindow and ShowCommandWindow which are called with reflection")]
private void SetupWindow(Window commandWindow)
{
this.window = commandWindow;
this.window.Closed += new EventHandler(this.Window_Closed);
this.window.Loaded += new RoutedEventHandler(this.Window_Loaded);
}
/// <summary>
/// Handles the SelectedCommandInSelectedModuleNeedsImportModule event
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event arguments</param>
private void CommandNeedsImportModule(object sender, ImportModuleEventArgs e)
{
this.commandNeedingImportModule = e.CommandName;
this.parentModuleNeedingImportModule = e.ParentModuleName;
this.selectedModuleNeedingImportModule = e.SelectedModuleName;
this.allModulesViewModel.WaitMessageDisplayed = true;
this.ImportModuleNeeded.Set();
}
/// <summary>
/// Handles the SelectedCommandInSelectedModuleNeedsHelp event
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event arguments</param>
private void CommandNeedsHelp(object sender, HelpNeededEventArgs e)
{
this.commandNeedingHelp = e.CommandName;
this.HelpNeeded.Set();
}
/// <summary>
/// Called when the window is closed to set this.dialogCanceled
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event arguments</param>
private void Window_Closed(object sender, EventArgs e)
{
if (this.hostWindow != null)
{
this.hostWindow.Focus();
}
this.window = null;
this.windowClosed.Set();
}
/// <summary>
/// Called when the window is loaded to set this.Window_Loaded
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event arguments</param>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.window.Loaded -= new RoutedEventHandler(this.Window_Loaded);
this.windowLoaded.Set();
}
/// <summary>
/// Sets up event listening on the buttons
/// </summary>
/// <param name="run">button to run command</param>
/// <param name="copy">button to copy command code</param>
/// <param name="cancel">button to close window</param>
/// <param name="passThrough">true to change the text of Run to OK</param>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called from methods called using reflection")]
private void SetupButtonEvents(Button run, Button copy, Button cancel, bool passThrough)
{
if (passThrough)
{
run.Content = ShowCommandResources.ActionButtons_Button_Ok;
}
run.Click += new RoutedEventHandler(this.Buttons_RunClick);
copy.Click += new RoutedEventHandler(this.Buttons_CopyClick);
cancel.Click += new RoutedEventHandler(this.Buttons_CancelClick);
}
/// <summary>
/// Sets up event listening for a new viewModel
/// </summary>
private void SetupViewModel()
{
this.allModulesViewModel.SelectedCommandInSelectedModuleNeedsHelp += new EventHandler<HelpNeededEventArgs>(this.CommandNeedsHelp);
this.allModulesViewModel.SelectedCommandInSelectedModuleNeedsImportModule += new EventHandler<ImportModuleEventArgs>(this.CommandNeedsImportModule);
this.window.DataContext = this.allModulesViewModel;
}
/// <summary>
/// Copies the script into the clipboard
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event arguments</param>
private void Buttons_CopyClick(object sender, RoutedEventArgs e)
{
string script = this.InternalGetScript();
if (script == null)
{
return;
}
this.window.Dispatcher.Invoke(new ThreadStart(delegate { ShowCommandHelper.SetClipboardText(script); }));
}
/// <summary>
/// Sets a successful dialog result and then closes the window
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event arguments</param>
private void Buttons_RunClick(object sender, RoutedEventArgs e)
{
this.dialogCanceled = false;
this.CloseWindow();
}
/// <summary>
/// Closes the window
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event arguments</param>
private void Buttons_CancelClick(object sender, RoutedEventArgs e)
{
this.CloseWindow();
}
/// <summary>
/// closes the window
/// </summary>
private void CloseWindow()
{
if (this.window == null)
{
return;
}
this.window.Dispatcher.Invoke(new ThreadStart(delegate
{
// This can happen if ISE is closed while show-command is up
if (this.window != null)
{
this.window.Close();
}
}));
}
/// <summary>
/// Showing a MessageBox when user type a invalidate command name.
/// </summary>
/// <param name="errorString">error message</param>
private void ShowErrorString(string errorString)
{
if (errorString != null && errorString.Trim().Length > 0)
{
MessageBox.Show(
String.Format(
CultureInfo.CurrentUICulture,
ShowCommandResources.EndProcessingErrorMessage,
errorString),
"Show-Command",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
/// <summary>
/// returns the script to execute
/// </summary>
/// <returns>the script to execute</returns>
private string InternalGetScript()
{
if (this.allModulesViewModel != null)
{
return this.allModulesViewModel.GetScript();
}
if (this.commandViewModel == null)
{
return null;
}
return this.commandViewModel.GetScript();
}
/// <summary>
/// Implements IDisposable logic
/// </summary>
/// <param name="isDisposing">true if being called from Dispose</param>
private void Dispose(bool isDisposing)
{
if (isDisposing)
{
this.windowClosed.Dispose();
this.helpNeeded.Dispose();
this.windowLoaded.Dispose();
this.importModuleNeeded.Dispose();
}
}
#endregion instance private methods used only on this file
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
namespace FileHelpers.Tests.CommonTests
{
[TestFixture]
public class TransformEngine
{
private readonly string fileOut = TestCommon.GetTempFile("transformout.txt");
[Test]
public void CsvToFixedLength()
{
var link = new FileTransformEngine<FromClass, ToClass>();
link.TransformFile(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void CsvToFixedLengthCommon()
{
CommonEngine.TransformFile<FromClass, ToClass>(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void CsvToFixedLengthCommonAsync()
{
CommonEngine.TransformFileFast<FromClass, ToClass>(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void CsvToFixedLength2()
{
var link = new FileTransformEngine<FromClass, ToClass>();
link.TransformFile(FileTest.Good.Transform2.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(@"c:\Prueba1\anda ? ", res[0].CompanyName);
Assert.AreEqual("\"D:\\Glossaries\\O12\" ", res[1].CompanyName);
Assert.AreEqual(@"\\s\\ ", res[2].CompanyName);
}
[Test]
public void TransformRecords()
{
var engine = new FileTransformEngine<FromClass, ToClass>();
ToClass[] res = engine.ReadAndTransformRecords(FileTest.Good.Transform2.Path);
Assert.AreEqual(@"c:\Prueba1\anda ?", res[0].CompanyName);
Assert.AreEqual("\"D:\\Glossaries\\O12\"", res[1].CompanyName);
Assert.AreEqual(@"\\s\\", res[2].CompanyName);
}
[Test]
public void CsvToDelimited()
{
var link = new FileTransformEngine<FromClass, ToClass2>();
link.TransformFile(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void CsvToDelimitedCommon()
{
CommonEngine.TransformFile<FromClass, ToClass2>(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void CsvToDelimitedCommonAsync()
{
CommonEngine.TransformFileFast<FromClass, ToClass2>(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void CsvToDelimited2()
{
var link = new FileTransformEngine<FromClass, ToClass2>();
link.TransformFile(FileTest.Good.Transform2.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(@"c:\Prueba1\anda ?", res[0].CompanyName);
Assert.AreEqual("\"D:\\Glossaries\\O12\"", res[1].CompanyName);
Assert.AreEqual(@"\\s\\", res[2].CompanyName);
}
[Test]
public void AsyncCsvToFixedLength()
{
var link = new FileTransformEngine<FromClass, ToClass>();
link.TransformFileFast(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void AsyncCsvToFixedLength2()
{
var link = new FileTransformEngine<FromClass, ToClass>();
link.TransformFileFast(FileTest.Good.Transform2.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(@"c:\Prueba1\anda ? ", res[0].CompanyName);
Assert.AreEqual("\"D:\\Glossaries\\O12\" ", res[1].CompanyName);
Assert.AreEqual(@"\\s\\ ", res[2].CompanyName);
}
[Test]
public void AsyncCsvToDelimited()
{
var link = new FileTransformEngine<FromClass, ToClass2>();
link.TransformFileFast(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void AsyncCsvToDelimited2()
{
var link = new FileTransformEngine<FromClass, ToClass2>();
link.TransformFileFast(FileTest.Good.Transform2.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(@"c:\Prueba1\anda ?", res[0].CompanyName);
Assert.AreEqual("\"D:\\Glossaries\\O12\"", res[1].CompanyName);
Assert.AreEqual(@"\\s\\", res[2].CompanyName);
}
[DelimitedRecord(",")]
private class FromClass
: ITransformable<ToClass>,
ITransformable<ToClass2>
{
public string CustomerId;
public string CompanyName;
public string CustomerName;
ToClass ITransformable<ToClass>.TransformTo()
{
var res = new ToClass();
res.CustomerId = CustomerId;
res.CompanyName = CompanyName;
res.CustomerName = CustomerName;
return res;
}
ToClass2 ITransformable<ToClass2>.TransformTo()
{
var res = new ToClass2();
res.CustomerId = CustomerId;
res.CompanyName = CompanyName;
res.CustomerName = CustomerName;
return res;
}
}
[DelimitedRecord("|")]
private class ToClass2
{
public string CustomerId;
public string CompanyName;
public string CustomerName;
}
[FixedLengthRecord]
private class ToClass
{
[FieldFixedLength(10)]
public string CustomerId;
[FieldFixedLength(50)]
public string CompanyName;
[FieldFixedLength(60)]
public string CustomerName;
}
}
}
| |
// <copyright file="DiscreteUniformTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2014 Math.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>
namespace MathNet.Numerics.UnitTests.DistributionTests.Discrete
{
using System;
using System.Linq;
using Distributions;
using NUnit.Framework;
/// <summary>
/// Discrete uniform tests.
/// </summary>
[TestFixture, Category("Distributions")]
public class DiscreteUniformTests
{
/// <summary>
/// Can create discrete uniform.
/// </summary>
/// <param name="l">Lower bound.</param>
/// <param name="u">Upper bound.</param>
[TestCase(-10, 10)]
[TestCase(0, 4)]
[TestCase(10, 20)]
[TestCase(20, 20)]
public void CanCreateDiscreteUniform(int l, int u)
{
var du = new DiscreteUniform(l, u);
Assert.AreEqual(l, du.LowerBound);
Assert.AreEqual(u, du.UpperBound);
}
/// <summary>
/// Discrete Uniform create fails with bad parameters.
/// </summary>
/// <param name="l">Lower bound.</param>
/// <param name="u">Upper bound.</param>
[TestCase(-1, -2)]
[TestCase(6, 5)]
public void DiscreteUniformCreateFailsWithBadParameters(int l, int u)
{
Assert.That(() => new DiscreteUniform(l, u), Throws.ArgumentException);
}
/// <summary>
/// Validate ToString.
/// </summary>
[Test]
public void ValidateToString()
{
var b = new DiscreteUniform(0, 10);
Assert.AreEqual("DiscreteUniform(Lower = 0, Upper = 10)", b.ToString());
}
/// <summary>
/// Validate entropy.
/// </summary>
/// <param name="l">Lower bound.</param>
/// <param name="u">Upper bound.</param>
/// <param name="e">Expected value.</param>
[TestCase(-10, 10, 3.0445224377234229965005979803657054342845752874046093)]
[TestCase(0, 4, 1.6094379124341003746007593332261876395256013542685181)]
[TestCase(10, 20, 2.3978952727983705440619435779651292998217068539374197)]
[TestCase(20, 20, 0.0)]
public void ValidateEntropy(int l, int u, double e)
{
var du = new DiscreteUniform(l, u);
AssertHelpers.AlmostEqualRelative(e, du.Entropy, 14);
}
/// <summary>
/// Validate skewness.
/// </summary>
/// <param name="l">Lower bound.</param>
/// <param name="u">Upper bound.</param>
[TestCase(-10, 10)]
[TestCase(0, 4)]
[TestCase(10, 20)]
[TestCase(20, 20)]
public void ValidateSkewness(int l, int u)
{
var du = new DiscreteUniform(l, u);
Assert.AreEqual(0.0, du.Skewness);
}
/// <summary>
/// Validate mode.
/// </summary>
/// <param name="l">Lower bound.</param>
/// <param name="u">Upper bound.</param>
/// <param name="m">Expected value.</param>
[TestCase(-10, 10, 0)]
[TestCase(0, 4, 2)]
[TestCase(10, 20, 15)]
[TestCase(20, 20, 20)]
public void ValidateMode(int l, int u, int m)
{
var du = new DiscreteUniform(l, u);
Assert.AreEqual(m, du.Mode);
}
/// <summary>
/// Validate median.
/// </summary>
/// <param name="l">Lower bound.</param>
/// <param name="u">Upper bound.</param>
/// <param name="m">Expected value.</param>
[TestCase(-10, 10, 0)]
[TestCase(0, 4, 2)]
[TestCase(10, 20, 15)]
[TestCase(20, 20, 20)]
public void ValidateMedian(int l, int u, int m)
{
var du = new DiscreteUniform(l, u);
Assert.AreEqual(m, du.Median);
}
/// <summary>
/// Validate mean.
/// </summary>
/// <param name="l">Lower bound.</param>
/// <param name="u">Upper bound.</param>
/// <param name="m">Expected value.</param>
[TestCase(-10, 10, 0)]
[TestCase(0, 4, 2)]
[TestCase(10, 20, 15)]
[TestCase(20, 20, 20)]
public void ValidateMean(int l, int u, int m)
{
var du = new DiscreteUniform(l, u);
Assert.AreEqual(m, du.Mean);
}
/// <summary>
/// Validate minimum.
/// </summary>
[Test]
public void ValidateMinimum()
{
var b = new DiscreteUniform(-10, 10);
Assert.AreEqual(-10, b.Minimum);
}
/// <summary>
/// Validate maximum.
/// </summary>
[Test]
public void ValidateMaximum()
{
var b = new DiscreteUniform(-10, 10);
Assert.AreEqual(10, b.Maximum);
}
/// <summary>
/// Validate probability.
/// </summary>
/// <param name="l">Lower bound.</param>
/// <param name="u">Upper bound.</param>
/// <param name="x">Input X value.</param>
/// <param name="p">Expected value.</param>
[TestCase(-10, 10, -5, 1 / 21.0)]
[TestCase(-10, 10, 1, 1 / 21.0)]
[TestCase(-10, 10, 10, 1 / 21.0)]
[TestCase(-10, -10, 0, 0.0)]
[TestCase(-10, -10, -10, 1.0)]
public void ValidateProbability(int l, int u, int x, double p)
{
var b = new DiscreteUniform(l, u);
Assert.AreEqual(p, b.Probability(x));
}
/// <summary>
/// Validate porbability log.
/// </summary>
/// <param name="l">Lower bound.</param>
/// <param name="u">Upper bound.</param>
/// <param name="x">Input X value.</param>
/// <param name="dln">Expected value.</param>
[TestCase(-10, 10, -5, -3.0445224377234229965005979803657054342845752874046093)]
[TestCase(-10, 10, 1, -3.0445224377234229965005979803657054342845752874046093)]
[TestCase(-10, 10, 10, -3.0445224377234229965005979803657054342845752874046093)]
[TestCase(-10, -10, 0, Double.NegativeInfinity)]
[TestCase(-10, -10, -10, 0.0)]
public void ValidateProbabilityLn(int l, int u, int x, double dln)
{
var b = new DiscreteUniform(l, u);
Assert.AreEqual(dln, b.ProbabilityLn(x));
}
/// <summary>
/// Can sample static.
/// </summary>
[Test]
public void CanSampleStatic()
{
DiscreteUniform.Sample(new Random(0), 0, 10);
}
/// <summary>
/// Can sample sequence static.
/// </summary>
[Test]
public void CanSampleSequenceStatic()
{
var ied = DiscreteUniform.Samples(new Random(0), 0, 10);
GC.KeepAlive(ied.Take(5).ToArray());
}
/// <summary>
/// Fail sample static with bad parameters.
/// </summary>
[Test]
public void FailSampleStatic()
{
Assert.That(() => DiscreteUniform.Sample(new Random(0), 20, 10), Throws.ArgumentException);
}
/// <summary>
/// Fail sample sequence static with bad parameters.
/// </summary>
[Test]
public void FailSampleSequenceStatic()
{
Assert.That(() => DiscreteUniform.Samples(new Random(0), 20, 10).First(), Throws.ArgumentException);
}
/// <summary>
/// Can sample.
/// </summary>
[Test]
public void CanSample()
{
var n = new DiscreteUniform(0, 10);
n.Sample();
}
/// <summary>
/// Can sample sequence.
/// </summary>
[Test]
public void CanSampleSequence()
{
var n = new DiscreteUniform(0, 10);
var ied = n.Samples();
GC.KeepAlive(ied.Take(5).ToArray());
}
/// <summary>
/// Validate cumulative distribution.
/// </summary>
/// <param name="l">Lower bound.</param>
/// <param name="u">Upper bound.</param>
/// <param name="x">Input X value.</param>
/// <param name="cdf">Expected value.</param>
[TestCase(-10, 10, -5, 6.0 / 21.0)]
[TestCase(-10, 10, 1, 12.0 / 21.0)]
[TestCase(-10, 10, 10, 1.0)]
[TestCase(-10, -10, 0, 1.0)]
[TestCase(-10, -10, -10, 1.0)]
[TestCase(-10, -10, -11, 0.0)]
public void ValidateCumulativeDistribution(int l, int u, double x, double cdf)
{
var b = new DiscreteUniform(l, u);
Assert.AreEqual(cdf, b.CumulativeDistribution(x));
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.PointOfService;
using Windows.Graphics.Display;
using Windows.Media.Capture;
using Windows.System.Display;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
public sealed partial class Scenario5_DisplayingBarcodePreview : Page, INotifyPropertyChanged
{
public bool IsScannerClaimed { get; set; } = false;
public bool IsPreviewing { get; set; } = false;
public bool ScannerSupportsPreview { get; set; } = false;
public bool SoftwareTriggerStarted { get; set; } = false;
MainPage rootPage = MainPage.Current;
ObservableCollection<BarcodeScannerInfo> barcodeScanners = new ObservableCollection<BarcodeScannerInfo>();
BarcodeScanner selectedScanner = null;
ClaimedBarcodeScanner claimedScanner = null;
DeviceWatcher watcher;
static readonly Guid rotationGuid = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1");
DisplayRequest displayRequest = new DisplayRequest();
MediaCapture mediaCapture;
bool isSelectionChanging = false;
string pendingSelectionDeviceId = null;
bool isStopPending = false;
public event PropertyChangedEventHandler PropertyChanged;
public Scenario5_DisplayingBarcodePreview()
{
this.InitializeComponent();
ScannerListSource.Source = barcodeScanners;
watcher = DeviceInformation.CreateWatcher(BarcodeScanner.GetDeviceSelector());
watcher.Added += Watcher_Added;
watcher.Removed += Watcher_Removed;
watcher.Updated += Watcher_Updated;
watcher.Start();
DataContext = this;
}
private async void Watcher_Added(DeviceWatcher sender, DeviceInformation args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
barcodeScanners.Add(new BarcodeScannerInfo(args.Name, args.Id));
// Select the first scanner by default.
if (barcodeScanners.Count == 1)
{
ScannerListBox.SelectedIndex = 0;
}
});
}
private void Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
{
// We don't do anything here, but this event needs to be handled to enable realtime updates.
// See https://aka.ms/devicewatcher_added.
}
private void Watcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
// We don't do anything here, but this event needs to be handled to enable realtime updates.
//See https://aka.ms/devicewatcher_added.
}
protected async override void OnNavigatedFrom(NavigationEventArgs e)
{
watcher.Stop();
if (isSelectionChanging)
{
// If selection is changing, then let it know to stop media capture
// when it's done.
isStopPending = true;
}
else
{
// If selection is not changing, then it's safe to stop immediately.
await CloseScannerResourcesAsync();
}
}
/// <summary>
/// Starts previewing the selected scanner's video feed and prevents the display from going to sleep.
/// </summary>
private async Task StartMediaCaptureAsync(string videoDeviceId)
{
mediaCapture = new MediaCapture();
// Register for a notification when something goes wrong
mediaCapture.Failed += MediaCapture_Failed;
var settings = new MediaCaptureInitializationSettings
{
VideoDeviceId = videoDeviceId,
StreamingCaptureMode = StreamingCaptureMode.Video,
SharingMode = MediaCaptureSharingMode.SharedReadOnly,
};
// Initialize MediaCapture
bool captureInitialized = false;
try
{
await mediaCapture.InitializeAsync(settings);
captureInitialized = true;
}
catch (UnauthorizedAccessException)
{
rootPage.NotifyUser("The app was denied access to the camera", NotifyType.ErrorMessage);
}
catch (Exception e)
{
rootPage.NotifyUser("Failed to initialize the camera: " + e.Message, NotifyType.ErrorMessage);
}
if (captureInitialized)
{
// Prevent the device from sleeping while the preview is running.
displayRequest.RequestActive();
PreviewControl.Source = mediaCapture;
await mediaCapture.StartPreviewAsync();
await SetPreviewRotationAsync(DisplayInformation.GetForCurrentView().CurrentOrientation);
IsPreviewing = true;
RaisePropertyChanged(nameof(IsPreviewing));
}
else
{
mediaCapture.Dispose();
mediaCapture = null;
}
}
/// <summary>
/// Close the scanners and stop the preview.
/// </summary>
private async Task CloseScannerResourcesAsync()
{
claimedScanner?.Dispose();
claimedScanner = null;
selectedScanner?.Dispose();
selectedScanner = null;
SoftwareTriggerStarted = false;
RaisePropertyChanged(nameof(SoftwareTriggerStarted));
if (IsPreviewing)
{
if (mediaCapture != null)
{
await mediaCapture.StopPreviewAsync();
mediaCapture.Dispose();
mediaCapture = null;
}
// Allow the display to go to sleep.
displayRequest.RequestRelease();
IsPreviewing = false;
RaisePropertyChanged(nameof(IsPreviewing));
}
}
/// <summary>
/// Set preview rotation and mirroring state to adjust for the orientation of the camera, and for embedded cameras, the rotation of the device.
/// </summary>
/// <param name="message"></param>
/// <param name="type"></param>
private async Task SetPreviewRotationAsync(DisplayOrientations displayOrientation)
{
bool isExternalCamera;
bool isPreviewMirrored;
// Figure out where the camera is located to account for mirroring and later adjust rotation accordingly.
DeviceInformation cameraInformation = await DeviceInformation.CreateFromIdAsync(selectedScanner.VideoDeviceId);
if ((cameraInformation.EnclosureLocation == null) || (cameraInformation.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown))
{
isExternalCamera = true;
isPreviewMirrored = false;
}
else
{
isExternalCamera = false;
isPreviewMirrored = (cameraInformation.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
}
PreviewControl.FlowDirection = isPreviewMirrored ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
if (!isExternalCamera)
{
// Calculate which way and how far to rotate the preview.
int rotationDegrees = 0;
switch (displayOrientation)
{
case DisplayOrientations.Portrait:
rotationDegrees = 90;
break;
case DisplayOrientations.LandscapeFlipped:
rotationDegrees = 180;
break;
case DisplayOrientations.PortraitFlipped:
rotationDegrees = 270;
break;
case DisplayOrientations.Landscape:
default:
rotationDegrees = 0;
break;
}
// The rotation direction needs to be inverted if the preview is being mirrored.
if (isPreviewMirrored)
{
rotationDegrees = (360 - rotationDegrees) % 360;
}
// Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames.
var streamProperties = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
streamProperties.Properties[rotationGuid] = rotationDegrees;
await mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, streamProperties, null);
}
}
/// <summary>
/// Media capture failed, potentially due to the camera being unplugged.
/// </summary>
/// <param name="sender"></param>
/// <param name="errorEventArgs"></param>
private void MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
{
rootPage.NotifyUser("Media capture failed. Make sure the camera is still connected.", NotifyType.ErrorMessage);
}
/// <summary>
/// Event Handler for Show Preview Button Click.
/// Displays the preview window for the selected barcode scanner.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void ShowPreviewButton_Click(object sender, RoutedEventArgs e)
{
await claimedScanner?.ShowVideoPreviewAsync();
}
/// <summary>
/// Event Handler for Hide Preview Button Click.
/// Hides the preview window for the selected barcode scanner.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HidePreviewButton_Click(object sender, RoutedEventArgs e)
{
claimedScanner?.HideVideoPreview();
}
/// <summary>
/// Event Handler for Start Software Trigger Button Click.
/// Starts scanning.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void StartSoftwareTriggerButton_Click(object sender, RoutedEventArgs e)
{
if (claimedScanner != null)
{
await claimedScanner.StartSoftwareTriggerAsync();
SoftwareTriggerStarted = true;
RaisePropertyChanged(nameof(SoftwareTriggerStarted));
}
}
/// <summary>
/// Event Handler for Stop Software Trigger Button Click.
/// Stops scanning.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void StopSoftwareTriggerButton_Click(object sender, RoutedEventArgs e)
{
if (claimedScanner != null)
{
await claimedScanner.StopSoftwareTriggerAsync();
SoftwareTriggerStarted = false;
RaisePropertyChanged(nameof(SoftwareTriggerStarted));
}
}
/// <summary>
/// Event Handler for Flip Preview Button Click.
/// Stops scanning.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FlipPreview_Click(object sender, RoutedEventArgs e)
{
if (PreviewControl.FlowDirection == FlowDirection.LeftToRight)
{
PreviewControl.FlowDirection = FlowDirection.RightToLeft;
}
else
{
PreviewControl.FlowDirection = FlowDirection.LeftToRight;
}
}
/// <summary>
/// Event handler for scanner listbox selection changed
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private async void ScannerSelection_Changed(object sender, SelectionChangedEventArgs args)
{
var selectedScannerInfo = (BarcodeScannerInfo)args.AddedItems[0];
var deviceId = selectedScannerInfo.DeviceId;
if (isSelectionChanging)
{
pendingSelectionDeviceId = deviceId;
return;
}
do
{
await SelectScannerAsync(deviceId);
// Stop takes precedence over updating the selection.
if (isStopPending)
{
await CloseScannerResourcesAsync();
break;
}
deviceId = pendingSelectionDeviceId;
pendingSelectionDeviceId = null;
} while (!String.IsNullOrEmpty(deviceId));
}
/// <summary>
/// Select the scanner specified by its device ID.
/// </summary>
/// <param name="scannerDeviceId"></param>
private async Task SelectScannerAsync(string scannerDeviceId)
{
isSelectionChanging = true;
await CloseScannerResourcesAsync();
selectedScanner = await BarcodeScanner.FromIdAsync(scannerDeviceId);
if (selectedScanner != null)
{
claimedScanner = await selectedScanner.ClaimScannerAsync();
if (claimedScanner != null)
{
await claimedScanner.EnableAsync();
claimedScanner.Closed += ClaimedScanner_Closed;
ScannerSupportsPreview = !String.IsNullOrEmpty(selectedScanner.VideoDeviceId);
RaisePropertyChanged(nameof(ScannerSupportsPreview));
claimedScanner.DataReceived += ClaimedScanner_DataReceived;
if (ScannerSupportsPreview)
{
await StartMediaCaptureAsync(selectedScanner.VideoDeviceId);
}
}
else
{
rootPage.NotifyUser("Failed to claim the selected barcode scanner", NotifyType.ErrorMessage);
}
}
else
{
rootPage.NotifyUser("Failed to create a barcode scanner object", NotifyType.ErrorMessage);
}
IsScannerClaimed = claimedScanner != null;
RaisePropertyChanged(nameof(IsScannerClaimed));
isSelectionChanging = false;
}
/// <summary>
/// Closed notification was received from the selected scanner.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void ClaimedScanner_Closed(ClaimedBarcodeScanner sender, ClaimedBarcodeScannerClosedEventArgs args)
{
// Resources associated to the claimed barcode scanner can be cleaned up here
}
/// <summary>
/// Scan data was received from the selected scanner.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private async void ClaimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
ScenarioOutputScanDataLabel.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
ScenarioOutputScanData.Text = DataHelpers.GetDataString(args.Report.ScanData);
ScenarioOutputScanDataType.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType);
});
}
/// <summary>
/// Update listeners that a property was changed so that data bindings can be updated.
/// </summary>
/// <param name="propertyName"></param>
public void RaisePropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| |
/************************************************************************************
Filename : OVRLipSyncDebugConsole.cs
Content : Write to a text string, used by UI.Text
Created : May 22, 2015
Copyright : Copyright 2015 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class OVRLipSyncDebugConsole : MonoBehaviour
{
public ArrayList messages = new ArrayList();
public int maxMessages = 15; // The max number of messages displayed
public Text textMsg; // text string to display
// Our instance to allow this script to be called without a direct connection.
private static OVRLipSyncDebugConsole s_Instance = null;
// Clear timeout
private bool clearTimeoutOn = false;
private float clearTimeout = 0.0f;
/// <summary>
/// Gets the instance.
/// </summary>
/// <value>The instance.</value>
public static OVRLipSyncDebugConsole instance
{
get
{
if (s_Instance == null)
{
s_Instance = FindObjectOfType(typeof(OVRLipSyncDebugConsole)) as OVRLipSyncDebugConsole;
if (s_Instance == null)
{
GameObject console = new GameObject();
console.AddComponent<OVRLipSyncDebugConsole>();
console.name = "OVRLipSyncDebugConsole";
s_Instance = FindObjectOfType(typeof(OVRLipSyncDebugConsole)) as OVRLipSyncDebugConsole;
}
}
return s_Instance;
}
}
/// <summary>
/// Awake this instance.
/// </summary>
void Awake()
{
s_Instance = this;
Init();
}
/// <summary>
/// Update this instance.
/// </summary>
void Update()
{
if(clearTimeoutOn == true)
{
clearTimeout -= Time.deltaTime;
if(clearTimeout < 0.0f)
{
Clear();
clearTimeout = 0.0f;
clearTimeoutOn = false;
}
}
}
/// <summary>
/// Init this instance.
/// </summary>
public void Init()
{
if(textMsg == null)
{
Debug.LogWarning("DebugConsole Init WARNING::UI text not set. Will not be able to display anything.");
}
Clear();
}
//+++++++++ INTERFACE FUNCTIONS ++++++++++++++++++++++++++++++++
/// <summary>
/// Log the specified message.
/// </summary>
/// <param name="message">Message.</param>
public static void Log(string message)
{
OVRLipSyncDebugConsole.instance.AddMessage(message, Color.white);
}
/// <summary>
/// Log the specified message and color.
/// </summary>
/// <param name="message">Message.</param>
/// <param name="color">Color.</param>
public static void Log(string message, Color color)
{
OVRLipSyncDebugConsole.instance.AddMessage(message, color);
}
/// <summary>
/// Clear this instance.
/// </summary>
public static void Clear()
{
OVRLipSyncDebugConsole.instance.ClearMessages();
}
/// <summary>
/// Calls clear after a certain time.
/// </summary>
/// <param name="timeToClear">Time to clear.</param>
public static void ClearTimeout(float timeToClear)
{
OVRLipSyncDebugConsole.instance.SetClearTimeout(timeToClear);
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/// <summary>
/// Adds the message.
/// </summary>
/// <param name="message">Message.</param>
/// <param name="color">Color.</param>
public void AddMessage(string message, Color color)
{
messages.Add(message);
if(textMsg != null)
textMsg.color = color;
Display();
}
/// <summary>
/// Clears the messages.
/// </summary>
public void ClearMessages()
{
messages.Clear();
Display();
}
/// <summary>
/// Sets the clear timeout.
/// </summary>
/// <param name="timeout">Timeout.</param>
public void SetClearTimeout(float timeout)
{
clearTimeout = timeout;
clearTimeoutOn = true;
}
/// <summary>
// Prunes the array to fit within the maxMessages limit
/// </summary>
void Prune()
{
int diff;
if (messages.Count > maxMessages)
{
if (messages.Count <= 0)
{
diff = 0;
}
else
{
diff = messages.Count - maxMessages;
}
messages.RemoveRange(0, (int)diff);
}
}
/// <summary>
/// Display this instance.
/// </summary>
void Display()
{
if (messages.Count > maxMessages)
{
Prune();
}
if(textMsg != null)
{
textMsg.text = ""; // Clear text out
int x = 0;
while (x < messages.Count)
{
textMsg.text += (string)messages[x];
textMsg.text +='\n';
x += 1;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Xml;
using System.Xml.Schema;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Security;
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces);
public delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract);
public delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract);
public sealed class XmlFormatReaderGenerator
#else
internal delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces);
internal delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract);
internal delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract);
internal sealed class XmlFormatReaderGenerator
#endif
{
private CriticalHelper _helper;
public XmlFormatReaderGenerator()
{
_helper = new CriticalHelper();
}
public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
{
return _helper.GenerateClassReader(classContract);
}
public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract)
{
return _helper.GenerateCollectionReader(collectionContract);
}
public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract)
{
return _helper.GenerateGetOnlyCollectionReader(collectionContract);
}
/// <SecurityNote>
/// Review - handles all aspects of IL generation including initializing the DynamicMethod.
/// changes to how IL generated could affect how data is deserialized and what gets access to data,
/// therefore we mark it for review so that changes to generation logic are reviewed.
/// </SecurityNote>
private class CriticalHelper
{
#if !NET_NATIVE
private CodeGenerator _ilg;
private LocalBuilder _objectLocal;
private Type _objectType;
private ArgBuilder _xmlReaderArg;
private ArgBuilder _contextArg;
private ArgBuilder _memberNamesArg;
private ArgBuilder _memberNamespacesArg;
private ArgBuilder _collectionContractArg;
#endif
public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
{
if (DataContractSerializer.Option == SerializationOption.ReflectionOnly)
{
return new ReflectionXmlClassReader(classContract).ReflectionReadClass;
}
#if NET_NATIVE
else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup)
{
return new ReflectionXmlClassReader(classContract).ReflectionReadClass;
}
#endif
else
{
#if NET_NATIVE
throw new InvalidOperationException("Cannot generate class reader");
#else
_ilg = new CodeGenerator();
bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null);
try
{
_ilg.BeginMethod("Read" + classContract.StableName.Name + "FromXml", Globals.TypeOfXmlFormatClassReaderDelegate, memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForRead(securityException);
}
else
{
throw;
}
}
InitArgs();
CreateObject(classContract);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
InvokeOnDeserializing(classContract);
LocalBuilder objectId = null;
if (classContract.IsISerializable)
{
ReadISerializable(classContract);
}
else
{
ReadClass(classContract);
}
if (Globals.TypeOfIDeserializationCallback.IsAssignableFrom(classContract.UnderlyingType))
{
_ilg.Call(_objectLocal, XmlFormatGeneratorStatics.OnDeserializationMethod, null);
}
InvokeOnDeserialized(classContract);
if (objectId == null)
{
_ilg.Load(_objectLocal);
// Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization.
// DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation
// on DateTimeOffset; which does not work in partial trust.
if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter)
{
_ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfDateTimeOffsetAdapter);
_ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetMethod);
_ilg.ConvertValue(Globals.TypeOfDateTimeOffset, _ilg.CurrentMethod.ReturnType);
}
//Copy the KeyValuePairAdapter<K,T> to a KeyValuePair<K,T>.
else if (classContract.IsKeyValuePairAdapter)
{
_ilg.Call(classContract.GetKeyValuePairMethodInfo);
_ilg.ConvertValue(Globals.TypeOfKeyValuePair.MakeGenericType(classContract.KeyValuePairGenericArguments), _ilg.CurrentMethod.ReturnType);
}
else
{
_ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType);
}
}
return (XmlFormatClassReaderDelegate)_ilg.EndMethod();
#endif
}
}
public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract)
{
if (DataContractSerializer.Option == SerializationOption.ReflectionOnly)
{
return new ReflectionXmlCollectionReader().ReflectionReadCollection;
}
#if NET_NATIVE
else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup)
{
return new ReflectionXmlCollectionReader().ReflectionReadCollection;
}
#endif
else
{
#if NET_NATIVE
throw new InvalidOperationException("Cannot generate class reader");
#else
_ilg = GenerateCollectionReaderHelper(collectionContract, false /*isGetOnlyCollection*/);
ReadCollection(collectionContract);
_ilg.Load(_objectLocal);
_ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType);
return (XmlFormatCollectionReaderDelegate)_ilg.EndMethod();
#endif
}
}
public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract)
{
if (DataContractSerializer.Option == SerializationOption.ReflectionOnly)
{
return new ReflectionXmlCollectionReader().ReflectionReadGetOnlyCollection;
}
#if NET_NATIVE
else if (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup)
{
return new ReflectionXmlCollectionReader().ReflectionReadGetOnlyCollection;
}
#endif
else
{
#if NET_NATIVE
throw new InvalidOperationException("Cannot generate class reader");
#else
_ilg = GenerateCollectionReaderHelper(collectionContract, true /*isGetOnlyCollection*/);
ReadGetOnlyCollection(collectionContract);
return (XmlFormatGetOnlyCollectionReaderDelegate)_ilg.EndMethod();
#endif
}
}
#if !NET_NATIVE
private CodeGenerator GenerateCollectionReaderHelper(CollectionDataContract collectionContract, bool isGetOnlyCollection)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = collectionContract.RequiresMemberAccessForRead(null);
try
{
if (isGetOnlyCollection)
{
_ilg.BeginMethod("Read" + collectionContract.StableName.Name + "FromXml" + "IsGetOnly", Globals.TypeOfXmlFormatGetOnlyCollectionReaderDelegate, memberAccessFlag);
}
else
{
_ilg.BeginMethod("Read" + collectionContract.StableName.Name + "FromXml" + string.Empty, Globals.TypeOfXmlFormatCollectionReaderDelegate, memberAccessFlag);
}
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
collectionContract.RequiresMemberAccessForRead(securityException);
}
else
{
throw;
}
}
InitArgs();
_collectionContractArg = _ilg.GetArg(4);
return _ilg;
}
private void InitArgs()
{
_xmlReaderArg = _ilg.GetArg(0);
_contextArg = _ilg.GetArg(1);
_memberNamesArg = _ilg.GetArg(2);
_memberNamespacesArg = _ilg.GetArg(3);
}
private void CreateObject(ClassDataContract classContract)
{
Type type = _objectType = classContract.UnderlyingType;
if (type.IsValueType && !classContract.IsNonAttributedType)
type = Globals.TypeOfValueType;
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
if (classContract.UnderlyingType == Globals.TypeOfDBNull)
{
_ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value"));
_ilg.Stloc(_objectLocal);
}
else if (classContract.IsNonAttributedType)
{
if (type.IsValueType)
{
_ilg.Ldloca(_objectLocal);
_ilg.InitObj(type);
}
else
{
_ilg.New(classContract.GetNonAttributedTypeConstructor());
_ilg.Stloc(_objectLocal);
}
}
else
{
_ilg.Call(null, XmlFormatGeneratorStatics.GetUninitializedObjectMethod, DataContract.GetIdForInitialization(classContract));
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(_objectLocal);
}
}
private void InvokeOnDeserializing(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnDeserializing(classContract.BaseContract);
if (classContract.OnDeserializing != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnDeserializing);
}
}
private void InvokeOnDeserialized(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnDeserialized(classContract.BaseContract);
if (classContract.OnDeserialized != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnDeserialized);
}
}
private void ReadClass(ClassDataContract classContract)
{
if (classContract.HasExtensionData)
{
LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData");
_ilg.New(XmlFormatGeneratorStatics.ExtensionDataObjectCtor);
_ilg.Store(extensionDataLocal);
ReadMembers(classContract, extensionDataLocal);
ClassDataContract currentContract = classContract;
while (currentContract != null)
{
MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod;
if (extensionDataSetMethod != null)
_ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal);
currentContract = currentContract.BaseContract;
}
}
else
{
ReadMembers(classContract, null /*extensionDataLocal*/);
}
}
private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal)
{
int memberCount = classContract.MemberNames.Length;
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount);
LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1);
int firstRequiredMember;
bool[] requiredMembers = GetRequiredMembers(classContract, out firstRequiredMember);
bool hasRequiredMembers = (firstRequiredMember < memberCount);
LocalBuilder requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, "requiredIndex", firstRequiredMember) : null;
object forReadElements = _ilg.For(null, null, null);
_ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg);
_ilg.IfFalseBreak(forReadElements);
if (hasRequiredMembers)
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetMemberIndexWithRequiredMembersMethod, _xmlReaderArg, _memberNamesArg, _memberNamespacesArg, memberIndexLocal, requiredIndexLocal, extensionDataLocal);
else
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetMemberIndexMethod, _xmlReaderArg, _memberNamesArg, _memberNamespacesArg, memberIndexLocal, extensionDataLocal);
Label[] memberLabels = _ilg.Switch(memberCount);
ReadMembers(classContract, requiredMembers, memberLabels, memberIndexLocal, requiredIndexLocal);
_ilg.EndSwitch();
_ilg.EndFor();
if (hasRequiredMembers)
{
_ilg.If(requiredIndexLocal, Cmp.LessThan, memberCount);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMissingExceptionMethod, _xmlReaderArg, memberIndexLocal, requiredIndexLocal, _memberNamesArg);
_ilg.EndIf();
}
}
private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder requiredIndexLocal)
{
int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, requiredMembers,
memberLabels, memberIndexLocal, requiredIndexLocal);
for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
{
DataMember dataMember = classContract.Members[i];
Type memberType = dataMember.MemberType;
_ilg.Case(memberLabels[memberCount], dataMember.Name);
if (dataMember.IsRequired)
{
int nextRequiredIndex = memberCount + 1;
for (; nextRequiredIndex < requiredMembers.Length; nextRequiredIndex++)
if (requiredMembers[nextRequiredIndex])
break;
_ilg.Set(requiredIndexLocal, nextRequiredIndex);
}
LocalBuilder value = null;
if (dataMember.IsGetOnlyCollection)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(dataMember.MemberInfo);
value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value");
_ilg.Stloc(value);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value);
ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace);
}
else
{
value = ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace);
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Ldloc(value);
_ilg.StoreMember(dataMember.MemberInfo);
}
#if FEATURE_LEGACYNETCF
// The DataContractSerializer in the full framework doesn't support unordered elements:
// deserialization will fail if the data members in the XML are not sorted alphabetically.
// But the NetCF DataContractSerializer does support unordered element. To maintain compatibility
// with Mango we always search for the member from the beginning of the member list.
// We set memberIndexLocal to -1 because GetMemberIndex always starts from memberIndex+1.
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
ilg.Set(memberIndexLocal, (int)-1);
else
#endif // FEATURE_LEGACYNETCF
_ilg.Set(memberIndexLocal, memberCount);
_ilg.EndCase();
}
return memberCount;
}
private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequiredMember)
{
int memberCount = contract.MemberNames.Length;
bool[] requiredMembers = new bool[memberCount];
GetRequiredMembers(contract, requiredMembers);
for (firstRequiredMember = 0; firstRequiredMember < memberCount; firstRequiredMember++)
if (requiredMembers[firstRequiredMember])
break;
return requiredMembers;
}
private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers)
{
int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers);
List<DataMember> members = contract.Members;
for (int i = 0; i < members.Count; i++, memberCount++)
{
requiredMembers[memberCount] = members[i].IsRequired;
}
return memberCount;
}
private void ReadISerializable(ClassDataContract classContract)
{
ConstructorInfo ctor = classContract.GetISerializableConstructor();
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, _xmlReaderArg, classContract.UnderlyingType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(ctor);
}
private LocalBuilder ReadValue(Type type, string name, string ns)
{
LocalBuilder value = _ilg.DeclareLocal(type, "valueRead");
LocalBuilder nullableValue = null;
int nullables = 0;
while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
{
nullables++;
type = type.GetGenericArguments()[0];
}
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType)
{
LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, _xmlReaderArg, type, DataContract.IsTypeSerializable(type));
_ilg.Stloc(objectId);
// Deserialize null
_ilg.If(objectId, Cmp.EqualTo, Globals.NullObjectId);
if (nullables != 0)
{
_ilg.LoadAddress(value);
_ilg.InitObj(value.LocalType);
}
else if (type.IsValueType)
ThrowValidationException(SR.Format(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type)));
else
{
_ilg.Load(null);
_ilg.Stloc(value);
}
// Deserialize value
// Compare against Globals.NewObjectId, which is set to string.Empty
_ilg.ElseIfIsEmptyString(objectId);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod);
_ilg.Stloc(objectId);
if (type.IsValueType)
{
_ilg.IfNotIsEmptyString(objectId);
ThrowValidationException(SR.Format(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type)));
_ilg.EndIf();
}
if (nullables != 0)
{
nullableValue = value;
value = _ilg.DeclareLocal(type, "innerValueRead");
}
if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject)
{
_ilg.Call(_xmlReaderArg, primitiveContract.XmlFormatReaderMethod);
_ilg.Stloc(value);
if (!type.IsValueType)
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, value);
}
else
{
InternalDeserialize(value, type, name, ns);
}
// Deserialize ref
_ilg.Else();
if (type.IsValueType)
ThrowValidationException(SR.Format(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type)));
else
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetExistingObjectMethod, objectId, type, name, ns);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(value);
}
_ilg.EndIf();
if (nullableValue != null)
{
_ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId);
WrapNullableObject(value, nullableValue, nullables);
_ilg.EndIf();
value = nullableValue;
}
}
else
{
InternalDeserialize(value, type, name, ns);
}
return value;
}
private void InternalDeserialize(LocalBuilder value, Type type, string name, string ns)
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlReaderArg);
Type declaredType = type;
_ilg.Load(DataContract.GetId(declaredType.TypeHandle));
_ilg.Ldtoken(declaredType);
_ilg.Load(name);
_ilg.Load(ns);
_ilg.Call(XmlFormatGeneratorStatics.InternalDeserializeMethod);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(value);
}
private void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue, int nullables)
{
Type innerType = innerValue.LocalType, outerType = outerValue.LocalType;
_ilg.LoadAddress(outerValue);
_ilg.Load(innerValue);
for (int i = 1; i < nullables; i++)
{
Type type = Globals.TypeOfNullable.MakeGenericType(innerType);
_ilg.New(type.GetConstructor(new Type[] { innerType }));
innerType = type;
}
_ilg.Call(outerType.GetConstructor(new Type[] { innerType }));
}
private void ReadCollection(CollectionDataContract collectionContract)
{
Type type = collectionContract.UnderlyingType;
Type itemType = collectionContract.ItemType;
bool isArray = (collectionContract.Kind == CollectionKind.Array);
ConstructorInfo constructor = collectionContract.Constructor;
if (type.IsInterface)
{
switch (collectionContract.Kind)
{
case CollectionKind.GenericDictionary:
type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments());
constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
break;
case CollectionKind.Dictionary:
type = Globals.TypeOfHashtable;
constructor = XmlFormatGeneratorStatics.HashtableCtor;
break;
case CollectionKind.Collection:
case CollectionKind.GenericCollection:
case CollectionKind.Enumerable:
case CollectionKind.GenericEnumerable:
case CollectionKind.List:
case CollectionKind.GenericList:
type = itemType.MakeArrayType();
isArray = true;
break;
}
}
string itemName = collectionContract.ItemName;
string itemNs = collectionContract.StableName.Namespace;
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
if (!isArray)
{
if (type.IsValueType)
{
_ilg.Ldloca(_objectLocal);
_ilg.InitObj(type);
}
else
{
_ilg.New(constructor);
_ilg.Stloc(_objectLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
}
}
LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetArraySizeMethod);
_ilg.Stloc(size);
LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod);
_ilg.Stloc(objectId);
bool canReadPrimitiveArray = false;
if (isArray && TryReadPrimitiveArray(type, itemType, size))
{
canReadPrimitiveArray = true;
_ilg.IfNot();
}
_ilg.If(size, Cmp.EqualTo, -1);
LocalBuilder growingCollection = null;
if (isArray)
{
growingCollection = _ilg.DeclareLocal(type, "growingCollection");
_ilg.NewArray(itemType, 32);
_ilg.Stloc(growingCollection);
}
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
object forLoop = _ilg.For(i, 0, Int32.MaxValue);
IsStartElement(_memberNamesArg, _memberNamespacesArg);
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs);
if (isArray)
{
MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType);
_ilg.Call(null, ensureArraySizeMethod, growingCollection, i);
_ilg.Stloc(growingCollection);
_ilg.StoreArrayElement(growingCollection, i, value);
}
else
StoreCollectionValue(_objectLocal, value, collectionContract);
_ilg.Else();
IsEndElement();
_ilg.If();
_ilg.Break(forLoop);
_ilg.Else();
HandleUnexpectedItemInCollection(i);
_ilg.EndIf();
_ilg.EndIf();
_ilg.EndFor();
if (isArray)
{
MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType);
_ilg.Call(null, trimArraySizeMethod, growingCollection, i);
_ilg.Stloc(_objectLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal);
}
_ilg.Else();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, size);
if (isArray)
{
_ilg.NewArray(itemType, size);
_ilg.Stloc(_objectLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
}
LocalBuilder j = _ilg.DeclareLocal(Globals.TypeOfInt, "j");
_ilg.For(j, 0, size);
IsStartElement(_memberNamesArg, _memberNamespacesArg);
_ilg.If();
LocalBuilder itemValue = ReadCollectionItem(collectionContract, itemType, itemName, itemNs);
if (isArray)
_ilg.StoreArrayElement(_objectLocal, j, itemValue);
else
StoreCollectionValue(_objectLocal, itemValue, collectionContract);
_ilg.Else();
HandleUnexpectedItemInCollection(j);
_ilg.EndIf();
_ilg.EndFor();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _memberNamespacesArg);
_ilg.EndIf();
if (canReadPrimitiveArray)
{
_ilg.Else();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal);
_ilg.EndIf();
}
}
private void ReadGetOnlyCollection(CollectionDataContract collectionContract)
{
Type type = collectionContract.UnderlyingType;
Type itemType = collectionContract.ItemType;
bool isArray = (collectionContract.Kind == CollectionKind.Array);
string itemName = collectionContract.ItemName;
string itemNs = collectionContract.StableName.Namespace;
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(_objectLocal);
//check that items are actually going to be deserialized into the collection
IsStartElement(_memberNamesArg, _memberNamespacesArg);
_ilg.If();
_ilg.If(_objectLocal, Cmp.EqualTo, null);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type);
_ilg.Else();
LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize");
if (isArray)
{
_ilg.Load(_objectLocal);
_ilg.Call(XmlFormatGeneratorStatics.GetArrayLengthMethod);
_ilg.Stloc(size);
}
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
object forLoop = _ilg.For(i, 0, Int32.MaxValue);
IsStartElement(_memberNamesArg, _memberNamespacesArg);
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs);
if (isArray)
{
_ilg.If(size, Cmp.EqualTo, i);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowArrayExceededSizeExceptionMethod, size, type);
_ilg.Else();
_ilg.StoreArrayElement(_objectLocal, i, value);
_ilg.EndIf();
}
else
StoreCollectionValue(_objectLocal, value, collectionContract);
_ilg.Else();
IsEndElement();
_ilg.If();
_ilg.Break(forLoop);
_ilg.Else();
HandleUnexpectedItemInCollection(i);
_ilg.EndIf();
_ilg.EndIf();
_ilg.EndFor();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _memberNamespacesArg);
_ilg.EndIf();
_ilg.EndIf();
}
private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
if (primitiveContract == null)
return false;
string readArrayMethod = null;
switch (itemType.GetTypeCode())
{
case TypeCode.Boolean:
readArrayMethod = "TryReadBooleanArray";
break;
case TypeCode.DateTime:
readArrayMethod = "TryReadDateTimeArray";
break;
case TypeCode.Decimal:
readArrayMethod = "TryReadDecimalArray";
break;
case TypeCode.Int32:
readArrayMethod = "TryReadInt32Array";
break;
case TypeCode.Int64:
readArrayMethod = "TryReadInt64Array";
break;
case TypeCode.Single:
readArrayMethod = "TryReadSingleArray";
break;
case TypeCode.Double:
readArrayMethod = "TryReadDoubleArray";
break;
default:
break;
}
if (readArrayMethod != null)
{
_ilg.Load(_xmlReaderArg);
_ilg.Load(_contextArg);
_ilg.Load(_memberNamesArg);
_ilg.Load(_memberNamespacesArg);
_ilg.Load(size);
_ilg.Ldloca(_objectLocal);
_ilg.Call(typeof(XmlReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers));
return true;
}
return false;
}
private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs)
{
if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary)
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod);
LocalBuilder value = _ilg.DeclareLocal(itemType, "valueRead");
_ilg.Load(_collectionContractArg);
_ilg.Call(XmlFormatGeneratorStatics.GetItemContractMethod);
_ilg.Load(_xmlReaderArg);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.ReadXmlValueMethod);
_ilg.ConvertValue(Globals.TypeOfObject, itemType);
_ilg.Stloc(value);
return value;
}
else
{
return ReadValue(itemType, itemName, itemNs);
}
}
private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract)
{
if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary)
{
ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract;
if (keyValuePairContract == null)
{
DiagnosticUtility.DebugAssert("Failed to create contract for KeyValuePair type");
}
DataMember keyMember = keyValuePairContract.Members[0];
DataMember valueMember = keyValuePairContract.Members[1];
LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name);
LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name);
_ilg.LoadAddress(value);
_ilg.LoadMember(keyMember.MemberInfo);
_ilg.Stloc(pairKey);
_ilg.LoadAddress(value);
_ilg.LoadMember(valueMember.MemberInfo);
_ilg.Stloc(pairValue);
_ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue);
if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid)
_ilg.Pop();
}
else
{
_ilg.Call(collection, collectionContract.AddMethod, value);
if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid)
_ilg.Pop();
}
}
private void HandleUnexpectedItemInCollection(LocalBuilder iterator)
{
IsStartElement();
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.SkipUnknownElementMethod, _xmlReaderArg);
_ilg.Dec(iterator);
_ilg.Else();
ThrowUnexpectedStateException(XmlNodeType.Element);
_ilg.EndIf();
}
private void IsStartElement(ArgBuilder nameArg, ArgBuilder nsArg)
{
_ilg.Call(_xmlReaderArg, XmlFormatGeneratorStatics.IsStartElementMethod2, nameArg, nsArg);
}
private void IsStartElement()
{
_ilg.Call(_xmlReaderArg, XmlFormatGeneratorStatics.IsStartElementMethod0);
}
private void IsEndElement()
{
_ilg.Load(_xmlReaderArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.NodeTypeProperty);
_ilg.Load(XmlNodeType.EndElement);
_ilg.Ceq();
}
private void ThrowUnexpectedStateException(XmlNodeType expectedState)
{
_ilg.Call(null, XmlFormatGeneratorStatics.CreateUnexpectedStateExceptionMethod, expectedState, _xmlReaderArg);
_ilg.Throw();
}
private void ThrowValidationException(string msg, params object[] values)
{
{
_ilg.Load(msg);
}
ThrowValidationException();
}
private void ThrowValidationException()
{
//SerializationException is internal in SL and so cannot be directly invoked from DynamicMethod
//So use helper function to create SerializationException
_ilg.Call(XmlFormatGeneratorStatics.CreateSerializationExceptionMethod);
_ilg.Throw();
}
#endif
}
internal static object UnsafeGetUninitializedObject(Type type)
{
return FormatterServices.GetUninitializedObject(type);
}
/// <SecurityNote>
/// Critical - Elevates by calling GetUninitializedObject which has a LinkDemand
/// Safe - marked as such so that it's callable from transparent generated IL. Takes id as parameter which
/// is guaranteed to be in internal serialization cache.
/// </SecurityNote>
#if USE_REFEMIT
public static object UnsafeGetUninitializedObject(int id)
#else
internal static object UnsafeGetUninitializedObject(int id)
#endif
{
var type = DataContract.GetDataContractForInitialization(id).TypeForInitialization;
return UnsafeGetUninitializedObject(type);
}
}
}
| |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT License
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Internal;
using MySqlConnector;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
namespace Pomelo.Extensions.Caching.MySql
{
internal class MonoDatabaseOperations : DatabaseOperations
{
public MonoDatabaseOperations(
string readConnectionString, string writeConnectionString, string schemaName, string tableName, ISystemClock systemClock)
: base(readConnectionString, writeConnectionString, schemaName, tableName, systemClock)
{
}
protected override byte[] GetCacheItem(string key, bool includeValue)
{
var utcNow = SystemClock.UtcNow;
string query;
if (includeValue)
{
query = MySqlQueries.GetCacheItem;
}
else
{
query = MySqlQueries.GetCacheItemWithoutValue;
}
byte[] value = null;
//TimeSpan? slidingExpiration = null;
//DateTimeOffset? absoluteExpiration = null;
//DateTimeOffset expirationTime;
using (var connection = new MySqlConnection(ReadConnectionString))
{
using (var command = new MySqlCommand(query, connection))
{
command.Parameters
.AddCacheItemId(key)
.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
connection.Open();
using (var reader = command.ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.SingleResult))
{
if (reader.Read())
{
/*var id = reader.GetString(Columns.Indexes.CacheItemIdIndex);
expirationTime = DateTimeOffset.Parse(reader[Columns.Indexes.ExpiresAtTimeIndex].ToString());
if (!reader.IsDBNull(Columns.Indexes.SlidingExpirationInSecondsIndex))
{
slidingExpiration = TimeSpan.FromSeconds(
reader.GetInt64(Columns.Indexes.SlidingExpirationInSecondsIndex));
}
if (!reader.IsDBNull(Columns.Indexes.AbsoluteExpirationIndex))
{
absoluteExpiration = DateTimeOffset.Parse(
reader[Columns.Indexes.AbsoluteExpirationIndex].ToString());
}*/
if (includeValue)
{
value = (byte[])reader[Columns.Indexes.CacheItemValueIndex];
}
}
else
{
return null;
}
}
}
}
return value;
}
protected override async Task<byte[]> GetCacheItemAsync(string key, bool includeValue, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
var utcNow = SystemClock.UtcNow;
string query;
if (includeValue)
{
query = MySqlQueries.GetCacheItem;
}
else
{
query = MySqlQueries.GetCacheItemWithoutValue;
}
byte[] value = null;
//TimeSpan? slidingExpiration = null;
//DateTime? absoluteExpiration = null;
//DateTime expirationTime;
using (var connection = new MySqlConnection(ReadConnectionString))
{
using (var command = new MySqlCommand(MySqlQueries.GetCacheItem, connection))
{
command.Parameters
.AddCacheItemId(key)
.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
await connection.OpenAsync(token);
using (var reader = await command.ExecuteReaderAsync(
CommandBehavior.SingleRow | CommandBehavior.SingleResult,
token))
{
if (await reader.ReadAsync(token))
{
/*var id = reader.GetString(Columns.Indexes.CacheItemIdIndex);
expirationTime = DateTime.Parse(reader[Columns.Indexes.ExpiresAtTimeIndex].ToString());
if (!await reader.IsDBNullAsync(Columns.Indexes.SlidingExpirationInSecondsIndex))
{
slidingExpiration = TimeSpan.FromSeconds(
Convert.ToInt64(reader[Columns.Indexes.SlidingExpirationInSecondsIndex].ToString()));
}
if (!await reader.IsDBNullAsync(Columns.Indexes.AbsoluteExpirationIndex))
{
absoluteExpiration = DateTime.Parse(
reader[Columns.Indexes.AbsoluteExpirationIndex].ToString());
}*/
if (includeValue)
{
value = (byte[])reader[Columns.Indexes.CacheItemValueIndex];
}
}
else
{
return null;
}
}
}
}
return value;
}
public override void SetCacheItem(string key, byte[] value, DistributedCacheEntryOptions options)
{
var utcNow = SystemClock.UtcNow;
var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
ValidateOptions(options.SlidingExpiration, absoluteExpiration);
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var upsertCommand = new MySqlCommand(MySqlQueries.SetCacheItem, connection))
{
upsertCommand.Parameters
.AddCacheItemId(key)
.AddCacheItemValue(value)
.AddSlidingExpirationInSeconds(options.SlidingExpiration)
.AddAbsoluteExpirationMono(absoluteExpiration)
.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
connection.Open();
try
{
upsertCommand.ExecuteNonQuery();
}
catch (MySqlException ex)
{
if (IsDuplicateKeyException(ex))
{
// There is a possibility that multiple requests can try to add the same item to the cache, in
// which case we receive a 'duplicate key' exception on the primary key column.
}
else
{
throw;
}
}
}
}
}
public override async Task SetCacheItemAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
{
token.ThrowIfCancellationRequested();
var utcNow = SystemClock.UtcNow;
var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
ValidateOptions(options.SlidingExpiration, absoluteExpiration);
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var upsertCommand = new MySqlCommand(MySqlQueries.SetCacheItem, connection))
{
upsertCommand.Parameters
.AddCacheItemId(key)
.AddCacheItemValue(value)
.AddSlidingExpirationInSeconds(options.SlidingExpiration)
.AddAbsoluteExpirationMono(absoluteExpiration)
.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
await connection.OpenAsync(token);
try
{
await upsertCommand.ExecuteNonQueryAsync(token);
}
catch (MySqlException ex)
{
if (IsDuplicateKeyException(ex))
{
// There is a possibility that multiple requests can try to add the same item to the cache, in
// which case we receive a 'duplicate key' exception on the primary key column.
}
else
{
throw;
}
}
}
}
}
/*public override void DeleteExpiredCacheItems()
{
var utcNow = SystemClock.UtcNow;
using (var connection = new MySqlConnection(WriteConnectionString))
{
using (var command = new MySqlCommand(MySqlQueries.DeleteExpiredCacheItems, connection))
{
command.Parameters.AddWithValue("UtcNow", MySqlDbType.DateTime, utcNow.UtcDateTime);
connection.Open();
var effectedRowCount = command.ExecuteNonQuery();
}
}
}*/
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// ----------------------------------------------------------------------------
// This class takes an EXPRMEMGRP and a set of arguments and binds the arguments
// to the best applicable method in the group.
// ----------------------------------------------------------------------------
internal sealed partial class ExpressionBinder
{
internal sealed class GroupToArgsBinder
{
private enum Result
{
Success,
Failure_SearchForExpanded,
Failure_NoSearchForExpanded
}
private readonly ExpressionBinder _pExprBinder;
private bool _fCandidatesUnsupported;
private readonly BindingFlag _fBindFlags;
private readonly ExprMemberGroup _pGroup;
private readonly ArgInfos _pArguments;
private readonly ArgInfos _pOriginalArguments;
private readonly bool _bHasNamedArguments;
private AggregateType _pCurrentType;
private MethodOrPropertySymbol _pCurrentSym;
private TypeArray _pCurrentTypeArgs;
private TypeArray _pCurrentParameters;
private int _nArgBest;
// end of current namespaces extension method list
private readonly GroupToArgsBinderResult _results;
private readonly List<CandidateFunctionMember> _methList;
private readonly MethPropWithInst _mpwiParamTypeConstraints;
private readonly MethPropWithInst _mpwiBogus;
private readonly MethPropWithInst _mpwiCantInferInstArg;
private readonly MethWithType _mwtBadArity;
private Name _pInvalidSpecifiedName;
private Name _pNameUsedInPositionalArgument;
private Name _pDuplicateSpecifiedName;
// When we find a type with an interface, then we want to mark all other interfaces that it
// implements as being hidden. We also want to mark object as being hidden. So stick them
// all in this list, and then for subsequent types, if they're in this list, then we
// ignore them.
private readonly List<CType> _HiddenTypes;
private bool _bArgumentsChangedForNamedOrOptionalArguments;
public GroupToArgsBinder(ExpressionBinder exprBinder, BindingFlag bindFlags, ExprMemberGroup grp, ArgInfos args, ArgInfos originalArgs, bool bHasNamedArguments)
{
Debug.Assert(grp != null);
Debug.Assert(exprBinder != null);
Debug.Assert(args != null);
_pExprBinder = exprBinder;
_fCandidatesUnsupported = false;
_fBindFlags = bindFlags;
_pGroup = grp;
_pArguments = args;
_pOriginalArguments = originalArgs;
_bHasNamedArguments = bHasNamedArguments;
_pCurrentType = null;
_pCurrentSym = null;
_pCurrentTypeArgs = null;
_pCurrentParameters = null;
_nArgBest = -1;
_results = new GroupToArgsBinderResult();
_methList = new List<CandidateFunctionMember>();
_mpwiParamTypeConstraints = new MethPropWithInst();
_mpwiBogus = new MethPropWithInst();
_mpwiCantInferInstArg = new MethPropWithInst();
_mwtBadArity = new MethWithType();
_HiddenTypes = new List<CType>();
}
// ----------------------------------------------------------------------------
// This method does the actual binding.
// ----------------------------------------------------------------------------
public void Bind()
{
Debug.Assert(_pGroup.SymKind == SYMKIND.SK_MethodSymbol || _pGroup.SymKind == SYMKIND.SK_PropertySymbol && 0 != (_pGroup.Flags & EXPRFLAG.EXF_INDEXER));
LookForCandidates();
if (!GetResultOfBind())
{
throw ReportErrorsOnFailure();
}
}
public GroupToArgsBinderResult GetResultsOfBind()
{
return _results;
}
private SymbolLoader GetSymbolLoader()
{
return _pExprBinder.GetSymbolLoader();
}
private CSemanticChecker GetSemanticChecker()
{
return _pExprBinder.GetSemanticChecker();
}
private ErrorHandling GetErrorContext()
{
return _pExprBinder.GetErrorContext();
}
private static CType GetTypeQualifier(ExprMemberGroup pGroup)
{
Debug.Assert(pGroup != null);
return (pGroup.Flags & EXPRFLAG.EXF_CTOR) != 0 ? pGroup.ParentType : pGroup.OptionalObject?.Type;
}
private void LookForCandidates()
{
bool fExpanded = false;
bool bSearchForExpanded = true;
bool allCandidatesUnsupported = true;
bool lookedAtCandidates = false;
// Calculate the mask based on the type of the sym we've found so far. This
// is to ensure that if we found a propsym (or methsym, or whatever) the
// iterator will only return propsyms (or methsyms, or whatever)
symbmask_t mask = (symbmask_t)(1 << (int)_pGroup.SymKind);
CType pTypeThrough = _pGroup.OptionalObject?.Type;
CMemberLookupResults.CMethodIterator iterator = _pGroup.MemberLookupResults.GetMethodIterator(GetSemanticChecker(), GetSymbolLoader(), pTypeThrough, GetTypeQualifier(_pGroup), _pExprBinder.ContextForMemberLookup(), true, // AllowBogusAndInaccessible
false, _pGroup.TypeArgs.Count, _pGroup.Flags, mask);
while (true)
{
bool bFoundExpanded;
bFoundExpanded = false;
if (bSearchForExpanded && !fExpanded)
{
bFoundExpanded = fExpanded = ConstructExpandedParameters();
}
// Get the next sym to search for.
if (!bFoundExpanded)
{
fExpanded = false;
if (!GetNextSym(iterator))
{
break;
}
// Get the parameters.
_pCurrentParameters = _pCurrentSym.Params;
bSearchForExpanded = true;
}
if (_bArgumentsChangedForNamedOrOptionalArguments)
{
// If we changed them last time, then we need to reset them.
_bArgumentsChangedForNamedOrOptionalArguments = false;
CopyArgInfos(_pOriginalArguments, _pArguments);
}
// If we have named arguments, reorder them for this method.
// If we don't have Exprs, its because we're doing a method group conversion.
// In those scenarios, we never want to add named arguments or optional arguments.
if (_bHasNamedArguments)
{
if (!ReOrderArgsForNamedArguments())
{
continue;
}
}
else if (HasOptionalParameters())
{
if (!AddArgumentsForOptionalParameters())
{
continue;
}
}
if (!bFoundExpanded)
{
lookedAtCandidates = true;
allCandidatesUnsupported &= CSemanticChecker.CheckBogus(_pCurrentSym);
// If we have the wrong number of arguments and still have room in our cache of 20,
// then store it in our cache and go to the next sym.
if (_pCurrentParameters.Count != _pArguments.carg)
{
bSearchForExpanded = true;
continue;
}
}
// If we cant use the current symbol, then we've filtered it, so get the next one.
if (!iterator.CanUseCurrentSymbol())
{
continue;
}
// Get the current type args.
Result currentTypeArgsResult = DetermineCurrentTypeArgs();
if (currentTypeArgsResult != Result.Success)
{
bSearchForExpanded = (currentTypeArgsResult == Result.Failure_SearchForExpanded);
continue;
}
// Check access.
bool fCanAccess = !iterator.IsCurrentSymbolInaccessible();
if (!fCanAccess && (!_methList.IsEmpty() || _results.GetInaccessibleResult()))
{
// We'll never use this one for error reporting anyway, so just skip it.
bSearchForExpanded = false;
continue;
}
// Check bogus.
bool fBogus = fCanAccess && iterator.IsCurrentSymbolBogus();
if (fBogus && (!_methList.IsEmpty() || _results.GetInaccessibleResult() || _mpwiBogus))
{
// We'll never use this one for error reporting anyway, so just skip it.
bSearchForExpanded = false;
continue;
}
// Check convertibility of arguments.
if (!ArgumentsAreConvertible())
{
bSearchForExpanded = true;
continue;
}
// We know we have the right number of arguments and they are all convertible.
if (!fCanAccess)
{
// In case we never get an accessible method, this will allow us to give
// a better error...
Debug.Assert(!_results.GetInaccessibleResult());
_results.GetInaccessibleResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
}
else if (fBogus)
{
// In case we never get a good method, this will allow us to give
// a better error...
Debug.Assert(!_mpwiBogus);
_mpwiBogus.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
}
else
{
// This is a plausible method / property to call.
// Link it in at the end of the list.
_methList.Add(new CandidateFunctionMember(
new MethPropWithInst(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs),
_pCurrentParameters,
0,
fExpanded));
// When we find a method, we check if the type has interfaces. If so, mark the other interfaces
// as hidden, and object as well.
if (_pCurrentType.isInterfaceType())
{
TypeArray ifaces = _pCurrentType.GetIfacesAll();
for (int i = 0; i < ifaces.Count; i++)
{
AggregateType type = ifaces[i] as AggregateType;
Debug.Assert(type.isInterfaceType());
_HiddenTypes.Add(type);
}
// Mark object.
AggregateType typeObject = GetSymbolLoader().GetPredefindType(PredefinedType.PT_OBJECT);
_HiddenTypes.Add(typeObject);
}
}
// Don't look at the expanded form.
bSearchForExpanded = false;
}
_fCandidatesUnsupported = allCandidatesUnsupported && lookedAtCandidates;
// Restore the arguments to their original state if we changed them for named/optional arguments.
// ILGen will take care of putting the real arguments in there.
if (_bArgumentsChangedForNamedOrOptionalArguments)
{
// If we changed them last time, then we need to reset them.
CopyArgInfos(_pOriginalArguments, _pArguments);
}
}
private void CopyArgInfos(ArgInfos src, ArgInfos dst)
{
dst.carg = src.carg;
dst.types = src.types;
dst.prgexpr.Clear();
for (int i = 0; i < src.prgexpr.Count; i++)
{
dst.prgexpr.Add(src.prgexpr[i]);
}
}
private bool GetResultOfBind()
{
// We looked at all the evidence, and we come to render the verdict:
if (!_methList.IsEmpty())
{
CandidateFunctionMember pmethBest;
if (_methList.Count == 1)
{
// We found the single best method to call.
pmethBest = _methList.Head();
}
else
{
// We have some ambiguities, lets sort them out.
CType pTypeThrough = _pGroup.OptionalObject?.Type;
pmethBest = _pExprBinder.FindBestMethod(_methList, pTypeThrough, _pArguments, out CandidateFunctionMember pAmbig1, out CandidateFunctionMember pAmbig2);
if (null == pmethBest)
{
_results.AmbiguousResult = pAmbig2.mpwi;
if (pAmbig1.@params != pAmbig2.@params ||
pAmbig1.mpwi.MethProp().Params.Count != pAmbig2.mpwi.MethProp().Params.Count ||
pAmbig1.mpwi.TypeArgs != pAmbig2.mpwi.TypeArgs ||
pAmbig1.mpwi.GetType() != pAmbig2.mpwi.GetType() ||
pAmbig1.mpwi.MethProp().Params == pAmbig2.mpwi.MethProp().Params)
{
throw GetErrorContext().Error(ErrorCode.ERR_AmbigCall, pAmbig1.mpwi, pAmbig2.mpwi);
}
// The two signatures are identical so don't use the type args in the error message.
throw GetErrorContext().Error(ErrorCode.ERR_AmbigCall, pAmbig1.mpwi.MethProp(), pAmbig2.mpwi.MethProp());
}
}
// This is the "success" exit path.
Debug.Assert(pmethBest != null);
_results.BestResult = pmethBest.mpwi;
// Record our best match in the memgroup as well. This is temporary.
if (true)
{
ReportErrorsOnSuccess();
}
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////////////////
// This method returns true if we're able to match arguments to their names.
// If we either have too many arguments, or we cannot match their names, then
// we return false.
//
// Note that if we have not enough arguments, we still return true as long as
// we can find matching parameters for each named arguments, and all parameters
// that do not have a matching argument are optional parameters.
private bool ReOrderArgsForNamedArguments()
{
// First we need to find the method that we're actually trying to call.
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject);
if (methprop == null)
{
return false;
}
int numParameters = _pCurrentParameters.Count;
// If we have no parameters, or fewer parameters than we have arguments, bail.
if (numParameters == 0 || numParameters < _pArguments.carg)
{
return false;
}
// Make sure all the names we specified are in the list and we don't have duplicates.
if (!NamedArgumentNamesAppearInParameterList(methprop))
{
return false;
}
_bArgumentsChangedForNamedOrOptionalArguments = ReOrderArgsForNamedArguments(
methprop,
_pCurrentParameters,
_pCurrentType,
_pGroup,
_pArguments,
_pExprBinder.GetTypes(),
_pExprBinder.GetExprFactory(),
GetSymbolLoader());
return _bArgumentsChangedForNamedOrOptionalArguments;
}
internal static bool ReOrderArgsForNamedArguments(
MethodOrPropertySymbol methprop,
TypeArray pCurrentParameters,
AggregateType pCurrentType,
ExprMemberGroup pGroup,
ArgInfos pArguments,
TypeManager typeManager,
ExprFactory exprFactory,
SymbolLoader symbolLoader)
{
// We use the param count from pCurrentParameters because they may have been resized
// for param arrays.
int numParameters = pCurrentParameters.Count;
Expr[] pExprArguments = new Expr[numParameters];
// Now go through the parameters. First set all positional arguments in the new argument
// set, then for the remainder, look for a named argument with a matching name.
int index = 0;
Expr paramArrayArgument = null;
TypeArray @params = typeManager.SubstTypeArray(
pCurrentParameters,
pCurrentType,
pGroup.TypeArgs);
foreach (Name name in methprop.ParameterNames)
{
// This can happen if we had expanded our param array to size 0.
if (index >= pCurrentParameters.Count)
{
break;
}
// If:
// (1) we have a param array method
// (2) we're on the last arg
// (3) the thing we have is an array init thats generated for param array
// then let us through.
if (methprop.isParamArray &&
index < pArguments.carg &&
pArguments.prgexpr[index] is ExprArrayInit arrayInit && arrayInit.GeneratedForParamArray)
{
paramArrayArgument = pArguments.prgexpr[index];
}
// Positional.
if (index < pArguments.carg &&
!(pArguments.prgexpr[index] is ExprNamedArgumentSpecification) &&
!(pArguments.prgexpr[index] is ExprArrayInit arrayInitPos && arrayInitPos.GeneratedForParamArray))
{
pExprArguments[index] = pArguments.prgexpr[index++];
continue;
}
// Look for names.
Expr pNewArg = FindArgumentWithName(pArguments, name);
if (pNewArg == null)
{
if (methprop.IsParameterOptional(index))
{
pNewArg = GenerateOptionalArgument(symbolLoader, exprFactory, methprop, @params[index], index);
}
else if (paramArrayArgument != null && index == methprop.Params.Count - 1)
{
// If we have a param array argument and we're on the last one, then use it.
pNewArg = paramArrayArgument;
}
else
{
// No name and no default value.
return false;
}
}
pExprArguments[index++] = pNewArg;
}
// Here we've found all the arguments, or have default values for them.
CType[] prgTypes = new CType[pCurrentParameters.Count];
for (int i = 0; i < numParameters; i++)
{
if (i < pArguments.prgexpr.Count)
{
pArguments.prgexpr[i] = pExprArguments[i];
}
else
{
pArguments.prgexpr.Add(pExprArguments[i]);
}
prgTypes[i] = pArguments.prgexpr[i].Type;
}
pArguments.carg = pCurrentParameters.Count;
pArguments.types = symbolLoader.getBSymmgr().AllocParams(pCurrentParameters.Count, prgTypes);
return true;
}
/////////////////////////////////////////////////////////////////////////////////
private static Expr GenerateOptionalArgument(
SymbolLoader symbolLoader,
ExprFactory exprFactory,
MethodOrPropertySymbol methprop,
CType type,
int index)
{
CType pParamType = type;
CType pRawParamType = type.StripNubs();
Expr optionalArgument;
if (methprop.HasDefaultParameterValue(index))
{
CType pConstValType = methprop.GetDefaultParameterValueConstValType(index);
ConstVal cv = methprop.GetDefaultParameterValue(index);
if (pConstValType.isPredefType(PredefinedType.PT_DATETIME) &&
(pRawParamType.isPredefType(PredefinedType.PT_DATETIME) || pRawParamType.isPredefType(PredefinedType.PT_OBJECT) || pRawParamType.isPredefType(PredefinedType.PT_VALUE)))
{
// This is the specific case where we want to create a DateTime
// but the constval that stores it is a long.
AggregateType dateTimeType = symbolLoader.GetPredefindType(PredefinedType.PT_DATETIME);
optionalArgument = exprFactory.CreateConstant(dateTimeType, ConstVal.Get(DateTime.FromBinary(cv.Int64Val)));
}
else if (pConstValType.isSimpleOrEnumOrString())
{
// In this case, the constval is a simple type (all the numerics, including
// decimal), or an enum or a string. This covers all the substantial values,
// and everything else that can be encoded is just null or default(something).
// For enum parameters, we create a constant of the enum type. For everything
// else, we create the appropriate constant.
if (pRawParamType.isEnumType() && pConstValType == pRawParamType.underlyingType())
{
optionalArgument = exprFactory.CreateConstant(pRawParamType, cv);
}
else
{
optionalArgument = exprFactory.CreateConstant(pConstValType, cv);
}
}
else if ((pParamType.IsRefType() || pParamType is NullableType) && cv.IsNullRef)
{
// We have an "= null" default value with a reference type or a nullable type.
optionalArgument = exprFactory.CreateNull();
}
else
{
// We have a default value that is encoded as a nullref, and that nullref is
// interpreted as default(something). For instance, the pParamType could be
// a type parameter type or a non-simple value type.
optionalArgument = exprFactory.CreateZeroInit(pParamType);
}
}
else
{
// There was no default parameter specified, so generally use default(T),
// except for some cases when the parameter type in metatdata is object.
if (pParamType.isPredefType(PredefinedType.PT_OBJECT))
{
if (methprop.MarshalAsObject(index))
{
// For [opt] parameters of type object, if we have marshal(iunknown),
// marshal(idispatch), or marshal(interface), then we emit a null.
optionalArgument = exprFactory.CreateNull();
}
else
{
// Otherwise, we generate Type.Missing
AggregateSymbol agg = symbolLoader.GetPredefAgg(PredefinedType.PT_MISSING);
Name name = NameManager.GetPredefinedName(PredefinedName.PN_CAP_VALUE);
FieldSymbol field = symbolLoader.LookupAggMember(name, agg, symbmask_t.MASK_FieldSymbol) as FieldSymbol;
FieldWithType fwt = new FieldWithType(field, agg.getThisType());
ExprField exprField = exprFactory.CreateField(agg.getThisType(), null, fwt, false);
optionalArgument = exprFactory.CreateCast(type, exprField);
}
}
else
{
// Every type aside from object that doesn't have a default value gets
// its default value.
optionalArgument = exprFactory.CreateZeroInit(pParamType);
}
}
Debug.Assert(optionalArgument != null);
optionalArgument.IsOptionalArgument = true;
return optionalArgument;
}
/////////////////////////////////////////////////////////////////////////////////
private MethodOrPropertySymbol FindMostDerivedMethod(
MethodOrPropertySymbol pMethProp,
Expr pObject)
{
return FindMostDerivedMethod(GetSymbolLoader(), pMethProp, pObject?.Type);
}
/////////////////////////////////////////////////////////////////////////////////
public static MethodOrPropertySymbol FindMostDerivedMethod(
SymbolLoader symbolLoader,
MethodOrPropertySymbol pMethProp,
CType pType)
{
bool bIsIndexer = false;
if (!(pMethProp is MethodSymbol method))
{
PropertySymbol prop = (PropertySymbol)pMethProp;
method = prop.GetterMethod ?? prop.SetterMethod;
if (method == null)
{
return null;
}
bIsIndexer = prop is IndexerSymbol;
}
if (!method.isVirtual || pType == null)
{
// if pType is null, this must be a static call.
return method;
}
// Now get the slot method.
var slotMethod = method.swtSlot?.Meth();
if (slotMethod != null)
{
method = slotMethod;
}
if (!(pType is AggregateType agg))
{
// Not something that can have overrides anyway.
return method;
}
for (AggregateSymbol pAggregate = agg.GetOwningAggregate();
pAggregate?.GetBaseAgg() != null;
pAggregate = pAggregate.GetBaseAgg())
{
for (MethodOrPropertySymbol meth = symbolLoader.LookupAggMember(method.name, pAggregate, symbmask_t.MASK_MethodSymbol | symbmask_t.MASK_PropertySymbol) as MethodOrPropertySymbol;
meth != null;
meth = SymbolLoader.LookupNextSym(meth, pAggregate, symbmask_t.MASK_MethodSymbol | symbmask_t.MASK_PropertySymbol) as MethodOrPropertySymbol)
{
if (!meth.isOverride)
{
continue;
}
if (meth.swtSlot.Sym != null && meth.swtSlot.Sym == method)
{
if (bIsIndexer)
{
Debug.Assert(meth is MethodSymbol);
return ((MethodSymbol)meth).getProperty();
}
else
{
return meth;
}
}
}
}
// If we get here, it means we can have two cases: one is that we have
// a delegate. This is because the delegate invoke method is virtual and is
// an override, but we won't have the slots set up correctly, and will
// not find the base type in the inheritance hierarchy. The second is that
// we're calling off of the base itself.
Debug.Assert(method.parent is AggregateSymbol);
return method;
}
/////////////////////////////////////////////////////////////////////////////////
private bool HasOptionalParameters()
{
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject);
return methprop != null && methprop.HasOptionalParameters();
}
/////////////////////////////////////////////////////////////////////////////////
// Returns true if we can either add enough optional parameters to make the
// argument list match, or if we don't need to at all.
private bool AddArgumentsForOptionalParameters()
{
if (_pCurrentParameters.Count <= _pArguments.carg)
{
// If we have enough arguments, or too many, no need to add any optionals here.
return true;
}
// First we need to find the method that we're actually trying to call.
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject);
if (methprop == null)
{
return false;
}
// If we're here, we know we're not in a named argument case. As such, we can
// just generate defaults for every missing argument.
int i = _pArguments.carg;
int index = 0;
TypeArray @params = _pExprBinder.GetTypes().SubstTypeArray(
_pCurrentParameters,
_pCurrentType,
_pGroup.TypeArgs);
Expr[] pArguments = new Expr[_pCurrentParameters.Count - i];
for (; i < @params.Count; i++, index++)
{
if (!methprop.IsParameterOptional(i))
{
// We don't have an optional here, but we need to fill it in.
return false;
}
pArguments[index] = GenerateOptionalArgument(GetSymbolLoader(), _pExprBinder.GetExprFactory(), methprop, @params[i], i);
}
// Success. Lets copy them in now.
for (int n = 0; n < index; n++)
{
_pArguments.prgexpr.Add(pArguments[n]);
}
CType[] prgTypes = new CType[@params.Count];
for (int n = 0; n < @params.Count; n++)
{
prgTypes[n] = _pArguments.prgexpr[n].Type;
}
_pArguments.types = GetSymbolLoader().getBSymmgr().AllocParams(@params.Count, prgTypes);
_pArguments.carg = @params.Count;
_bArgumentsChangedForNamedOrOptionalArguments = true;
return true;
}
/////////////////////////////////////////////////////////////////////////////////
private static Expr FindArgumentWithName(ArgInfos pArguments, Name pName)
{
List<Expr> prgexpr = pArguments.prgexpr;
for (int i = 0; i < pArguments.carg; i++)
{
Expr expr = prgexpr[i];
if (expr is ExprNamedArgumentSpecification named && named.Name == pName)
{
return expr;
}
}
return null;
}
/////////////////////////////////////////////////////////////////////////////////
private bool NamedArgumentNamesAppearInParameterList(
MethodOrPropertySymbol methprop)
{
// Keep track of the current position in the parameter list so that we can check
// containment from this point onwards as well as complete containment. This is
// for error reporting. The user cannot specify a named argument for a parameter
// that has a fixed argument value.
List<Name> currentPosition = methprop.ParameterNames;
HashSet<Name> names = new HashSet<Name>();
for (int i = 0; i < _pArguments.carg; i++)
{
if (!(_pArguments.prgexpr[i] is ExprNamedArgumentSpecification named))
{
if (!currentPosition.IsEmpty())
{
currentPosition = currentPosition.Tail();
}
continue;
}
Name name = named.Name;
if (!methprop.ParameterNames.Contains(name))
{
if (_pInvalidSpecifiedName == null)
{
_pInvalidSpecifiedName = name;
}
return false;
}
else if (!currentPosition.Contains(name))
{
if (_pNameUsedInPositionalArgument == null)
{
_pNameUsedInPositionalArgument = name;
}
return false;
}
if (!names.Add(name))
{
if (_pDuplicateSpecifiedName == null)
{
_pDuplicateSpecifiedName = name;
}
return false;
}
}
return true;
}
// This method returns true if we have another sym to consider.
// If we've found a match in the current type, and have no more syms to consider in this type, then we
// return false.
private bool GetNextSym(CMemberLookupResults.CMethodIterator iterator)
{
if (!iterator.MoveNext(_methList.IsEmpty()))
{
return false;
}
_pCurrentSym = iterator.GetCurrentSymbol();
AggregateType type = iterator.GetCurrentType();
// If our current type is null, this is our first iteration, so set the type.
// If our current type is not null, and we've got a new type now, and we've already matched
// a symbol, then bail out.
if (_pCurrentType != type &&
_pCurrentType != null &&
!_methList.IsEmpty() &&
!_methList.Head().mpwi.GetType().isInterfaceType())
{
return false;
}
_pCurrentType = type;
// We have a new type. If this type is hidden, we need another type.
while (_HiddenTypes.Contains(_pCurrentType))
{
// Move through this type and get the next one.
for (; iterator.GetCurrentType() == _pCurrentType; iterator.MoveNext(_methList.IsEmpty())) ;
_pCurrentSym = iterator.GetCurrentSymbol();
_pCurrentType = iterator.GetCurrentType();
if (iterator.AtEnd())
{
return false;
}
}
return true;
}
private bool ConstructExpandedParameters()
{
// Deal with params.
if (_pCurrentSym == null || _pArguments == null || _pCurrentParameters == null)
{
return false;
}
if (0 != (_fBindFlags & BindingFlag.BIND_NOPARAMS))
{
return false;
}
if (!_pCurrentSym.isParamArray)
{
return false;
}
// Count the number of optionals in the method. If there are enough optionals
// and actual arguments, then proceed.
{
int numOptionals = 0;
for (int i = _pArguments.carg; i < _pCurrentSym.Params.Count; i++)
{
if (_pCurrentSym.IsParameterOptional(i))
{
numOptionals++;
}
}
if (_pArguments.carg + numOptionals < _pCurrentParameters.Count - 1)
{
return false;
}
}
Debug.Assert(_methList.IsEmpty() || _methList.Head().mpwi.MethProp() != _pCurrentSym);
// Construct the expanded params.
return _pExprBinder.TryGetExpandedParams(_pCurrentSym.Params, _pArguments.carg, out _pCurrentParameters);
}
private Result DetermineCurrentTypeArgs()
{
TypeArray typeArgs = _pGroup.TypeArgs;
// Get the type args.
if (_pCurrentSym is MethodSymbol methSym && methSym.typeVars.Count != typeArgs.Count)
{
// Can't infer if some type args are specified.
if (typeArgs.Count > 0)
{
if (!_mwtBadArity)
{
_mwtBadArity.Set(methSym, _pCurrentType);
}
return Result.Failure_NoSearchForExpanded;
}
Debug.Assert(methSym.typeVars.Count > 0);
// Try to infer. If we have an errorsym in the type arguments, we know we cant infer,
// but we want to attempt it anyway. We'll mark this as "cant infer" so that we can
// report the appropriate error, but we'll continue inferring, since we want
// error sym to go to any type.
bool inferenceSucceeded = MethodTypeInferrer.Infer(
_pExprBinder, GetSymbolLoader(), methSym, _pCurrentParameters, _pArguments,
out _pCurrentTypeArgs);
if (!inferenceSucceeded)
{
if (_results.IsBetterUninferableResult(_pCurrentTypeArgs))
{
TypeArray pTypeVars = methSym.typeVars;
if (pTypeVars != null && _pCurrentTypeArgs != null && pTypeVars.Count == _pCurrentTypeArgs.Count)
{
_mpwiCantInferInstArg.Set(methSym, _pCurrentType, _pCurrentTypeArgs);
}
else
{
_mpwiCantInferInstArg.Set(methSym, _pCurrentType, pTypeVars);
}
}
return Result.Failure_SearchForExpanded;
}
}
else
{
_pCurrentTypeArgs = typeArgs;
}
return Result.Success;
}
private bool ArgumentsAreConvertible()
{
bool containsErrorSym = false;
if (_pArguments.carg != 0)
{
UpdateArguments();
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pCurrentParameters[ivar];
bool constraintErrors = !TypeBind.CheckConstraints(GetSemanticChecker(), GetErrorContext(), var, CheckConstraintsFlags.NoErrors);
if (constraintErrors && !DoesTypeArgumentsContainErrorSym(var))
{
_mpwiParamTypeConstraints.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
return false;
}
}
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pCurrentParameters[ivar];
containsErrorSym |= DoesTypeArgumentsContainErrorSym(var);
bool fresult;
Expr pArgument = _pArguments.prgexpr[ivar];
// If we have a named argument, strip it to do the conversion.
if (pArgument is ExprNamedArgumentSpecification named)
{
pArgument = named.Value;
}
fresult = _pExprBinder.canConvert(pArgument, var);
// Mark this as a legitimate error if we didn't have any error syms.
if (!fresult && !containsErrorSym)
{
if (ivar > _nArgBest)
{
_nArgBest = ivar;
// If we already have best method for instance methods don't overwrite with extensions
if (!_results.GetBestResult())
{
_results.GetBestResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
}
}
else if (ivar == _nArgBest && _pArguments.types[ivar] != var)
{
// this is to eliminate the paranoid case of types that are equal but can't convert
// (think ErrorType != ErrorType)
// See if they just differ in out / ref.
CType argStripped = _pArguments.types[ivar] is ParameterModifierType modArg ?
modArg.GetParameterType() : _pArguments.types[ivar];
CType varStripped = var is ParameterModifierType modVar ? modVar.GetParameterType() : var;
if (argStripped == varStripped)
{
// If we already have best method for instance methods don't overwrite with extensions
if (!_results.GetBestResult())
{
_results.GetBestResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
}
}
}
if (_pCurrentSym is MethodSymbol meth)
{
// Do not store the result if we have an extension method and the instance
// parameter isn't convertible.
_results.AddInconvertibleResult(meth, _pCurrentType, _pCurrentTypeArgs);
}
return false;
}
}
}
if (containsErrorSym)
{
if (_results.IsBetterUninferableResult(_pCurrentTypeArgs) && _pCurrentSym is MethodSymbol meth)
{
// If we're an instance method then mark us down.
_results.GetUninferableResult().Set(meth, _pCurrentType, _pCurrentTypeArgs);
}
}
else
{
if (_pCurrentSym is MethodSymbol meth)
{
// Do not store the result if we have an extension method and the instance
// parameter isn't convertible.
_results.AddInconvertibleResult(meth, _pCurrentType, _pCurrentTypeArgs);
}
}
return !containsErrorSym;
}
private void UpdateArguments()
{
// Parameter types might have changed as a result of
// method type inference.
_pCurrentParameters = _pExprBinder.GetTypes().SubstTypeArray(
_pCurrentParameters, _pCurrentType, _pCurrentTypeArgs);
// It is also possible that an optional argument has changed its value
// as a result of method type inference. For example, when inferring
// from Foo(10) to Foo<T>(T t1, T t2 = default(T)), the fabricated
// argument list starts off as being (10, default(T)). After type
// inference has successfully inferred T as int, it needs to be
// transformed into (10, default(int)) before applicability checking
// notices that default(T) is not assignable to int.
if (_pArguments.prgexpr == null || _pArguments.prgexpr.Count == 0)
{
return;
}
MethodOrPropertySymbol pMethod = null;
for (int iParam = 0; iParam < _pCurrentParameters.Count; ++iParam)
{
Expr pArgument = _pArguments.prgexpr[iParam];
if (!pArgument.IsOptionalArgument)
{
continue;
}
CType pType = _pCurrentParameters[iParam];
if (pType == pArgument.Type)
{
continue;
}
// Argument has changed its type because of method type inference. Recompute it.
if (pMethod == null)
{
pMethod = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject);
Debug.Assert(pMethod != null);
}
Debug.Assert(pMethod.IsParameterOptional(iParam));
Expr pArgumentNew = GenerateOptionalArgument(GetSymbolLoader(), _pExprBinder.GetExprFactory(), pMethod, _pCurrentParameters[iParam], iParam);
_pArguments.prgexpr[iParam] = pArgumentNew;
}
}
private bool DoesTypeArgumentsContainErrorSym(CType var)
{
if (!(var is AggregateType varAgg))
{
return false;
}
TypeArray typeVars = varAgg.GetTypeArgsAll();
for (int i = 0; i < typeVars.Count; i++)
{
CType type = typeVars[i];
if (type is ErrorType)
{
return true;
}
else if (type is AggregateType)
{
// If we have an agg type sym, check if its type args have errors.
if (DoesTypeArgumentsContainErrorSym(type))
{
return true;
}
}
}
return false;
}
// ----------------------------------------------------------------------------
private void ReportErrorsOnSuccess()
{
// used for Methods and Indexers
Debug.Assert(_pGroup.SymKind == SYMKIND.SK_MethodSymbol || _pGroup.SymKind == SYMKIND.SK_PropertySymbol && 0 != (_pGroup.Flags & EXPRFLAG.EXF_INDEXER));
Debug.Assert(_pGroup.TypeArgs.Count == 0 || _pGroup.SymKind == SYMKIND.SK_MethodSymbol);
Debug.Assert(0 == (_pGroup.Flags & EXPRFLAG.EXF_USERCALLABLE) || _results.GetBestResult().MethProp().isUserCallable());
if (_pGroup.SymKind == SYMKIND.SK_MethodSymbol)
{
Debug.Assert(_results.GetBestResult().MethProp() is MethodSymbol);
if (_results.GetBestResult().TypeArgs.Count > 0)
{
// Check method type variable constraints.
TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), new MethWithInst(_results.GetBestResult()));
}
}
}
private RuntimeBinderException ReportErrorsOnFailure()
{
// First and foremost, report if the user specified a name more than once.
if (_pDuplicateSpecifiedName != null)
{
return GetErrorContext().Error(ErrorCode.ERR_DuplicateNamedArgument, _pDuplicateSpecifiedName);
}
Debug.Assert(_methList.IsEmpty());
// Report inaccessible.
if (_results.GetInaccessibleResult())
{
// We might have called this, but it is inaccessible...
return GetSemanticChecker().ReportAccessError(_results.GetInaccessibleResult(), _pExprBinder.ContextForMemberLookup(), GetTypeQualifier(_pGroup));
}
// Report bogus.
if (_mpwiBogus)
{
// We might have called this, but it is bogus...
return GetErrorContext().Error(ErrorCode.ERR_BindToBogus, _mpwiBogus);
}
bool bUseDelegateErrors = false;
Name nameErr = _pGroup.Name;
// Check for an invoke.
if (_pGroup.OptionalObject != null &&
_pGroup.OptionalObject.Type != null &&
_pGroup.OptionalObject.Type.isDelegateType() &&
_pGroup.Name == NameManager.GetPredefinedName(PredefinedName.PN_INVOKE))
{
Debug.Assert(!_results.GetBestResult() || _results.GetBestResult().MethProp().getClass().IsDelegate());
Debug.Assert(!_results.GetBestResult() || _results.GetBestResult().GetType().getAggregate().IsDelegate());
bUseDelegateErrors = true;
nameErr = _pGroup.OptionalObject.Type.getAggregate().name;
}
if (_results.GetBestResult())
{
// If we had some invalid arguments for best matching.
return ReportErrorsForBestMatching(bUseDelegateErrors);
}
if (_results.GetUninferableResult() || _mpwiCantInferInstArg)
{
if (!_results.GetUninferableResult())
{
//copy the extension method for which instance argument type inference failed
_results.GetUninferableResult().Set(_mpwiCantInferInstArg.Sym as MethodSymbol, _mpwiCantInferInstArg.GetType(), _mpwiCantInferInstArg.TypeArgs);
}
Debug.Assert(_results.GetUninferableResult().Sym is MethodSymbol);
MethWithType mwtCantInfer = new MethWithType();
mwtCantInfer.Set(_results.GetUninferableResult().Meth(), _results.GetUninferableResult().GetType());
return GetErrorContext().Error(ErrorCode.ERR_CantInferMethTypeArgs, mwtCantInfer);
}
if (_mwtBadArity)
{
int cvar = _mwtBadArity.Meth().typeVars.Count;
return GetErrorContext().Error(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _mwtBadArity, new ErrArgSymKind(_mwtBadArity.Meth()), _pArguments.carg);
}
if (_mpwiParamTypeConstraints)
{
// This will always report an error
TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), new MethWithInst(_mpwiParamTypeConstraints));
Debug.Fail("Unreachable");
return null;
}
if (_pInvalidSpecifiedName != null)
{
// Give a better message for delegate invoke.
return _pGroup.OptionalObject != null && _pGroup.OptionalObject.Type is AggregateType agg
&& agg.GetOwningAggregate().IsDelegate()
? GetErrorContext().Error(
ErrorCode.ERR_BadNamedArgumentForDelegateInvoke, agg.GetOwningAggregate().name,
_pInvalidSpecifiedName)
: GetErrorContext().Error(ErrorCode.ERR_BadNamedArgument, _pGroup.Name, _pInvalidSpecifiedName);
}
if (_pNameUsedInPositionalArgument != null)
{
return GetErrorContext().Error(ErrorCode.ERR_NamedArgumentUsedInPositional, _pNameUsedInPositionalArgument);
}
// The number of arguments must be wrong.
if (_fCandidatesUnsupported)
{
return GetErrorContext().Error(ErrorCode.ERR_BindToBogus, nameErr);
}
if (bUseDelegateErrors)
{
Debug.Assert(0 == (_pGroup.Flags & EXPRFLAG.EXF_CTOR));
return GetErrorContext().Error(ErrorCode.ERR_BadDelArgCount, nameErr, _pArguments.carg);
}
if (0 != (_pGroup.Flags & EXPRFLAG.EXF_CTOR))
{
Debug.Assert(!(_pGroup.ParentType is TypeParameterType));
return GetErrorContext().Error(ErrorCode.ERR_BadCtorArgCount, _pGroup.ParentType, _pArguments.carg);
}
return GetErrorContext().Error(ErrorCode.ERR_BadArgCount, nameErr, _pArguments.carg);
}
private RuntimeBinderException ReportErrorsForBestMatching(bool bUseDelegateErrors)
{
if (bUseDelegateErrors)
{
// Point to the Delegate, not the Invoke method
return GetErrorContext().Error(ErrorCode.ERR_BadDelArgTypes, _results.GetBestResult().GetType());
}
return GetErrorContext().Error(ErrorCode.ERR_BadArgTypes, _results.GetBestResult());
}
}
}
}
| |
using System;
using System.Diagnostics;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Provides support for converting byte sequences to <see cref="string"/>s and back again.
/// The resulting <see cref="string"/>s preserve the original byte sequences' sort order.
/// <para/>
/// The <see cref="string"/>s are constructed using a Base 8000h encoding of the original
/// binary data - each char of an encoded <see cref="string"/> represents a 15-bit chunk
/// from the byte sequence. Base 8000h was chosen because it allows for all
/// lower 15 bits of char to be used without restriction; the surrogate range
/// [U+D8000-U+DFFF] does not represent valid chars, and would require
/// complicated handling to avoid them and allow use of char's high bit.
/// <para/>
/// Although unset bits are used as padding in the final char, the original
/// byte sequence could contain trailing bytes with no set bits (null bytes):
/// padding is indistinguishable from valid information. To overcome this
/// problem, a char is appended, indicating the number of encoded bytes in the
/// final content char.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("Implement Analysis.TokenAttributes.ITermToBytesRefAttribute and store bytes directly instead. this class will be removed in Lucene 5.0")]
public sealed class IndexableBinaryStringTools
{
private static readonly CodingCase[] CODING_CASES = new CodingCase[] {
// CodingCase(int initialShift, int finalShift)
new CodingCase(7, 1),
// CodingCase(int initialShift, int middleShift, int finalShift)
new CodingCase(14, 6, 2),
new CodingCase(13, 5, 3),
new CodingCase(12, 4, 4),
new CodingCase(11, 3, 5),
new CodingCase(10, 2, 6),
new CodingCase(9, 1, 7),
new CodingCase(8, 0)
};
// Export only static methods
private IndexableBinaryStringTools()
{
}
/// <summary>
/// Returns the number of chars required to encode the given <see cref="byte"/>s.
/// </summary>
/// <param name="inputArray"> Byte sequence to be encoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of bytes in <paramref name="inputArray"/> </param>
/// <returns> The number of chars required to encode the number of <see cref="byte"/>s. </returns>
// LUCENENET specific overload for CLS compliance
public static int GetEncodedLength(byte[] inputArray, int inputOffset, int inputLength)
{
// Use long for intermediaries to protect against overflow
return (int)((8L * inputLength + 14L) / 15L) + 1;
}
/// <summary>
/// Returns the number of chars required to encode the given <see cref="sbyte"/>s.
/// </summary>
/// <param name="inputArray"> <see cref="sbyte"/> sequence to be encoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of sbytes in <paramref name="inputArray"/> </param>
/// <returns> The number of chars required to encode the number of <see cref="sbyte"/>s. </returns>
[CLSCompliant(false)]
public static int GetEncodedLength(sbyte[] inputArray, int inputOffset, int inputLength)
{
// Use long for intermediaries to protect against overflow
return (int)((8L * inputLength + 14L) / 15L) + 1;
}
/// <summary>
/// Returns the number of <see cref="byte"/>s required to decode the given char sequence.
/// </summary>
/// <param name="encoded"> Char sequence to be decoded </param>
/// <param name="offset"> Initial offset </param>
/// <param name="length"> Number of characters </param>
/// <returns> The number of <see cref="byte"/>s required to decode the given char sequence </returns>
public static int GetDecodedLength(char[] encoded, int offset, int length)
{
int numChars = length - 1;
if (numChars <= 0)
{
return 0;
}
else
{
// Use long for intermediaries to protect against overflow
long numFullBytesInFinalChar = encoded[offset + length - 1];
long numEncodedChars = numChars - 1;
return (int)((numEncodedChars * 15L + 7L) / 8L + numFullBytesInFinalChar);
}
}
/// <summary>
/// Encodes the input <see cref="byte"/> sequence into the output char sequence. Before
/// calling this method, ensure that the output array has sufficient
/// capacity by calling <see cref="GetEncodedLength(byte[], int, int)"/>.
/// </summary>
/// <param name="inputArray"> <see cref="byte"/> sequence to be encoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of bytes in <paramref name="inputArray"/> </param>
/// <param name="outputArray"> <see cref="char"/> sequence to store encoded result </param>
/// <param name="outputOffset"> Initial offset into outputArray </param>
/// <param name="outputLength"> Length of output, must be GetEncodedLength(inputArray, inputOffset, inputLength) </param>
// LUCENENET specific overload for CLS compliance
public static void Encode(byte[] inputArray, int inputOffset, int inputLength, char[] outputArray, int outputOffset, int outputLength)
{
Encode((sbyte[])(Array)inputArray, inputOffset, inputLength, outputArray, outputOffset, outputLength);
}
/// <summary>
/// Encodes the input <see cref="sbyte"/> sequence into the output char sequence. Before
/// calling this method, ensure that the output array has sufficient
/// capacity by calling <see cref="GetEncodedLength(sbyte[], int, int)"/>.
/// </summary>
/// <param name="inputArray"> <see cref="sbyte"/> sequence to be encoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of bytes in <paramref name="inputArray"/> </param>
/// <param name="outputArray"> <see cref="char"/> sequence to store encoded result </param>
/// <param name="outputOffset"> Initial offset into outputArray </param>
/// <param name="outputLength"> Length of output, must be getEncodedLength </param>
[CLSCompliant(false)]
public static void Encode(sbyte[] inputArray, int inputOffset, int inputLength, char[] outputArray, int outputOffset, int outputLength)
{
Debug.Assert(outputLength == GetEncodedLength(inputArray, inputOffset, inputLength));
if (inputLength > 0)
{
int inputByteNum = inputOffset;
int caseNum = 0;
int outputCharNum = outputOffset;
CodingCase codingCase;
for (; inputByteNum + CODING_CASES[caseNum].numBytes <= inputLength; ++outputCharNum)
{
codingCase = CODING_CASES[caseNum];
if (2 == codingCase.numBytes)
{
outputArray[outputCharNum] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + (((int)((uint)(inputArray[inputByteNum + 1] & 0xFF) >> codingCase.finalShift)) & codingCase.finalMask) & (short)0x7FFF);
} // numBytes is 3
else
{
outputArray[outputCharNum] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.middleShift) + (((int)((uint)(inputArray[inputByteNum + 2] & 0xFF) >> codingCase.finalShift)) & codingCase.finalMask) & (short)0x7FFF);
}
inputByteNum += codingCase.advanceBytes;
if (++caseNum == CODING_CASES.Length)
{
caseNum = 0;
}
}
// Produce final char (if any) and trailing count chars.
codingCase = CODING_CASES[caseNum];
if (inputByteNum + 1 < inputLength) // codingCase.numBytes must be 3
{
outputArray[outputCharNum++] = (char)((((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.middleShift)) & (short)0x7FFF);
// Add trailing char containing the number of full bytes in final char
outputArray[outputCharNum++] = (char)1;
}
else if (inputByteNum < inputLength)
{
outputArray[outputCharNum++] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.initialShift) & (short)0x7FFF);
// Add trailing char containing the number of full bytes in final char
outputArray[outputCharNum++] = caseNum == 0 ? (char)1 : (char)0;
} // No left over bits - last char is completely filled.
else
{
// Add trailing char containing the number of full bytes in final char
outputArray[outputCharNum++] = (char)1;
}
}
}
/// <summary>
/// Decodes the input <see cref="char"/> sequence into the output <see cref="byte"/> sequence. Before
/// calling this method, ensure that the output array has sufficient capacity
/// by calling <see cref="GetDecodedLength(char[], int, int)"/>.
/// </summary>
/// <param name="inputArray"> <see cref="char"/> sequence to be decoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of chars in <paramref name="inputArray"/> </param>
/// <param name="outputArray"> <see cref="byte"/> sequence to store encoded result </param>
/// <param name="outputOffset"> Initial offset into outputArray </param>
/// <param name="outputLength"> Length of output, must be
/// GetDecodedLength(inputArray, inputOffset, inputLength) </param>
// LUCENENET specific overload for CLS compliance
public static void Decode(char[] inputArray, int inputOffset, int inputLength, byte[] outputArray, int outputOffset, int outputLength)
{
Decode(inputArray, inputOffset, inputLength, (sbyte[])(Array)outputArray, outputOffset, outputLength);
}
/// <summary>
/// Decodes the input char sequence into the output sbyte sequence. Before
/// calling this method, ensure that the output array has sufficient capacity
/// by calling <see cref="GetDecodedLength(char[], int, int)"/>.
/// </summary>
/// <param name="inputArray"> <see cref="char"/> sequence to be decoded </param>
/// <param name="inputOffset"> Initial offset into <paramref name="inputArray"/> </param>
/// <param name="inputLength"> Number of chars in <paramref name="inputArray"/> </param>
/// <param name="outputArray"> <see cref="byte"/> sequence to store encoded result </param>
/// <param name="outputOffset"> Initial offset into outputArray </param>
/// <param name="outputLength"> Length of output, must be
/// GetDecodedLength(inputArray, inputOffset, inputLength) </param>
[CLSCompliant(false)]
public static void Decode(char[] inputArray, int inputOffset, int inputLength, sbyte[] outputArray, int outputOffset, int outputLength)
{
Debug.Assert(outputLength == GetDecodedLength(inputArray, inputOffset, inputLength));
int numInputChars = inputLength - 1;
int numOutputBytes = outputLength;
if (numOutputBytes > 0)
{
int caseNum = 0;
int outputByteNum = outputOffset;
int inputCharNum = inputOffset;
short inputChar;
CodingCase codingCase;
for (; inputCharNum < numInputChars - 1; ++inputCharNum)
{
codingCase = CODING_CASES[caseNum];
inputChar = (short)inputArray[inputCharNum];
if (2 == codingCase.numBytes)
{
if (0 == caseNum)
{
outputArray[outputByteNum] = (sbyte)((short)((ushort)inputChar >> codingCase.initialShift));
}
else
{
outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.initialShift));
}
outputArray[outputByteNum + 1] = (sbyte)((inputChar & codingCase.finalMask) << codingCase.finalShift);
} // numBytes is 3
else
{
outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.initialShift));
outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.middleMask) >> codingCase.middleShift));
outputArray[outputByteNum + 2] = (sbyte)((inputChar & codingCase.finalMask) << codingCase.finalShift);
}
outputByteNum += codingCase.advanceBytes;
if (++caseNum == CODING_CASES.Length)
{
caseNum = 0;
}
}
// Handle final char
inputChar = (short)inputArray[inputCharNum];
codingCase = CODING_CASES[caseNum];
if (0 == caseNum)
{
outputArray[outputByteNum] = 0;
}
outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.initialShift));
int bytesLeft = numOutputBytes - outputByteNum;
if (bytesLeft > 1)
{
if (2 == codingCase.numBytes)
{
outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.finalMask) >> codingCase.finalShift));
} // numBytes is 3
else
{
outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.middleMask) >> codingCase.middleShift));
if (bytesLeft > 2)
{
outputArray[outputByteNum + 2] = (sbyte)((inputChar & codingCase.finalMask) << codingCase.finalShift);
}
}
}
}
}
internal class CodingCase
{
internal int numBytes, initialShift, middleShift, finalShift, advanceBytes = 2;
internal short middleMask, finalMask;
internal CodingCase(int initialShift, int middleShift, int finalShift)
{
this.numBytes = 3;
this.initialShift = initialShift;
this.middleShift = middleShift;
this.finalShift = finalShift;
this.finalMask = (short)((int)((uint)(short)0xFF >> finalShift));
this.middleMask = (short)((short)0xFF << middleShift);
}
internal CodingCase(int initialShift, int finalShift)
{
this.numBytes = 2;
this.initialShift = initialShift;
this.finalShift = finalShift;
this.finalMask = (short)((int)((uint)(short)0xFF >> finalShift));
if (finalShift != 0)
{
advanceBytes = 1;
}
}
}
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections.Generic;
using SFML.Window;
namespace SFML
{
namespace Graphics
{
////////////////////////////////////////////////////////////
/// <summary>
/// Wrapper for pixel shaders
/// </summary>
////////////////////////////////////////////////////////////
public class Shader : ObjectBase
{
////////////////////////////////////////////////////////////
/// <summary>
/// Special type that can be passed to SetParameter,
/// and that represents the texture of the object being drawn
/// </summary>
////////////////////////////////////////////////////////////
public class CurrentTextureType {}
////////////////////////////////////////////////////////////
/// <summary>
/// Special value that can be passed to SetParameter,
/// and that represents the texture of the object being drawn
/// </summary>
////////////////////////////////////////////////////////////
public static readonly CurrentTextureType CurrentTexture = null;
////////////////////////////////////////////////////////////
/// <summary>
/// Load the vertex and fragment shaders from files
///
/// This function can load both the vertex and the fragment
/// shaders, or only one of them: pass NULL if you don't want to load
/// either the vertex shader or the fragment shader.
/// The sources must be text files containing valid shaders
/// in GLSL language. GLSL is a C-like language dedicated to
/// OpenGL shaders; you'll probably need to read a good documentation
/// for it before writing your own shaders.
/// </summary>
/// <param name="vertexShaderFilename">Path of the vertex shader file to load, or null to skip this shader</param>
/// <param name="fragmentShaderFilename">Path of the fragment shader file to load, or null to skip this shader</param>
/// <exception cref="LoadingFailedException" />
////////////////////////////////////////////////////////////
public Shader(string vertexShaderFilename, string fragmentShaderFilename) :
base(sfShader_createFromFile(vertexShaderFilename, fragmentShaderFilename))
{
if (CPointer == IntPtr.Zero)
throw new LoadingFailedException("shader", vertexShaderFilename + " " + fragmentShaderFilename);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Load both the vertex and fragment shaders from custom streams
///
/// This function can load both the vertex and the fragment
/// shaders, or only one of them: pass NULL if you don't want to load
/// either the vertex shader or the fragment shader.
/// The sources must be valid shaders in GLSL language. GLSL is
/// a C-like language dedicated to OpenGL shaders; you'll
/// probably need to read a good documentation for it before
/// writing your own shaders.
/// </summary>
/// <param name="vertexShaderStream">Source stream to read the vertex shader from, or null to skip this shader</param>
/// <param name="fragmentShaderStream">Source stream to read the fragment shader from, or null to skip this shader</param>
/// <exception cref="LoadingFailedException" />
////////////////////////////////////////////////////////////
public Shader(Stream vertexShaderStream, Stream fragmentShaderStream) :
base(IntPtr.Zero)
{
StreamAdaptor vertexAdaptor = new StreamAdaptor(vertexShaderStream);
StreamAdaptor fragmentAdaptor = new StreamAdaptor(fragmentShaderStream);
SetThis(sfShader_createFromStream(vertexAdaptor.InputStreamPtr, fragmentAdaptor.InputStreamPtr));
vertexAdaptor.Dispose();
fragmentAdaptor.Dispose();
if (CPointer == IntPtr.Zero)
throw new LoadingFailedException("shader");
}
////////////////////////////////////////////////////////////
/// <summary>
/// Load both the vertex and fragment shaders from source codes in memory
///
/// This function can load both the vertex and the fragment
/// shaders, or only one of them: pass NULL if you don't want to load
/// either the vertex shader or the fragment shader.
/// The sources must be valid shaders in GLSL language. GLSL is
/// a C-like language dedicated to OpenGL shaders; you'll
/// probably need to read a good documentation for it before
/// writing your own shaders.
/// </summary>
/// <param name="vertexShader">String containing the source code of the vertex shader</param>
/// <param name="fragmentShader">String containing the source code of the fragment shader</param>
/// <returns>New shader instance</returns>
/// <exception cref="LoadingFailedException" />
////////////////////////////////////////////////////////////
public static Shader FromString(string vertexShader, string fragmentShader)
{
IntPtr ptr = sfShader_createFromMemory(vertexShader, fragmentShader);
if (ptr == IntPtr.Zero)
throw new LoadingFailedException("shader");
return new Shader(ptr);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change a float parameter of the shader
///
/// "name" is the name of the variable to change in the shader.
/// The corresponding parameter in the shader must be a float
/// (float GLSL type).
/// </summary>
///
/// <param name="name">Name of the parameter in the shader</param>
/// <param name="x">Value to assign</param>
///
////////////////////////////////////////////////////////////
public void SetParameter(string name, float x)
{
sfShader_setFloatParameter(CPointer, name, x);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change a 2-components vector parameter of the shader
///
/// "name" is the name of the variable to change in the shader.
/// The corresponding parameter in the shader must be a 2x1 vector
/// (vec2 GLSL type).
/// </summary>
/// <param name="name">Name of the parameter in the shader</param>
/// <param name="x">First component of the value to assign</param>
/// <param name="y">Second component of the value to assign</param>
////////////////////////////////////////////////////////////
public void SetParameter(string name, float x, float y)
{
sfShader_setFloat2Parameter(CPointer, name, x, y);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change a 3-components vector parameter of the shader
///
/// "name" is the name of the variable to change in the shader.
/// The corresponding parameter in the shader must be a 3x1 vector
/// (vec3 GLSL type).
/// </summary>
/// <param name="name">Name of the parameter in the shader</param>
/// <param name="x">First component of the value to assign</param>
/// <param name="y">Second component of the value to assign</param>
/// <param name="z">Third component of the value to assign</param>
////////////////////////////////////////////////////////////
public void SetParameter(string name, float x, float y, float z)
{
sfShader_setFloat3Parameter(CPointer, name, x, y, z);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change a 4-components vector parameter of the shader
///
/// "name" is the name of the variable to change in the shader.
/// The corresponding parameter in the shader must be a 4x1 vector
/// (vec4 GLSL type).
/// </summary>
/// <param name="name">Name of the parameter in the shader</param>
/// <param name="x">First component of the value to assign</param>
/// <param name="y">Second component of the value to assign</param>
/// <param name="z">Third component of the value to assign</param>
/// <param name="w">Fourth component of the value to assign</param>
////////////////////////////////////////////////////////////
public void SetParameter(string name, float x, float y, float z, float w)
{
sfShader_setFloat4Parameter(CPointer, name, x, y, z, w);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change a 2-components vector parameter of the shader
///
/// "name" is the name of the variable to change in the shader.
/// The corresponding parameter in the shader must be a 2x1 vector
/// (vec2 GLSL type).
/// </summary>
/// <param name="name">Name of the parameter in the shader</param>
/// <param name="vector">Vector to assign</param>
////////////////////////////////////////////////////////////
public void SetParameter(string name, Vector2f vector)
{
SetParameter(name, vector.X, vector.Y);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change a color parameter of the shader
///
/// "name" is the name of the variable to change in the shader.
/// The corresponding parameter in the shader must be a 4x1 vector
/// (vec4 GLSL type).
/// </summary>
/// <param name="name">Name of the parameter in the shader</param>
/// <param name="color">Color to assign</param>
////////////////////////////////////////////////////////////
public void SetParameter(string name, Color color)
{
sfShader_setColorParameter(CPointer, name, color);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change a matrix parameter of the shader
///
/// "name" is the name of the variable to change in the shader.
/// The corresponding parameter in the shader must be a 4x4 matrix
/// (mat4 GLSL type).
/// </summary>
/// <param name="name">Name of the parameter in the shader</param>
/// <param name="transform">Transform to assign</param>
////////////////////////////////////////////////////////////
public void SetParameter(string name, Transform transform)
{
sfShader_setTransformParameter(CPointer, name, transform);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change a texture parameter of the shader
///
/// "name" is the name of the variable to change in the shader.
/// The corresponding parameter in the shader must be a 2D texture
/// (sampler2D GLSL type).
///
/// It is important to note that \a texture must remain alive as long
/// as the shader uses it, no copy is made internally.
///
/// To use the texture of the object being draw, which cannot be
/// known in advance, you can pass the special value
/// Shader.CurrentTexture.
/// </summary>
/// <param name="name">Name of the texture in the shader</param>
/// <param name="texture">Texture to assign</param>
////////////////////////////////////////////////////////////
public void SetParameter(string name, Texture texture)
{
myTextures[name] = texture;
sfShader_setTextureParameter(CPointer, name, texture.CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change a texture parameter of the shader
///
/// This overload maps a shader texture variable to the
/// texture of the object being drawn, which cannot be
/// known in advance. The second argument must be
/// sf::Shader::CurrentTexture.
/// The corresponding parameter in the shader must be a 2D texture
/// (sampler2D GLSL type).
/// </summary>
/// <param name="name">Name of the texture in the shader</param>
/// <param name="current">Always pass the spacial value Shader.CurrentTexture</param>
////////////////////////////////////////////////////////////
public void SetParameter(string name, CurrentTextureType current)
{
sfShader_setCurrentTextureParameter(CPointer, name);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Bind a shader for rendering
/// </summary>
/// <param name="shader">Shader to bind (can be null to use no shader)</param>
////////////////////////////////////////////////////////////
public static void Bind(Shader shader)
{
sfShader_bind(shader != null ? shader.CPointer : IntPtr.Zero);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Tell whether or not the system supports shaders.
///
/// This property should always be checked before using
/// the shader features. If it returns false, then
/// any attempt to use Shader will fail.
/// </summary>
////////////////////////////////////////////////////////////
public static bool IsAvailable
{
get {return sfShader_isAvailable();}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[Shader]";
}
////////////////////////////////////////////////////////////
/// <summary>
/// Handle the destruction of the object
/// </summary>
/// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param>
////////////////////////////////////////////////////////////
protected override void Destroy(bool disposing)
{
if (!disposing)
Context.Global.SetActive(true);
myTextures.Clear();
sfShader_destroy(CPointer);
if (!disposing)
Context.Global.SetActive(false);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the shader from a pointer
/// </summary>
/// <param name="ptr">Pointer to the shader instance</param>
////////////////////////////////////////////////////////////
public Shader(IntPtr ptr) :
base(ptr)
{
}
Dictionary<string, Texture> myTextures = new Dictionary<string, Texture>();
#region Imports
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfShader_createFromFile(string vertexShaderFilename, string fragmentShaderFilename);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfShader_createFromMemory(string vertexShader, string fragmentShader);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfShader_createFromStream(IntPtr vertexShaderStream, IntPtr fragmentShaderStream);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShader_destroy(IntPtr shader);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShader_setFloatParameter(IntPtr shader, string name, float x);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShader_setFloat2Parameter(IntPtr shader, string name, float x, float y);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShader_setFloat3Parameter(IntPtr shader, string name, float x, float y, float z);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShader_setFloat4Parameter(IntPtr shader, string name, float x, float y, float z, float w);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShader_setColorParameter(IntPtr shader, string name, Color color);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShader_setTransformParameter(IntPtr shader, string name, Transform transform);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShader_setTextureParameter(IntPtr shader, string name, IntPtr texture);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShader_setCurrentTextureParameter(IntPtr shader, string name);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShader_bind(IntPtr shader);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfShader_isAvailable();
#endregion
}
}
}
| |
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace OfficeDevPnP.Core.Tools.UnitTest.PnPBuildExtensions
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
/// <summary>
/// ToInt64(System.Double)
/// </summary>
public class ConvertToInt32_5
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ToInt32(0<double<0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d >= 0.5);
int actual = Convert.ToInt32(d);
int expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt32(1>double>=0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d < 0.5);
int actual = Convert.ToInt32(d);
int expected = 1;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt32(0)");
try
{
double d = 0d;
int actual = Convert.ToInt32(d);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt32(int32.max)");
try
{
double d = Int32.MaxValue;
int actual = Convert.ToInt32(d);
int expected = Int32.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt32(int32.min)");
try
{
double d = Int32.MinValue;
int actual = Convert.ToInt32(d);
int expected = Int32.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("005.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is not thrown.");
try
{
double d = (double)Int32.MaxValue + 1;
int i = Convert.ToInt32(d);
TestLibrary.TestFramework.LogError("101.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is not thrown.");
try
{
double d = (double)Int32.MinValue - 1;
int i = Convert.ToInt32(d);
TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToInt32_5 test = new ConvertToInt32_5();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt32_5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using Cosmos.Debug.Common;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Shell = Microsoft.VisualStudio.Shell;
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Collections.Specialized;
using System.Windows.Forms;
namespace Cosmos.Debug.VSDebugEngine {
// AD7Engine is the primary entrypoint object for the the debugger.
//
// It implements:
//
// IDebugEngine2: This interface represents a debug engine (DE). It is used to manage various aspects of a debugging session,
// from creating breakpoints to setting and clearing exceptions.
//
// IDebugEngineLaunch2: Used by a debug engine (DE) to launch and terminate programs.
//
// IDebugProgram3: This interface represents a program that is running in a process. Since this engine only debugs one process at a time and each
// process only contains one program, it is implemented on the engine.
//
// IDebugEngineProgram2: This interface provides simultanious debugging of multiple threads in a debuggee.
[ComVisible(true)]
[Guid("8355452D-6D2F-41b0-89B8-BB2AA2529E94")]
public class AD7Engine : IDebugEngine2, IDebugEngineLaunch2, IDebugProgram3, IDebugEngineProgram2 {
internal IDebugProgram2 mProgram;
// We only support one process, so we just keep a ref to it and save a lot of accounting.
internal AD7Process mProcess;
// A unique identifier for the program being debugged.
Guid mProgramID;
public const string ID = "FA1DA3A6-66FF-4c65-B077-E65F7164EF83";
internal AD7Module mModule;
private AD7Thread mThread;
private AD7ProgramNode mProgNode;
public IList<IDebugBoundBreakpoint2> Breakpoints = null;
// This object facilitates calling from this thread into the worker thread of the engine. This is necessary because the Win32 debugging
// api requires thread affinity to several operations.
// This object manages breakpoints in the sample engine.
protected BreakpointManager mBPMgr;
public BreakpointManager BPMgr {
get { return mBPMgr; }
}
public AD7Engine() {
mBPMgr = new BreakpointManager(this);
}
// Used to send events to the debugger. Some examples of these events are thread create, exception thrown, module load.
EngineCallback mEngineCallback;
internal EngineCallback Callback {
get { return mEngineCallback; }
}
#region Startup Methods
// During startup these methods are called in this order:
// -LaunchSuspended
// -ResumeProcess
// -Attach - Triggered by Attach
int IDebugEngineLaunch2.LaunchSuspended(string aPszServer, IDebugPort2 aPort, string aDebugInfo
, string aArgs, string aDir, string aEnv, string aOptions, enum_LAUNCH_FLAGS aLaunchFlags
, uint aStdInputHandle, uint aStdOutputHandle, uint hStdError, IDebugEventCallback2 aAD7Callback
, out IDebugProcess2 oProcess) {
// Launches a process by means of the debug engine.
// Normally, Visual Studio launches a program using the IDebugPortEx2::LaunchSuspended method and then attaches the debugger
// to the suspended program. However, there are circumstances in which the debug engine may need to launch a program
// (for example, if the debug engine is part of an interpreter and the program being debugged is an interpreted language),
// in which case Visual Studio uses the IDebugEngineLaunch2::LaunchSuspended method
// The IDebugEngineLaunch2::ResumeProcess method is called to start the process after the process has been successfully launched in a suspended state.
oProcess = null;
try {
mEngineCallback = new EngineCallback(this, aAD7Callback);
var xDebugInfo = new NameValueCollection();
NameValueCollectionHelper.LoadFromString(xDebugInfo, aDebugInfo);
//TODO: In the future we might support command line args for kernel etc
//string xCmdLine = EngineUtils.BuildCommandLine(exe, args);
//var processLaunchInfo = new ProcessLaunchInfo(exe, xCmdLine, dir, env, options, launchFlags, hStdInput, hStdOutput, hStdError);
AD7EngineCreateEvent.Send(this);
oProcess = mProcess = new AD7Process(xDebugInfo, mEngineCallback, this, aPort);
// We only support one process, so just use its ID for the program ID
mProgramID = mProcess.ID;
//AD7ThreadCreateEvent.Send(this, xProcess.Thread);
mModule = new AD7Module();
mProgNode = new AD7ProgramNode(mProcess.PhysID);
} catch (Exception e) {
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
int IDebugEngine2.Attach(IDebugProgram2[] rgpPrograms, IDebugProgramNode2[] rgpProgramNodes, uint aCeltPrograms, IDebugEventCallback2 ad7Callback, enum_ATTACH_REASON dwReason) {
// Attach the debug engine to a program.
//
// Attach can either be called to attach to a new process, or to complete an attach
// to a launched process.
// So could we simplify and move code from LaunchSuspended to here and maybe even
// eliminate the debughost? Although I supposed DebugHost has some other uses as well.
if (aCeltPrograms != 1) {
System.Diagnostics.Debug.Fail("Cosmos Debugger only supports one debug target at a time.");
throw new ArgumentException();
}
try {
EngineUtils.RequireOk(rgpPrograms[0].GetProgramId(out mProgramID));
mProgram = rgpPrograms[0];
AD7EngineCreateEvent.Send(this);
AD7ProgramCreateEvent.Send(this);
AD7ModuleLoadEvent.Send(this, mModule, true);
// Dummy main thread
// We dont support threads yet, but the debugger expects threads.
// So we create a dummy object to represente our only "thread".
mThread = new AD7Thread(this, mProcess);
AD7LoadCompleteEvent.Send(this, mThread);
} catch (Exception e) {
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
int IDebugEngineLaunch2.ResumeProcess(IDebugProcess2 aProcess) {
// Resume a process launched by IDebugEngineLaunch2.LaunchSuspended
try {
// Send a program node to the SDM. This will cause the SDM to turn around and call IDebugEngine2.Attach
// which will complete the hookup with AD7
var xProcess = aProcess as AD7Process;
if (xProcess == null) {
return VSConstants.E_INVALIDARG;
}
IDebugPort2 xPort;
EngineUtils.RequireOk(aProcess.GetPort(out xPort));
var xDefPort = (IDebugDefaultPort2)xPort;
IDebugPortNotify2 xNotify;
EngineUtils.RequireOk(xDefPort.GetPortNotify(out xNotify));
// This triggers Attach
EngineUtils.RequireOk(xNotify.AddProgramNode(mProgNode));
Callback.OnModuleLoad(mModule);
Callback.OnSymbolSearch(mModule, xProcess.mISO.Replace("iso", "pdb"), enum_MODULE_INFO_FLAGS.MIF_SYMBOLS_LOADED);
// Important!
//
// This call triggers setting of breakpoints that exist before run.
// So it must be called before we resume the process.
// If not called VS will call it after our 3 startup events, but thats too late.
// This line was commented out in earlier Cosmos builds and caused problems with
// breakpoints and timing.
Callback.OnThreadStart(mThread);
// Not sure what this does exactly. It was commented out before
// but so was a lot of stuff we actually needed. If its uncommented it
// throws:
// "Operation is not valid due to the current state of the object."
//AD7EntrypointEvent.Send(this);
// Now finally release our process to go after breakpoints are set
mProcess.ResumeFromLaunch();
} catch (Exception e) {
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
#endregion
#region Other implemented support methods
int IDebugEngine2.ContinueFromSynchronousEvent(IDebugEvent2 aEvent) {
// Called by the SDM to indicate that a synchronous debug event, previously sent by the DE to the SDM,
// was received and processed. The only event the engine sends in this fashion is Program Destroy.
// It responds to that event by shutting down the engine.
//
// This is used in some cases - I set a BP here and it does get hit sometime during breakpoints
// being triggered for example.
try {
if (aEvent is AD7ProgramDestroyEvent) {
mEngineCallback = null;
mProgramID = Guid.Empty;
mThread = null;
mProgNode = null;
} else {
System.Diagnostics.Debug.Fail("Unknown synchronious event");
}
} catch (Exception e) {
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
int IDebugEngine2.CreatePendingBreakpoint(IDebugBreakpointRequest2 pBPRequest, out IDebugPendingBreakpoint2 ppPendingBP) {
// Creates a pending breakpoint in the engine. A pending breakpoint is contains all the information needed to bind a breakpoint to
// a location in the debuggee.
ppPendingBP = null;
try {
BPMgr.CreatePendingBreakpoint(pBPRequest, out ppPendingBP);
} catch (Exception e) {
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
int IDebugEngine2.DestroyProgram(IDebugProgram2 pProgram) {
// Informs a DE that the program specified has been atypically terminated and that the DE should
// clean up all references to the program and send a program destroy event.
//
// Tell the SDM that the engine knows that the program is exiting, and that the
// engine will send a program destroy. We do this because the Win32 debug api will always
// tell us that the process exited, and otherwise we have a race condition.
return AD7_HRESULT.E_PROGRAM_DESTROY_PENDING;
}
int IDebugEngine2.GetEngineId(out Guid oGuidEngine) {
// Gets the GUID of the DebugEngine.
oGuidEngine = new Guid(ID);
return VSConstants.S_OK;
}
int IDebugEngineLaunch2.TerminateProcess(IDebugProcess2 aProcess) {
// This function is used to terminate a process that the SampleEngine launched
// The debugger will call IDebugEngineLaunch2::CanTerminateProcess before calling this method.
try {
mProcess.Terminate();
mEngineCallback.OnProcessExit(0);
mProgram = null;
} catch (Exception e) {
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
public int Continue(IDebugThread2 aThread) {
// We don't appear to use or support this currently.
// Continue is called from the SDM when it wants execution to continue in the debugee
// but have stepping state remain. An example is when a tracepoint is executed,
// and the debugger does not want to actually enter break mode.
var xThread = (AD7Thread)aThread;
//if (AfterBreak) {
//Callback.OnBreak(xThread);
//}
return VSConstants.S_OK;
}
int IDebugEngine2.CauseBreak() {
// Requests that all programs being debugged by this DE stop execution the next time one of their threads attempts to run.
// This is normally called in response to the user clicking on the pause button in the debugger.
// When the break is complete, an AsyncBreakComplete event will be sent back to the debugger.
return ((IDebugProgram2)this).CauseBreak();
}
public int Detach() {
// Detach is called when debugging is stopped and the process was attached to (as opposed to launched)
// or when one of the Detach commands are executed in the UI.
BPMgr.ClearBoundBreakpoints();
return VSConstants.S_OK;
}
public int EnumModules(out IEnumDebugModules2 ppEnum) {
// EnumModules is called by the debugger when it needs to enumerate the modules in the program.
ppEnum = new AD7ModuleEnum(new[] { mModule });
return VSConstants.S_OK;
}
public int EnumThreads(out IEnumDebugThreads2 ppEnum) {
// EnumThreads is called by the debugger when it needs to enumerate the threads in the program.
ppEnum = new AD7ThreadEnum(new[] { mThread });
return VSConstants.S_OK;
}
public int GetEngineInfo(out string engineName, out Guid engineGuid) {
// Gets the name and identifier of the debug engine (DE) running this program.
engineName = ResourceStrings.EngineName;
engineGuid = new Guid(AD7Engine.ID);
return VSConstants.S_OK;
}
public int GetProgramId(out Guid aGuidProgramId) {
// Gets a GUID for this program. A debug engine (DE) must return the program identifier originally passed to the IDebugProgramNodeAttach2::OnAttach
// or IDebugEngine2::Attach methods. This allows identification of the program across debugger components.
aGuidProgramId = mProgramID;
return VSConstants.S_OK;
}
public int Step(IDebugThread2 pThread, enum_STEPKIND sk, enum_STEPUNIT Step) {
// This method is deprecated. Use the IDebugProcess3::Step method instead.
mProcess.Step((enum_STEPKIND)sk);
return VSConstants.S_OK;
}
public int ExecuteOnThread(IDebugThread2 pThread) {
// ExecuteOnThread is called when the SDM wants execution to continue and have
// stepping state cleared.
mProcess.Continue();
return VSConstants.S_OK;
}
#endregion
#region Unimplemented methods
// Gets the name of the program.
// The name returned by this method is always a friendly, user-displayable name that describes the program.
public int GetName(out string programName) {
// The Sample engine uses default transport and doesn't need to customize the name of the program,
// so return NULL.
programName = null;
return VSConstants.S_OK;
}
// This method gets the Edit and Continue (ENC) update for this program. A custom debug engine always returns E_NOTIMPL
public int GetENCUpdate(out object update) {
// The sample engine does not participate in managed edit & continue.
update = null;
return VSConstants.S_OK;
}
// Removes the list of exceptions the IDE has set for a particular run-time architecture or language.
// We dont support exceptions in the debuggee so this method is not actually implemented.
int IDebugEngine2.RemoveAllSetExceptions(ref Guid guidType) {
return VSConstants.S_OK;
}
// Removes the specified exception so it is no longer handled by the debug engine.
// The sample engine does not support exceptions in the debuggee so this method is not actually implemented.
int IDebugEngine2.RemoveSetException(EXCEPTION_INFO[] pException) {
// We stop on all exceptions.
return VSConstants.S_OK;
}
// Specifies how the DE should handle a given exception.
// We dont support exceptions in the debuggee so this method is not actually implemented.
int IDebugEngine2.SetException(EXCEPTION_INFO[] pException) {
return VSConstants.S_OK;
}
// Sets the locale of the DE.
// This method is called by the session debug manager (SDM) to propagate the locale settings of the IDE so that
// strings returned by the DE are properly localized. The sample engine is not localized so this is not implemented.
int IDebugEngine2.SetLocale(ushort wLangID) {
return VSConstants.S_OK;
}
// A metric is a registry value used to change a debug engine's behavior or to advertise supported functionality.
// This method can forward the call to the appropriate form of the Debugging SDK Helpers function, SetMetric.
int IDebugEngine2.SetMetric(string pszMetric, object varValue) {
// The sample engine does not need to understand any metric settings.
return VSConstants.S_OK;
}
// Sets the registry root currently in use by the DE. Different installations of Visual Studio can change where their registry information is stored
// This allows the debugger to tell the engine where that location is.
int IDebugEngine2.SetRegistryRoot(string pszRegistryRoot) {
// The sample engine does not read settings from the registry.
return VSConstants.S_OK;
}
public string GetAddressDescription(uint ip) {
// DebuggedModule module = m_debuggedProcess.ResolveAddress(ip);
return "";// EngineUtils.GetAddressDescription(module, ip);
}
// Determines if a debug engine (DE) can detach from the program.
public int CanDetach() {
// We always support detach
return VSConstants.S_OK;
}
// The debugger calls CauseBreak when the user clicks on the pause button in VS. The debugger should respond by entering
// breakmode.
public int CauseBreak() {
return this.mProcess.CauseBreak();
}
// EnumCodePaths is used for the step-into specific feature -- right click on the current statment and decide which
// function to step into. This is not something that the SampleEngine supports.
public int EnumCodePaths(string hint, IDebugCodeContext2 start, IDebugStackFrame2 frame, int fSource, out IEnumCodePaths2 pathEnum, out IDebugCodeContext2 safetyContext) {
pathEnum = null;
safetyContext = null;
return VSConstants.E_NOTIMPL;
}
// The properties returned by this method are specific to the program. If the program needs to return more than one property,
// then the IDebugProperty2 object returned by this method is a container of additional properties and calling the
// IDebugProperty2::EnumChildren method returns a list of all properties.
// A program may expose any number and type of additional properties that can be described through the IDebugProperty2 interface.
// An IDE might display the additional program properties through a generic property browser user interface.
// The sample engine does not support this
public int GetDebugProperty(out IDebugProperty2 ppProperty) {
throw new NotImplementedException();
}
// The debugger calls this when it needs to obtain the IDebugDisassemblyStream2 for a particular code-context.
// The sample engine does not support dissassembly so it returns E_NOTIMPL
public int GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 codeContext, out IDebugDisassemblyStream2 disassemblyStream) {
disassemblyStream = null;
return VSConstants.E_NOTIMPL;
}
// The memory bytes as represented by the IDebugMemoryBytes2 object is for the program's image in memory and not any memory
// that was allocated when the program was executed.
public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) {
throw new Exception("The method or operation is not implemented.");
}
// Writes a dump to a file.
public int WriteDump(enum_DUMPTYPE DUMPTYPE, string pszDumpUrl) {
// The sample debugger does not support creating or reading mini-dumps.
return VSConstants.E_NOTIMPL;
}
// Stops all threads running in this program.
// This method is called when this program is being debugged in a multi-program environment. When a stopping event from some other program
// is received, this method is called on this program. The implementation of this method should be asynchronous;
// that is, not all threads should be required to be stopped before this method returns. The implementation of this method may be
// as simple as calling the IDebugProgram2::CauseBreak method on this program.
//
// The sample engine only supports debugging native applications and therefore only has one program per-process
public int Stop() {
throw new Exception("The method or operation is not implemented.");
}
// WatchForExpressionEvaluationOnThread is used to cooperate between two different engines debugging
// the same process. The sample engine doesn't cooperate with other engines, so it has nothing
// to do here.
public int WatchForExpressionEvaluationOnThread(IDebugProgram2 pOriginatingProgram, uint dwTid, uint dwEvalFlags, IDebugEventCallback2 pExprCallback, int fWatch) {
return VSConstants.S_OK;
}
// WatchForThreadStep is used to cooperate between two different engines debugging the same process.
// The sample engine doesn't cooperate with other engines, so it has nothing to do here.
public int WatchForThreadStep(IDebugProgram2 pOriginatingProgram, uint dwTid, int fWatch, uint dwFrame) {
return VSConstants.S_OK;
}
// Terminates the program.
public int Terminate() {
mProgram = null;
// Because the sample engine is a native debugger, it implements IDebugEngineLaunch2, and will terminate
// the process in IDebugEngineLaunch2.TerminateProcess
return VSConstants.S_OK;
}
// Enumerates the code contexts for a given position in a source file.
public int EnumCodeContexts(IDebugDocumentPosition2 pDocPos, out IEnumDebugCodeContexts2 ppEnum) {
throw new NotImplementedException();
}
// Determines if a process can be terminated.
int IDebugEngineLaunch2.CanTerminateProcess(IDebugProcess2 process) {
return VSConstants.S_OK;
//try {
// int processId = EngineUtils.GetProcessId(process);
// //if (processId == m_debuggedProcess.Id)
// {
// return VSConstants.S_OK;
// }
// //else
// {
// //return VSConstants.S_FALSE;
// }
//}
// //catch (ComponentException e)
// //{
// // return e.HResult;
// //}
//catch (Exception e) {
// return EngineUtils.UnexpectedException(e);
//}
}
#endregion
#region Deprecated interface methods
// These methods are not called by the Visual Studio debugger, so they don't need to be implemented
int IDebugEngine2.EnumPrograms(out IEnumDebugPrograms2 programs) {
System.Diagnostics.Debug.Fail("This function is not called by the debugger");
programs = null;
return VSConstants.E_NOTIMPL;
}
public int Attach(IDebugEventCallback2 pCallback) {
System.Diagnostics.Debug.Fail("This function is not called by the debugger");
return VSConstants.E_NOTIMPL;
}
public int GetProcess(out IDebugProcess2 process) {
System.Diagnostics.Debug.Fail("This function is not called by the debugger");
process = null;
return VSConstants.E_NOTIMPL;
}
public int Execute() {
System.Diagnostics.Debug.Fail("This function is not called by the debugger.");
return VSConstants.E_NOTIMPL;
}
#endregion
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_FULL_CONSOLE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using IronPython.Compiler;
using IronPython.Modules;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting.Shell;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
namespace IronPython.Hosting {
/// <summary>
/// A simple Python command-line should mimic the standard python.exe
/// </summary>
public sealed class PythonCommandLine : CommandLine {
private PythonContext PythonContext {
get { return (PythonContext)Language; }
}
private new PythonConsoleOptions Options { get { return (PythonConsoleOptions)base.Options; } }
public PythonCommandLine() {
}
protected override string/*!*/ Logo {
get {
return GetLogoDisplay();
}
}
/// <summary>
/// Returns the display look for IronPython.
///
/// The returned string uses This \n instead of Environment.NewLine for it's line seperator
/// because it is intended to be outputted through the Python I/O system.
/// </summary>
public static string GetLogoDisplay() {
return PythonContext.GetVersionString() +
"\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n";
}
private int GetEffectiveExitCode(SystemExitException/*!*/ e) {
object nonIntegerCode;
int exitCode = e.GetExitCode(out nonIntegerCode);
if (nonIntegerCode != null) {
Console.WriteLine(nonIntegerCode.ToString(), Style.Error);
}
return exitCode;
}
protected override void Shutdown() {
try {
Language.Shutdown();
} catch (Exception e) {
Console.WriteLine("", Style.Error);
Console.WriteLine("Error in sys.exitfunc:", Style.Error);
Console.Write(Language.FormatException(e), Style.Error);
}
}
protected override int Run() {
if (Options.ModuleToRun != null) {
// PEP 338 support - http://www.python.org/dev/peps/pep-0338
// This requires the presence of the Python standard library or
// an equivalent runpy.py which defines a run_module method.
// import the runpy module
object runpy, runMod;
try {
runpy = Importer.Import(
PythonContext.SharedContext,
"runpy",
PythonTuple.EMPTY,
0
);
} catch (Exception) {
Console.WriteLine("Could not import runpy module", Style.Error);
return -1;
}
// get the run_module method
try {
runMod = PythonOps.GetBoundAttr(PythonContext.SharedContext, runpy, "run_module");
} catch (Exception) {
Console.WriteLine("Could not access runpy.run_module", Style.Error);
return -1;
}
// call it with the name of the module to run
try {
PythonOps.CallWithKeywordArgs(
PythonContext.SharedContext,
runMod,
new object[] { Options.ModuleToRun, "__main__", ScriptingRuntimeHelpers.True },
new string[] { "run_name", "alter_sys" }
);
} catch (SystemExitException e) {
object dummy;
return e.GetExitCode(out dummy);
}
return 0;
}
int result = base.Run();
// Check if IRONPYTHONINSPECT was set during execution
string inspectLine = Environment.GetEnvironmentVariable("IRONPYTHONINSPECT");
if (inspectLine != null && !Options.Introspection)
result = RunInteractiveLoop();
return result;
}
#region Initialization
protected override void Initialize() {
Debug.Assert(Language != null);
base.Initialize();
Console.Output = new OutputWriter(PythonContext, false);
Console.ErrorOutput = new OutputWriter(PythonContext, true);
// TODO: must precede path initialization! (??? - test test_importpkg.py)
int pathIndex = PythonContext.PythonOptions.SearchPaths.Count;
Language.DomainManager.LoadAssembly(typeof(string).Assembly);
Language.DomainManager.LoadAssembly(typeof(System.Diagnostics.Debug).Assembly);
InitializePath(ref pathIndex);
InitializeModules();
InitializeExtensionDLLs();
ImportSite();
// Equivalent to -i command line option
// Check if IRONPYTHONINSPECT was set before execution
string inspectLine = Environment.GetEnvironmentVariable("IRONPYTHONINSPECT");
if (inspectLine != null)
Options.Introspection = true;
// If running in console mode (including with -c), the current working directory should be
// the first entry in sys.path. If running a script file, however, the CWD should not be added;
// instead, the script's containg folder should be added.
string fullPath = "."; // this is a valid path resolving to current working dir. Pinky-swear.
if (Options.Command == null && Options.FileName != null) {
if (Options.FileName == "-") {
Options.FileName = "<stdin>";
} else {
#if !SILVERLIGHT
if (Directory.Exists(Options.FileName)) {
Options.FileName = Path.Combine(Options.FileName, "__main__.py");
}
if (!File.Exists(Options.FileName)) {
Console.WriteLine(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"File {0} does not exist.",
Options.FileName),
Style.Error);
Environment.Exit(1);
}
#endif
fullPath = Path.GetDirectoryName(
Language.DomainManager.Platform.GetFullPath(Options.FileName)
);
}
}
PythonContext.InsertIntoPath(0, fullPath);
PythonContext.MainThread = Thread.CurrentThread;
}
protected override Scope/*!*/ CreateScope() {
ModuleOptions trueDiv = (PythonContext.PythonOptions.DivisionOptions == PythonDivisionOptions.New) ? ModuleOptions.TrueDivision : ModuleOptions.None;
var modCtx = new ModuleContext(new PythonDictionary(), PythonContext);
modCtx.Features = trueDiv;
modCtx.InitializeBuiltins(true);
PythonContext.PublishModule("__main__", modCtx.Module);
modCtx.Globals["__doc__"] = null;
modCtx.Globals["__name__"] = "__main__";
return modCtx.GlobalScope;
}
private void InitializePath(ref int pathIndex) {
#if !SILVERLIGHT // paths, environment vars
if (!Options.IgnoreEnvironmentVariables) {
string path = Environment.GetEnvironmentVariable("IRONPYTHONPATH");
if (path != null && path.Length > 0) {
string[] paths = path.Split(Path.PathSeparator);
foreach (string p in paths) {
PythonContext.InsertIntoPath(pathIndex++, p);
}
}
}
#endif
}
private void InitializeModules() {
string executable = "";
string prefix = null;
#if !SILVERLIGHT // paths
Assembly entryAssembly = Assembly.GetEntryAssembly();
//Can be null if called from unmanaged code (VS integration scenario)
if (entryAssembly != null) {
executable = entryAssembly.Location;
prefix = Path.GetDirectoryName(executable);
}
// Make sure there an IronPython Lib directory, and if not keep looking up
while (prefix != null && !File.Exists(Path.Combine(prefix, "Lib/os.py"))) {
prefix = Path.GetDirectoryName(prefix);
}
#endif
PythonContext.SetHostVariables(prefix ?? "", executable, null);
}
/// <summary>
/// Loads any extension DLLs present in sys.prefix\DLLs directory and adds references to them.
///
/// This provides an easy drop-in location for .NET assemblies which should be automatically referenced
/// (exposed via import), COM libraries, and pre-compiled Python code.
/// </summary>
private void InitializeExtensionDLLs() {
string dir = Path.Combine(PythonContext.InitialPrefix, "DLLs");
if (Directory.Exists(dir)) {
foreach (string file in Directory.GetFiles(dir)) {
if (file.ToLower().EndsWith(".dll")) {
try {
ClrModule.AddReference(PythonContext.SharedContext, new FileInfo(file).Name);
} catch {
}
}
}
}
}
private void ImportSite() {
if (Options.SkipImportSite)
return;
try {
Importer.ImportModule(PythonContext.SharedContext, null, "site", false, -1);
} catch (Exception e) {
Console.Write(Language.FormatException(e), Style.Error);
}
}
#endregion
#region Interactive
protected override int RunInteractive() {
PrintLogo();
if (Scope == null) {
Scope = CreateScope();
}
int result = 1;
try {
RunStartup();
result = 0;
} catch (SystemExitException pythonSystemExit) {
return GetEffectiveExitCode(pythonSystemExit);
} catch (Exception) {
}
var sys = Engine.GetSysModule();
sys.SetVariable("ps1", ">>> ");
sys.SetVariable("ps2", "... ");
result = RunInteractiveLoop();
return (int)result;
}
protected override string Prompt {
get {
object value;
if (Engine.GetSysModule().TryGetVariable("ps1", out value)) {
var context = ((PythonScopeExtension)Scope.GetExtension(Language.ContextId)).ModuleContext.GlobalContext;
return PythonOps.ToString(context, value);
}
return ">>> ";
}
}
public override string PromptContinuation {
get {
object value;
if (Engine.GetSysModule().TryGetVariable("ps2", out value)) {
var context = ((PythonScopeExtension)Scope.GetExtension(Language.ContextId)).ModuleContext.GlobalContext;
return PythonOps.ToString(context, value);
}
return "... ";
}
}
private void RunStartup() {
if (Options.IgnoreEnvironmentVariables)
return;
#if !SILVERLIGHT // Environment.GetEnvironmentVariable
string startup = Environment.GetEnvironmentVariable("IRONPYTHONSTARTUP");
if (startup != null && startup.Length > 0) {
if (Options.HandleExceptions) {
try {
ExecuteCommand(Engine.CreateScriptSourceFromFile(startup));
} catch (Exception e) {
if (e is SystemExitException) throw;
Console.Write(Language.FormatException(e), Style.Error);
}
} else {
ExecuteCommand(Engine.CreateScriptSourceFromFile(startup));
}
}
#endif
}
protected override int? TryInteractiveAction() {
try {
try {
return TryInteractiveActionWorker();
} finally {
// sys.exc_info() is normally cleared after functions exit. But interactive console enters statements
// directly instead of using functions. So clear explicitly.
PythonOps.ClearCurrentException();
}
} catch (SystemExitException se) {
return GetEffectiveExitCode(se);
}
}
/// <summary>
/// Attempts to run a single interaction and handle any language-specific
/// exceptions. Base classes can override this and call the base implementation
/// surrounded with their own exception handling.
///
/// Returns null if successful and execution should continue, or an exit code.
/// </summary>
private int? TryInteractiveActionWorker() {
int? result = null;
try {
result = RunOneInteraction();
#if !FEATURE_EXCEPTION_STATE
} catch (ThreadAbortException) {
#else
} catch (ThreadAbortException tae) {
KeyboardInterruptException pki = tae.ExceptionState as KeyboardInterruptException;
if (pki != null) {
Console.WriteLine(Language.FormatException(tae), Style.Error);
Thread.ResetAbort();
}
#endif
}
return result;
}
/// <summary>
/// Parses a single interactive command and executes it.
///
/// Returns null if successful and execution should continue, or the appropiate exit code.
/// </summary>
private int? RunOneInteraction() {
bool continueInteraction;
string s = ReadStatement(out continueInteraction);
if (continueInteraction == false) {
PythonContext.DispatchCommand(null); // Notify dispatcher that we're done
return 0;
}
if (String.IsNullOrEmpty(s)) {
// Is it an empty line?
Console.Write(String.Empty, Style.Out);
return null;
}
SourceUnit su = Language.CreateSnippet(s, "<stdin>", SourceCodeKind.InteractiveCode);
PythonCompilerOptions pco = (PythonCompilerOptions)Language.GetCompilerOptions(Scope);
pco.Module |= ModuleOptions.ExecOrEvalCode;
Action action = delegate() {
try {
su.Compile(pco, ErrorSink).Run(Scope);
} catch (Exception e) {
if (e is SystemExitException) {
throw;
}
// Need to handle exceptions in the delegate so that they're not wrapped
// in a TargetInvocationException
UnhandledException(e);
}
};
try {
PythonContext.DispatchCommand(action);
} catch (SystemExitException sx) {
object dummy;
return sx.GetExitCode(out dummy);
}
return null;
}
protected override ErrorSink/*!*/ ErrorSink {
get { return ThrowingErrorSink.Default; }
}
protected override int GetNextAutoIndentSize(string text) {
return Parser.GetNextAutoIndentSize(text, Options.AutoIndentSize);
}
#endregion
#region Command
protected override int RunCommand(string command) {
if (Options.HandleExceptions) {
try {
return RunCommandWorker(command);
} catch (Exception e) {
Console.Write(Language.FormatException(e), Style.Error);
return 1;
}
}
return RunCommandWorker(command);
}
private int RunCommandWorker(string command) {
ScriptCode compiledCode;
ModuleOptions trueDiv = (PythonContext.PythonOptions.DivisionOptions == PythonDivisionOptions.New) ?
ModuleOptions.TrueDivision : ModuleOptions.None;
ModuleOptions modOpt = ModuleOptions.Optimized | ModuleOptions.ModuleBuiltins | trueDiv;
;
if (Options.SkipFirstSourceLine) {
modOpt |= ModuleOptions.SkipFirstLine;
}
PythonModule module = PythonContext.CompileModule(
"", // there is no file, it will be set to <module>
"__main__",
PythonContext.CreateSnippet(command, SourceCodeKind.File),
modOpt,
out compiledCode);
PythonContext.PublishModule("__main__", module);
Scope = module.Scope;
try {
compiledCode.Run(Scope);
} catch (SystemExitException pythonSystemExit) {
// disable introspection when exited:
Options.Introspection = false;
return GetEffectiveExitCode(pythonSystemExit);
}
return 0;
}
#endregion
#region File
protected override int RunFile(string/*!*/ fileName) {
int result = 1;
if (Options.HandleExceptions) {
try {
result = RunFileWorker(fileName);
} catch (Exception e) {
Console.Write(Language.FormatException(e), Style.Error);
}
} else {
result = RunFileWorker(fileName);
}
return result;
}
private int RunFileWorker(string/*!*/ fileName) {
try {
// There is no PEP for this case, only http://bugs.python.org/issue1739468
object importer;
if (Importer.TryImportMainFromZip(DefaultContext.Default, fileName, out importer)) {
return 0;
}
if (importer != null && importer.GetType() != typeof(PythonImport.NullImporter)) {
Console.WriteLine(String.Format("can't find '__main__' module in '{0}'", fileName), Style.Error);
return 0;
}
} catch (SystemExitException pythonSystemExit) {
// disable introspection when exited:
Options.Introspection = false;
return GetEffectiveExitCode(pythonSystemExit);
}
// classic file
ScriptCode compiledCode;
ModuleOptions modOpt = ModuleOptions.Optimized | ModuleOptions.ModuleBuiltins;
if(Options.SkipFirstSourceLine) {
modOpt |= ModuleOptions.SkipFirstLine;
}
PythonModule module = PythonContext.CompileModule(
fileName,
"__main__",
PythonContext.CreateFileUnit(String.IsNullOrEmpty(fileName) ? null : fileName, PythonContext.DefaultEncoding),
modOpt,
out compiledCode);
PythonContext.PublishModule("__main__", module);
Scope = module.Scope;
try {
compiledCode.Run(Scope);
} catch (SystemExitException pythonSystemExit) {
// disable introspection when exited:
Options.Introspection = false;
return GetEffectiveExitCode(pythonSystemExit);
}
return 0;
}
#endregion
public override IList<string> GetGlobals(string name) {
IList<string> res = base.GetGlobals(name);
foreach (object builtinName in PythonContext.BuiltinModuleInstance.__dict__.Keys) {
string strName = builtinName as string;
if (strName != null && strName.StartsWith(name)) {
res.Add(strName);
}
}
return res;
}
protected override void UnhandledException(Exception e) {
PythonOps.PrintException(PythonContext.SharedContext, e, Console);
}
private new PythonContext Language {
get {
return (PythonContext)base.Language;
}
}
}
}
#endif
| |
using J2N.Runtime.CompilerServices;
using YAF.Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using JCG = J2N.Collections.Generic;
namespace YAF.Lucene.Net.Codecs.PerField
{
/*
* 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 BinaryDocValues = YAF.Lucene.Net.Index.BinaryDocValues;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using FieldInfo = YAF.Lucene.Net.Index.FieldInfo;
using IBits = YAF.Lucene.Net.Util.IBits;
using IOUtils = YAF.Lucene.Net.Util.IOUtils;
using NumericDocValues = YAF.Lucene.Net.Index.NumericDocValues;
using RamUsageEstimator = YAF.Lucene.Net.Util.RamUsageEstimator;
using SegmentReadState = YAF.Lucene.Net.Index.SegmentReadState;
using SegmentWriteState = YAF.Lucene.Net.Index.SegmentWriteState;
using SortedDocValues = YAF.Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = YAF.Lucene.Net.Index.SortedSetDocValues;
/// <summary>
/// Enables per field docvalues support.
/// <para/>
/// Note, when extending this class, the name (<see cref="DocValuesFormat.Name"/>) is
/// written into the index. In order for the field to be read, the
/// name must resolve to your implementation via <see cref="DocValuesFormat.ForName(string)"/>.
/// This method uses <see cref="IDocValuesFormatFactory.GetDocValuesFormat(string)"/> to resolve format names.
/// See <see cref="DefaultDocValuesFormatFactory"/> for information about how to implement your own <see cref="DocValuesFormat"/>.
/// <para/>
/// Files written by each docvalues format have an additional suffix containing the
/// format name. For example, in a per-field configuration instead of <c>_1.dat</c>
/// filenames would look like <c>_1_Lucene40_0.dat</c>.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <seealso cref="IDocValuesFormatFactory"/>
/// <seealso cref="DefaultDocValuesFormatFactory"/>
[DocValuesFormatName("PerFieldDV40")]
public abstract class PerFieldDocValuesFormat : DocValuesFormat
{
// LUCENENET specific: Removing this static variable, since name is now determined by the DocValuesFormatNameAttribute.
///// <summary>
///// Name of this <seealso cref="PostingsFormat"/>. </summary>
//public static readonly string PER_FIELD_NAME = "PerFieldDV40";
/// <summary>
/// <see cref="FieldInfo"/> attribute name used to store the
/// format name for each field.
/// </summary>
public static readonly string PER_FIELD_FORMAT_KEY = typeof(PerFieldDocValuesFormat).Name + ".format";
/// <summary>
/// <see cref="FieldInfo"/> attribute name used to store the
/// segment suffix name for each field.
/// </summary>
public static readonly string PER_FIELD_SUFFIX_KEY = typeof(PerFieldDocValuesFormat).Name + ".suffix";
/// <summary>
/// Sole constructor. </summary>
protected PerFieldDocValuesFormat() // LUCENENET: CA1012: Abstract types should not have constructors (marked protected)
: base()
{
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override sealed DocValuesConsumer FieldsConsumer(SegmentWriteState state)
{
return new FieldsWriter(this, state);
}
internal class ConsumerAndSuffix : IDisposable
{
internal DocValuesConsumer Consumer { get; set; }
internal int Suffix { get; set; }
public void Dispose()
{
Consumer.Dispose();
}
}
private class FieldsWriter : DocValuesConsumer
{
private readonly PerFieldDocValuesFormat outerInstance;
internal readonly IDictionary<DocValuesFormat, ConsumerAndSuffix> formats = new Dictionary<DocValuesFormat, ConsumerAndSuffix>();
internal readonly IDictionary<string, int?> suffixes = new Dictionary<string, int?>();
internal readonly SegmentWriteState segmentWriteState;
public FieldsWriter(PerFieldDocValuesFormat outerInstance, SegmentWriteState state)
{
this.outerInstance = outerInstance;
segmentWriteState = state;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void AddNumericField(FieldInfo field, IEnumerable<long?> values)
{
GetInstance(field).AddNumericField(field, values);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values)
{
GetInstance(field).AddBinaryField(field, values);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd)
{
GetInstance(field).AddSortedField(field, values, docToOrd);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords)
{
GetInstance(field).AddSortedSetField(field, values, docToOrdCount, ords);
}
internal virtual DocValuesConsumer GetInstance(FieldInfo field)
{
DocValuesFormat format = null;
if (field.DocValuesGen != -1)
{
string formatName = field.GetAttribute(PER_FIELD_FORMAT_KEY);
// this means the field never existed in that segment, yet is applied updates
if (formatName != null)
{
format = DocValuesFormat.ForName(formatName);
}
}
if (format is null)
{
format = outerInstance.GetDocValuesFormatForField(field.Name);
}
if (format is null)
{
throw IllegalStateException.Create("invalid null DocValuesFormat for field=\"" + field.Name + "\"");
}
string formatName_ = format.Name;
string previousValue = field.PutAttribute(PER_FIELD_FORMAT_KEY, formatName_);
if (Debugging.AssertsEnabled) Debugging.Assert(field.DocValuesGen != -1 || previousValue is null,"formatName={0} prevValue={1}", formatName_, previousValue);
int? suffix = null;
if (!formats.TryGetValue(format, out ConsumerAndSuffix consumer) || consumer is null)
{
// First time we are seeing this format; create a new instance
if (field.DocValuesGen != -1)
{
string suffixAtt = field.GetAttribute(PER_FIELD_SUFFIX_KEY);
// even when dvGen is != -1, it can still be a new field, that never
// existed in the segment, and therefore doesn't have the recorded
// attributes yet.
if (suffixAtt != null)
{
suffix = Convert.ToInt32(suffixAtt, CultureInfo.InvariantCulture);
}
}
if (suffix is null)
{
// bump the suffix
if (!suffixes.TryGetValue(formatName_, out suffix) || suffix is null)
{
suffix = 0;
}
else
{
suffix = suffix + 1;
}
}
suffixes[formatName_] = suffix;
string segmentSuffix = GetFullSegmentSuffix(segmentWriteState.SegmentSuffix, GetSuffix(formatName_, Convert.ToString(suffix, CultureInfo.InvariantCulture)));
consumer = new ConsumerAndSuffix();
consumer.Consumer = format.FieldsConsumer(new SegmentWriteState(segmentWriteState, segmentSuffix));
consumer.Suffix = suffix.Value; // LUCENENET NOTE: At this point suffix cannot be null
formats[format] = consumer;
}
else
{
// we've already seen this format, so just grab its suffix
if (Debugging.AssertsEnabled) Debugging.Assert(suffixes.ContainsKey(formatName_));
suffix = consumer.Suffix;
}
previousValue = field.PutAttribute(PER_FIELD_SUFFIX_KEY, Convert.ToString(suffix, CultureInfo.InvariantCulture));
if (Debugging.AssertsEnabled) Debugging.Assert(field.DocValuesGen != -1 || previousValue is null,"suffix={0} prevValue={1}", suffix, previousValue);
// TODO: we should only provide the "slice" of FIS
// that this DVF actually sees ...
return consumer.Consumer;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Close all subs
IOUtils.Dispose(formats.Values);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static string GetSuffix(string formatName, string suffix)
{
return formatName + "_" + suffix;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static string GetFullSegmentSuffix(string outerSegmentSuffix, string segmentSuffix)
{
if (outerSegmentSuffix.Length == 0)
{
return segmentSuffix;
}
else
{
return outerSegmentSuffix + "_" + segmentSuffix;
}
}
private class FieldsReader : DocValuesProducer
{
private readonly PerFieldDocValuesFormat outerInstance;
// LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java
internal readonly IDictionary<string, DocValuesProducer> fields = new JCG.SortedDictionary<string, DocValuesProducer>(StringComparer.Ordinal);
internal readonly IDictionary<string, DocValuesProducer> formats = new Dictionary<string, DocValuesProducer>();
public FieldsReader(PerFieldDocValuesFormat outerInstance, SegmentReadState readState)
{
this.outerInstance = outerInstance;
// Read _X.per and init each format:
bool success = false;
try
{
// Read field name -> format name
foreach (FieldInfo fi in readState.FieldInfos)
{
if (fi.HasDocValues)
{
string fieldName = fi.Name;
string formatName = fi.GetAttribute(PER_FIELD_FORMAT_KEY);
if (formatName != null)
{
// null formatName means the field is in fieldInfos, but has no docvalues!
string suffix = fi.GetAttribute(PER_FIELD_SUFFIX_KEY);
if (Debugging.AssertsEnabled) Debugging.Assert(suffix != null);
DocValuesFormat format = DocValuesFormat.ForName(formatName);
string segmentSuffix = GetFullSegmentSuffix(readState.SegmentSuffix, GetSuffix(formatName, suffix));
// LUCENENET: Eliminated extra lookup by using TryGetValue instead of ContainsKey
if (!formats.TryGetValue(segmentSuffix, out DocValuesProducer field))
{
formats[segmentSuffix] = field = format.FieldsProducer(new SegmentReadState(readState, segmentSuffix));
}
fields[fieldName] = field;
}
}
}
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(formats.Values);
}
}
}
internal FieldsReader(PerFieldDocValuesFormat outerInstance, FieldsReader other)
{
this.outerInstance = outerInstance;
IDictionary<DocValuesProducer, DocValuesProducer> oldToNew = new JCG.Dictionary<DocValuesProducer, DocValuesProducer>(IdentityEqualityComparer<DocValuesProducer>.Default);
// First clone all formats
foreach (KeyValuePair<string, DocValuesProducer> ent in other.formats)
{
DocValuesProducer values = ent.Value;
formats[ent.Key] = values;
oldToNew[ent.Value] = values;
}
// Then rebuild fields:
foreach (KeyValuePair<string, DocValuesProducer> ent in other.fields)
{
oldToNew.TryGetValue(ent.Value, out DocValuesProducer producer);
if (Debugging.AssertsEnabled) Debugging.Assert(producer != null);
fields[ent.Key] = producer;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override NumericDocValues GetNumeric(FieldInfo field)
{
if (fields.TryGetValue(field.Name, out DocValuesProducer producer) && producer != null)
{
return producer.GetNumeric(field);
}
return null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override BinaryDocValues GetBinary(FieldInfo field)
{
if (fields.TryGetValue(field.Name, out DocValuesProducer producer) && producer != null)
{
return producer.GetBinary(field);
}
return null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override SortedDocValues GetSorted(FieldInfo field)
{
if (fields.TryGetValue(field.Name, out DocValuesProducer producer) && producer != null)
{
return producer.GetSorted(field);
}
return null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
if (fields.TryGetValue(field.Name, out DocValuesProducer producer) && producer != null)
{
return producer.GetSortedSet(field);
}
return null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override IBits GetDocsWithField(FieldInfo field)
{
if (fields.TryGetValue(field.Name, out DocValuesProducer producer) && producer != null)
{
return producer.GetDocsWithField(field);
}
return null;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
IOUtils.Dispose(formats.Values);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public object Clone()
{
return new FieldsReader(outerInstance, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override long RamBytesUsed()
{
long size = 0;
foreach (KeyValuePair<string, DocValuesProducer> entry in formats)
{
size += (entry.Key.Length * RamUsageEstimator.NUM_BYTES_CHAR)
+ entry.Value.RamBytesUsed();
}
return size;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void CheckIntegrity()
{
foreach (DocValuesProducer format in formats.Values)
{
format.CheckIntegrity();
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override sealed DocValuesProducer FieldsProducer(SegmentReadState state)
{
return new FieldsReader(this, state);
}
/// <summary>
/// Returns the doc values format that should be used for writing
/// new segments of <paramref name="field"/>.
/// <para/>
/// The field to format mapping is written to the index, so
/// this method is only invoked when writing, not when reading.
/// </summary>
public abstract DocValuesFormat GetDocValuesFormatForField(string field);
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using ESRI.ArcGIS.esriSystem;
//FILE AUTOMATICALLY GENERATED BY ESRI LICENSE INITIALIZATION ADDIN
//YOU SHOULD NOT NORMALLY EDIT OR REMOVE THIS FILE FROM THE PROJECT
namespace LocationAllocationSolver
{
internal sealed class LicenseInitializer
{
private IAoInitialize m_AoInit = new AoInitializeClass();
#region Private members
private const string MessageNoLicensesRequested = "Product: No licenses were requested";
private const string MessageProductAvailable = "Product: {0}: Available";
private const string MessageProductNotLicensed = "Product: {0}: Not Licensed";
private const string MessageExtensionAvailable = " Extension: {0}: Available";
private const string MessageExtensionNotLicensed = " Extension: {0}: Not Licensed";
private const string MessageExtensionFailed = " Extension: {0}: Failed";
private const string MessageExtensionUnavailable = " Extension: {0}: Unavailable";
private bool m_hasShutDown = false;
private bool m_hasInitializeProduct = false;
private List<int> m_requestedProducts;
private List<esriLicenseExtensionCode> m_requestedExtensions;
private Dictionary<esriLicenseProductCode, esriLicenseStatus> m_productStatus = new Dictionary<esriLicenseProductCode, esriLicenseStatus>();
private Dictionary<esriLicenseExtensionCode, esriLicenseStatus> m_extensionStatus = new Dictionary<esriLicenseExtensionCode, esriLicenseStatus>();
private bool m_productCheckOrdering = true; //default from low to high
#endregion
public bool InitializeApplication(esriLicenseProductCode[] productCodes, esriLicenseExtensionCode[] extensionLics)
{
//Cache product codes by enum int so can be sorted without custom sorter
m_requestedProducts = new List<int>();
foreach (esriLicenseProductCode code in productCodes)
{
int requestCodeNum = Convert.ToInt32(code);
if (!m_requestedProducts.Contains(requestCodeNum))
{
m_requestedProducts.Add(requestCodeNum);
}
}
AddExtensions(extensionLics);
return Initialize();
}
/// <summary>
/// A summary of the status of product and extensions initialization.
/// </summary>
public string LicenseMessage()
{
string prodStatus = string.Empty;
if (m_productStatus == null || m_productStatus.Count == 0)
{
prodStatus = MessageNoLicensesRequested + Environment.NewLine;
}
else if (m_productStatus.ContainsValue(esriLicenseStatus.esriLicenseAlreadyInitialized)
|| m_productStatus.ContainsValue(esriLicenseStatus.esriLicenseCheckedOut))
{
prodStatus = ReportInformation(m_AoInit as ILicenseInformation,
m_AoInit.InitializedProduct(),
esriLicenseStatus.esriLicenseCheckedOut) + Environment.NewLine;
}
else
{
//Failed...
foreach (KeyValuePair<esriLicenseProductCode, esriLicenseStatus> item in m_productStatus)
{
prodStatus += ReportInformation(m_AoInit as ILicenseInformation,
item.Key, item.Value) + Environment.NewLine;
}
}
string extStatus = string.Empty;
foreach (KeyValuePair<esriLicenseExtensionCode, esriLicenseStatus> item in m_extensionStatus)
{
string info = ReportInformation(m_AoInit as ILicenseInformation, item.Key, item.Value);
if (!string.IsNullOrEmpty(info))
extStatus += info + Environment.NewLine;
}
string status = prodStatus + extStatus;
return status.Trim();
}
/// <summary>
/// Shuts down AoInitialize object and check back in extensions to ensure
/// any ESRI libraries that have been used are unloaded in the correct order.
/// </summary>
/// <remarks>Once Shutdown has been called, you cannot re-initialize the product license
/// and should not make any ArcObjects call.</remarks>
public void ShutdownApplication()
{
if (m_hasShutDown)
return;
//Check back in extensions
foreach (KeyValuePair<esriLicenseExtensionCode, esriLicenseStatus> item in m_extensionStatus)
{
if (item.Value == esriLicenseStatus.esriLicenseCheckedOut)
m_AoInit.CheckInExtension(item.Key);
}
m_requestedProducts.Clear();
m_requestedExtensions.Clear();
m_extensionStatus.Clear();
m_productStatus.Clear();
m_AoInit.Shutdown();
m_hasShutDown = true;
//m_hasInitializeProduct = false;
}
/// <summary>
/// Indicates if the extension is currently checked out.
/// </summary>
public bool IsExtensionCheckedOut(esriLicenseExtensionCode code)
{
return m_AoInit.IsExtensionCheckedOut(code);
}
/// <summary>
/// Set the extension(s) to be checked out for your ArcObjects code.
/// </summary>
public bool AddExtensions(params esriLicenseExtensionCode[] requestCodes)
{
if (m_requestedExtensions == null)
m_requestedExtensions = new List<esriLicenseExtensionCode>();
foreach (esriLicenseExtensionCode code in requestCodes)
{
if (!m_requestedExtensions.Contains(code))
m_requestedExtensions.Add(code);
}
if (m_hasInitializeProduct)
return CheckOutLicenses(this.InitializedProduct);
return false;
}
/// <summary>
/// Check in extension(s) when it is no longer needed.
/// </summary>
public void RemoveExtensions(params esriLicenseExtensionCode[] requestCodes)
{
if (m_extensionStatus == null || m_extensionStatus.Count == 0)
return;
foreach (esriLicenseExtensionCode code in requestCodes)
{
if (m_extensionStatus.ContainsKey(code))
{
if (m_AoInit.CheckInExtension(code) == esriLicenseStatus.esriLicenseCheckedIn)
{
m_extensionStatus[code] = esriLicenseStatus.esriLicenseCheckedIn;
}
}
}
}
/// <summary>
/// Get/Set the ordering of product code checking. If true, check from lowest to
/// highest license. True by default.
/// </summary>
public bool InitializeLowerProductFirst
{
get
{
return m_productCheckOrdering;
}
set
{
m_productCheckOrdering = value;
}
}
/// <summary>
/// Retrieves the product code initialized in the ArcObjects application
/// </summary>
public esriLicenseProductCode InitializedProduct
{
get
{
try
{
return m_AoInit.InitializedProduct();
}
catch
{
return 0;
}
}
}
#region Helper methods
private bool Initialize()
{
if (m_requestedProducts == null || m_requestedProducts.Count == 0)
return false;
esriLicenseProductCode currentProduct = new esriLicenseProductCode();
bool productInitialized = false;
//Try to initialize a product
ILicenseInformation licInfo = (ILicenseInformation)m_AoInit;
m_requestedProducts.Sort();
if (!InitializeLowerProductFirst) //Request license from highest to lowest
m_requestedProducts.Reverse();
foreach (int prodNumber in m_requestedProducts)
{
esriLicenseProductCode prod = (esriLicenseProductCode)Enum.ToObject(typeof(esriLicenseProductCode), prodNumber);
esriLicenseStatus status = m_AoInit.IsProductCodeAvailable(prod);
if (status == esriLicenseStatus.esriLicenseAvailable)
{
status = m_AoInit.Initialize(prod);
if (status == esriLicenseStatus.esriLicenseAlreadyInitialized ||
status == esriLicenseStatus.esriLicenseCheckedOut)
{
productInitialized = true;
currentProduct = m_AoInit.InitializedProduct();
}
}
m_productStatus.Add(prod, status);
if (productInitialized)
break;
}
m_hasInitializeProduct = productInitialized;
m_requestedProducts.Clear();
//No product is initialized after trying all requested licenses, quit
if (!productInitialized)
{
return false;
}
//Check out extension licenses
return CheckOutLicenses(currentProduct);
}
private bool CheckOutLicenses(esriLicenseProductCode currentProduct)
{
bool allSuccessful = true;
//Request extensions
if (m_requestedExtensions != null && currentProduct != 0)
{
foreach (esriLicenseExtensionCode ext in m_requestedExtensions)
{
esriLicenseStatus licenseStatus = m_AoInit.IsExtensionCodeAvailable(currentProduct, ext);
if (licenseStatus == esriLicenseStatus.esriLicenseAvailable)//skip unavailable extensions
{
licenseStatus = m_AoInit.CheckOutExtension(ext);
}
allSuccessful = (allSuccessful && licenseStatus == esriLicenseStatus.esriLicenseCheckedOut);
if (m_extensionStatus.ContainsKey(ext))
m_extensionStatus[ext] = licenseStatus;
else
m_extensionStatus.Add(ext, licenseStatus);
}
m_requestedExtensions.Clear();
}
return allSuccessful;
}
private string ReportInformation(ILicenseInformation licInfo,
esriLicenseProductCode code, esriLicenseStatus status)
{
string prodName = string.Empty;
try
{
prodName = licInfo.GetLicenseProductName(code);
}
catch
{
prodName = code.ToString();
}
string statusInfo = string.Empty;
switch (status)
{
case esriLicenseStatus.esriLicenseAlreadyInitialized:
case esriLicenseStatus.esriLicenseCheckedOut:
statusInfo = string.Format(MessageProductAvailable, prodName);
break;
default:
statusInfo = string.Format(MessageProductNotLicensed, prodName);
break;
}
return statusInfo;
}
private string ReportInformation(ILicenseInformation licInfo,
esriLicenseExtensionCode code, esriLicenseStatus status)
{
string extensionName = string.Empty;
try
{
extensionName = licInfo.GetLicenseExtensionName(code);
}
catch
{
extensionName = code.ToString();
}
string statusInfo = string.Empty;
switch (status)
{
case esriLicenseStatus.esriLicenseAlreadyInitialized:
case esriLicenseStatus.esriLicenseCheckedOut:
statusInfo = string.Format(MessageExtensionAvailable, extensionName);
break;
case esriLicenseStatus.esriLicenseCheckedIn:
break;
case esriLicenseStatus.esriLicenseUnavailable:
statusInfo = string.Format(MessageExtensionUnavailable, extensionName);
break;
case esriLicenseStatus.esriLicenseFailure:
statusInfo = string.Format(MessageExtensionFailed, extensionName);
break;
default:
statusInfo = string.Format(MessageExtensionNotLicensed, extensionName);
break;
}
return statusInfo;
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Microsoft.Research.ClousotRegression;
namespace ObjectInvariants
{
public class SimpleInvariants
{
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 9, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 15, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.False, Message = @"invariant is false: this.items != null", PrimaryILOffset = 13, MethodILOffset = 23)]
public SimpleInvariants() { }
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 9, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 15, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 24, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 31, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"invariant unproven: this.items != null", PrimaryILOffset = 13, MethodILOffset = 37)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"invariant unproven: this.comparison != null", PrimaryILOffset = 31, MethodILOffset = 37)]
public SimpleInvariants(int[] a, IComparable b)
{
this.items = a;
this.comparison = b;
}
int[] items = null;
IComparable comparison = null;
[ClousotRegressionTest("regular")]
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.items != null);
Contract.Invariant(this.comparison != null);
}
}
public class CDictionary<TKey>
{
private IEqualityComparer<TKey> comparer;
private int count;
private int freeCount;
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(count >= freeCount);
Contract.Invariant(comparer != null);
}
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 3, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 15, MethodILOffset = 3)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 28, MethodILOffset = 3)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 18, MethodILOffset = 24)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 36, MethodILOffset = 24)]
public CDictionary(IEqualityComparer<TKey> comparer)
: this(0, comparer)
{
Contract.Requires(comparer != null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 65, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 73, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 35, MethodILOffset = 79)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 18, MethodILOffset = 79)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 36, MethodILOffset = 79)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 46, MethodILOffset = 79)]
public CDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
Contract.Requires(capacity >= 0);
Contract.Requires(comparer != null);
Contract.Ensures(this.comparer != null);
if (capacity > 0)
Initialize(capacity);
this.comparer = comparer;
}
private void Initialize(int capacity)
{
this.freeCount = 0;
this.count = 0;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 3, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 10, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 19, MethodILOffset = 27)]
~CDictionary()
{
this.comparer = null;
this.count = -1;
}
/// <summary>
/// Make sure we don't enforce the invariant
/// </summary>
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 3, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 10, MethodILOffset = 0)]
public virtual void Dispose()
{
this.comparer = null;
this.count = -1;
}
}
class OutgoingThis
{
object obj = null;
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(obj != null);
}
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 13, MethodILOffset = 8)]
public void S()
{
TestOutgoingThis.X(this);
}
}
static class TestOutgoingThis
{
public static void X(OutgoingThis obj)
{
}
}
class TestBaseWithInv
{
int x = 1;
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(x > 0);
}
public virtual void M() { }
}
class TestDerived : TestBaseWithInv
{
object obj = "";
[ContractInvariantMethod]
private void Invariant2()
{
Contract.Invariant(obj != null);
}
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 10, MethodILOffset = 8)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 13, MethodILOffset = 8)]
public override void M()
{
base.M();
}
}
class TestBaseWithoutInv
{
public virtual void M() { }
}
class TestDerived2 : TestBaseWithoutInv
{
object obj = "";
[ContractInvariantMethod]
private void Invariant2()
{
Contract.Invariant(obj != null);
}
[ClousotRegressionTest("regular")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 13, MethodILOffset = 8)]
public override void M()
{
base.M();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Tanka.FileSystem.WebApiSample.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
using System.Diagnostics;
using Microsoft.Xna.Framework.Graphics;
namespace tests
{
public class ParticleMainScene : CCScene
{
public ParticleMainScene() : base(AppDelegate.SharedWindow)
{
}
public virtual void initWithSubTest(int asubtest, int particles)
{
//srandom(0);
subtestNumber = asubtest;
CCSize s = Layer.VisibleBoundsWorldspace.Size;
lastRenderedCount = 0;
quantityParticles = particles;
CCMenuItemFont.FontSize = 64;
CCMenuItemFont.FontName = "arial";
CCMenuItemFont decrease = new CCMenuItemFont(" - ", onDecrease);
decrease.Color = new CCColor3B(0, 200, 20);
CCMenuItemFont increase = new CCMenuItemFont(" + ", onIncrease);
increase.Color = new CCColor3B(0, 200, 20);
CCMenu menu = new CCMenu(decrease, increase);
menu.AlignItemsHorizontally();
menu.Position = new CCPoint(s.Width / 2, s.Height / 2 + 15);
AddChild(menu, 1);
CCLabel infoLabel = new CCLabel("0 nodes", "Marker Felt", 30, CCLabelFormat.SpriteFont);
infoLabel.Color = new CCColor3B(0, 200, 20);
infoLabel.Position = new CCPoint(s.Width / 2, s.Height - 90);
AddChild(infoLabel, 1, PerformanceParticleTest.kTagInfoLayer);
// particles on stage
CCLabelAtlas labelAtlas = new CCLabelAtlas("0000", "Images/fps_Images", 12, 32, '.');
AddChild(labelAtlas, 0, PerformanceParticleTest.kTagLabelAtlas);
labelAtlas.Position = new CCPoint(s.Width - 66, 50);
// Next Prev Test
ParticleMenuLayer pMenu = new ParticleMenuLayer(true, PerformanceParticleTest.TEST_COUNT, PerformanceParticleTest.s_nParCurIdx);
AddChild(pMenu, 1, PerformanceParticleTest.kTagMenuLayer);
// Sub Tests
CCMenuItemFont.FontSize = 38;
CCMenuItemFont.FontName = "arial";
CCMenu pSubMenu = new CCMenu(null);
for (int i = 1; i <= 6; ++i)
{
//char str[10] = {0};
string str;
//sprintf(str, "%d ", i);
str = string.Format("{0:G}", i);
CCMenuItemFont itemFont = new CCMenuItemFont(str, testNCallback);
itemFont.Tag = i;
pSubMenu.AddChild(itemFont, 10);
if (i <= 3)
{
itemFont.Color = new CCColor3B(200, 20, 20);
}
else
{
itemFont.Color = new CCColor3B(0, 200, 20);
}
}
pSubMenu.AlignItemsHorizontally();
pSubMenu.Position = new CCPoint(s.Width / 2, 80);
AddChild(pSubMenu, 2);
CCLabel label = new CCLabel(title(), "arial", 38, CCLabelFormat.SpriteFont);
AddChild(label, 1);
label.Position = new CCPoint(s.Width / 2, s.Height - 32);
label.Color = new CCColor3B(255, 255, 40);
updateQuantityLabel();
createParticleSystem();
Schedule(step);
}
public virtual string title()
{
return "No title";
}
public void step(float dt)
{
CCLabelAtlas atlas = (CCLabelAtlas)GetChildByTag(PerformanceParticleTest.kTagLabelAtlas);
CCParticleSystem emitter = (CCParticleSystem)GetChildByTag(PerformanceParticleTest.kTagParticleSystem);
var str = string.Format("{0:0000}", emitter.ParticleCount);
atlas.Text = (str);
}
public void createParticleSystem()
{
/*
* Tests:
* 1: Point Particle System using 32-bit textures (PNG)
* 2: Point Particle System using 16-bit textures (PNG)
* 3: Point Particle System using 8-bit textures (PNG)
* 4: Point Particle System using 4-bit textures (PVRTC)
* 5: Quad Particle System using 32-bit textures (PNG)
* 6: Quad Particle System using 16-bit textures (PNG)
* 7: Quad Particle System using 8-bit textures (PNG)
* 8: Quad Particle System using 4-bit textures (PVRTC)
*/
RemoveChildByTag(PerformanceParticleTest.kTagParticleSystem, true);
// remove the "fire.png" from the TextureCache cache.
CCTexture2D texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
CCTextureCache.SharedTextureCache.RemoveTexture(texture);
var particleSystem = new CCParticleSystemQuad(quantityParticles);
switch (subtestNumber)
{
case 1:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
case 2:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Bgra4444;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
case 3:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Alpha8;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
// case 4:
// particleSystem->initWithTotalParticles(quantityParticles);
// ////---- particleSystem.texture = [[CCTextureCache sharedTextureCache] addImage:@"fire.pvr"];
// particleSystem->setTexture(CCTextureCache::sharedTextureCache()->addImage("Images/fire.png"));
// break;
case 4:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
case 5:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Bgra4444;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
case 6:
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Alpha8;
particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire");
break;
// case 8:
// particleSystem->initWithTotalParticles(quantityParticles);
// ////---- particleSystem.texture = [[CCTextureCache sharedTextureCache] addImage:@"fire.pvr"];
// particleSystem->setTexture(CCTextureCache::sharedTextureCache()->addImage("Images/fire.png"));
// break;
default:
particleSystem = null;
CCLog.Log("Shall not happen!");
break;
}
AddChild(particleSystem, 0, PerformanceParticleTest.kTagParticleSystem);
doTest();
// restore the default pixel format
CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color;
}
public void onDecrease(object pSender)
{
quantityParticles -= PerformanceParticleTest.kNodesIncrease;
if (quantityParticles < 0)
quantityParticles = 0;
updateQuantityLabel();
createParticleSystem();
}
public void onIncrease(object pSender)
{
quantityParticles += PerformanceParticleTest.kNodesIncrease;
if (quantityParticles > PerformanceParticleTest.kMaxParticles)
quantityParticles = PerformanceParticleTest.kMaxParticles;
updateQuantityLabel();
createParticleSystem();
}
public void testNCallback(object pSender)
{
subtestNumber = ((CCNode)pSender).Tag;
ParticleMenuLayer pMenu = (ParticleMenuLayer)GetChildByTag(PerformanceParticleTest.kTagMenuLayer);
pMenu.restartCallback(pSender);
}
public void updateQuantityLabel()
{
if (quantityParticles != lastRenderedCount)
{
var infoLabel = (CCLabel)GetChildByTag(PerformanceParticleTest.kTagInfoLayer);
string str = string.Format("{0} particles", quantityParticles);
infoLabel.Text = (str);
lastRenderedCount = quantityParticles;
}
}
public int getSubTestNum()
{
return subtestNumber;
}
public int getParticlesNum()
{
return quantityParticles;
}
public virtual void doTest()
{
throw new NotFiniteNumberException();
}
protected int lastRenderedCount;
protected int quantityParticles;
protected int subtestNumber;
}
}
| |
/*
* Licensed to SharpSoftware under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* SharpSoftware licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Itinero.Algorithms.Weights;
using Itinero.Graphs.Directed;
namespace Itinero.Algorithms.Contracted.Witness
{
/// <summary>
/// Contains extension methods related to the vertex info data structure.
/// </summary>
public static class VertexInfoExtensions
{
/// <summary>
/// Adds edges relevant for contraction to the given vertex info, assuming it's empty.
/// </summary>
public static void AddRelevantEdges<T>(this VertexInfo<T> vertexInfo, DirectedMetaGraph.EdgeEnumerator enumerator)
where T : struct
{
System.Diagnostics.Debug.Assert(vertexInfo.Count == 0);
var vertex = vertexInfo.Vertex;
enumerator.MoveTo(vertex);
while(enumerator.MoveNext())
{
if (enumerator.Neighbour == vertex)
{
continue;
}
vertexInfo.Add(enumerator.Current);
}
}
/// <summary>
/// Builds the potential shortcuts.
/// </summary>
public static void BuildShortcuts<T>(this VertexInfo<T> vertexinfo, WeightHandler<T> weightHandler)
where T : struct
{
var vertex = vertexinfo.Vertex;
var shortcuts = vertexinfo.Shortcuts;
// loop over all edge-pairs once.
var shortcut = new Shortcut<T>()
{
Backward = weightHandler.Infinite,
Forward = weightHandler.Infinite
};
var shortcutEdge = new OriginalEdge();
for (var j = 1; j < vertexinfo.Count; j++)
{
var edge1 = vertexinfo[j];
var edge1Weight = weightHandler.GetEdgeWeight(edge1);
shortcutEdge.Vertex1 = edge1.Neighbour;
// figure out what witness paths to calculate.
for (var k = 0; k < j; k++)
{
var edge2 = vertexinfo[k];
var edge2Weight = weightHandler.GetEdgeWeight(edge2);
shortcutEdge.Vertex2 = edge2.Neighbour;
if (!(edge1Weight.Direction.B && edge2Weight.Direction.F) &&
!(edge1Weight.Direction.F && edge2Weight.Direction.B))
{ // impossible route, do nothing.
continue;
}
shortcut.Backward = weightHandler.Infinite;
shortcut.Forward = weightHandler.Infinite;
if (edge1Weight.Direction.B && edge2Weight.Direction.F)
{
shortcut.Forward = weightHandler.Add(edge1Weight.Weight, edge2Weight.Weight);
}
if (edge1Weight.Direction.F && edge2Weight.Direction.B)
{
shortcut.Backward = weightHandler.Add(edge1Weight.Weight, edge2Weight.Weight);
}
shortcuts.AddOrUpdate(shortcutEdge, shortcut, weightHandler);
}
}
}
/// <summary>
/// Calculates the priority of this vertex.
/// </summary>
public static float Priority<T>(this VertexInfo<T> vertexInfo, DirectedMetaGraph graph, WeightHandler<T> weightHandler, float differenceFactor, float contractedFactor,
float depthFactor, float weightDiffFactor = 1)
where T : struct
{
var vertex = vertexInfo.Vertex;
var removed = vertexInfo.Count;
var added = 0;
//var removedWeight = 0f;
//var addedWeight = 0f;
foreach (var shortcut in vertexInfo.Shortcuts)
{
var shortcutForward = weightHandler.GetMetric(shortcut.Value.Forward);
var shortcutBackward = weightHandler.GetMetric(shortcut.Value.Backward);
int localAdded, localRemoved;
if (shortcutForward > 0 && shortcutForward < float.MaxValue &&
shortcutBackward > 0 && shortcutBackward < float.MaxValue &&
System.Math.Abs(shortcutForward - shortcutBackward) < FastHierarchyBuilder<float>.E)
{ // add two bidirectional edges.
graph.TryAddOrUpdateEdge(shortcut.Key.Vertex1, shortcut.Key.Vertex2, shortcutForward, null, vertex,
out localAdded, out localRemoved);
added += localAdded;
removed += localRemoved;
graph.TryAddOrUpdateEdge(shortcut.Key.Vertex2, shortcut.Key.Vertex1, shortcutForward, null, vertex,
out localAdded, out localRemoved);
added += localAdded;
removed += localRemoved;
//added += 2;
//addedWeight += shortcutForward;
//addedWeight += shortcutBackward;
}
else
{
if (shortcutForward > 0 && shortcutForward < float.MaxValue)
{
graph.TryAddOrUpdateEdge(shortcut.Key.Vertex1, shortcut.Key.Vertex2, shortcutForward, true, vertex,
out localAdded, out localRemoved);
added += localAdded;
removed += localRemoved;
graph.TryAddOrUpdateEdge(shortcut.Key.Vertex2, shortcut.Key.Vertex1, shortcutForward, false, vertex,
out localAdded, out localRemoved);
added += localAdded;
removed += localRemoved;
//added += 2;
//addedWeight += shortcutForward;
//addedWeight += shortcutForward;
}
if (shortcutBackward > 0 && shortcutBackward < float.MaxValue)
{
graph.TryAddOrUpdateEdge(shortcut.Key.Vertex1, shortcut.Key.Vertex2, shortcutBackward, false, vertex,
out localAdded, out localRemoved);
added += localAdded;
removed += localRemoved;
graph.TryAddOrUpdateEdge(shortcut.Key.Vertex2, shortcut.Key.Vertex1, shortcutBackward, true, vertex,
out localAdded, out localRemoved);
added += localAdded;
removed += localRemoved;
//added += 2;
//addedWeight += shortcutBackward;
//addedWeight += shortcutBackward;
}
}
}
//for (var e = 0; e < vertexInfo.Count; e++)
//{
// var w = weightHandler.GetEdgeWeight(vertexInfo[e]);
// var wMetric = weightHandler.GetMetric(w.Weight);
// if (w.Direction.F)
// {
// removedWeight += wMetric;
// }
// if (w.Direction.B)
// {
// removedWeight += wMetric;
// }
//}
var weigthDiff = 1f;
//if (removedWeight != 0)
//{
// weigthDiff = removedWeight;
//}
return (differenceFactor * (added - removed) + (depthFactor * vertexInfo.Depth) +
(contractedFactor * vertexInfo.ContractedNeighbours)) * (weigthDiff * weightDiffFactor);
//return ((differenceFactor * (2 * added - 4 * removed)) / 2 + (depthFactor * vertexInfo.Depth) +
// (contractedFactor * vertexInfo.ContractedNeighbours));// * (weigthDiff * weightDiffFactor);
}
public static bool RemoveShortcuts<T>(this VertexInfo<T> vertexInfo, DirectedGraph witnessGraph, WeightHandler<T> weightHandler)
where T : struct
{
var witnessGraphEnumerator = witnessGraph.GetEdgeEnumerator();
List<Tuple<OriginalEdge, Shortcut<T>>> toUpdate = null;
foreach (var pair in vertexInfo.Shortcuts)
{
var edge = pair.Key;
if (edge.Vertex1 >= witnessGraph.VertexCount ||
edge.Vertex2 >= witnessGraph.VertexCount)
{
continue;
}
var shortcut = pair.Value;
var shortcutForward = weightHandler.GetMetric(shortcut.Forward);
var shortcutBackward = weightHandler.GetMetric(shortcut.Backward);
var witnessedForward = float.MaxValue;
var witnessedBackward = float.MaxValue;
if (edge.Vertex1 < edge.Vertex2)
{
witnessGraphEnumerator.MoveTo(edge.Vertex1);
while (witnessGraphEnumerator.MoveNext())
{
if (witnessGraphEnumerator.Neighbour == edge.Vertex2)
{
witnessedForward = DirectedGraphExtensions.FromData(witnessGraphEnumerator.Data0);
witnessedBackward = DirectedGraphExtensions.FromData(witnessGraphEnumerator.Data1);
break;
}
}
}
else
{
witnessGraphEnumerator.MoveTo(edge.Vertex2);
while (witnessGraphEnumerator.MoveNext())
{
if (witnessGraphEnumerator.Neighbour == edge.Vertex1)
{
witnessedBackward = DirectedGraphExtensions.FromData(witnessGraphEnumerator.Data0);
witnessedForward = DirectedGraphExtensions.FromData(witnessGraphEnumerator.Data1);
break;
}
}
}
// check forward.
var hasUpdates = false;
if (shortcutForward > 0 && shortcutForward < float.MaxValue &&
shortcutForward - FastHierarchyBuilder<float>.E > witnessedForward)
{
shortcut.Forward = weightHandler.Infinite;
hasUpdates = true;
}
if (shortcutBackward > 0 && shortcutBackward < float.MaxValue &&
shortcutBackward - FastHierarchyBuilder<float>.E > witnessedBackward)
{
shortcut.Backward = weightHandler.Infinite;
hasUpdates = true;
}
if (hasUpdates)
{
if (toUpdate == null)
{
toUpdate = new List<Tuple<OriginalEdge, Shortcut<T>>>();
}
toUpdate.Add(new Tuple<OriginalEdge, Shortcut<T>>(edge, shortcut));
}
}
if (toUpdate != null)
{
foreach (var update in toUpdate)
{
vertexInfo.Shortcuts[update.Item1] = update.Item2;
}
return true;
}
return false;
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Reactive.Linq;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace Avalonia.Controls.Presenters
{
public class TextPresenter : TextBlock
{
public static readonly DirectProperty<TextPresenter, int> CaretIndexProperty =
TextBox.CaretIndexProperty.AddOwner<TextPresenter>(
o => o.CaretIndex,
(o, v) => o.CaretIndex = v);
public static readonly StyledProperty<char> PasswordCharProperty =
AvaloniaProperty.Register<TextPresenter, char>(nameof(PasswordChar));
public static readonly DirectProperty<TextPresenter, int> SelectionStartProperty =
TextBox.SelectionStartProperty.AddOwner<TextPresenter>(
o => o.SelectionStart,
(o, v) => o.SelectionStart = v);
public static readonly DirectProperty<TextPresenter, int> SelectionEndProperty =
TextBox.SelectionEndProperty.AddOwner<TextPresenter>(
o => o.SelectionEnd,
(o, v) => o.SelectionEnd = v);
private readonly DispatcherTimer _caretTimer;
private int _caretIndex;
private int _selectionStart;
private int _selectionEnd;
private bool _caretBlink;
private IBrush _highlightBrush;
static TextPresenter()
{
AffectsRender<TextPresenter>(PasswordCharProperty);
}
public TextPresenter()
{
_caretTimer = new DispatcherTimer();
_caretTimer.Interval = TimeSpan.FromMilliseconds(500);
_caretTimer.Tick += CaretTimerTick;
Observable.Merge(
this.GetObservable(SelectionStartProperty),
this.GetObservable(SelectionEndProperty))
.Subscribe(_ => InvalidateFormattedText());
this.GetObservable(CaretIndexProperty)
.Subscribe(CaretIndexChanged);
this.GetObservable(PasswordCharProperty)
.Subscribe(_ => InvalidateFormattedText());
}
public int CaretIndex
{
get
{
return _caretIndex;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
}
}
public char PasswordChar
{
get => GetValue(PasswordCharProperty);
set => SetValue(PasswordCharProperty, value);
}
public int SelectionStart
{
get
{
return _selectionStart;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
}
}
public int SelectionEnd
{
get
{
return _selectionEnd;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
}
}
public int GetCaretIndex(Point point)
{
var hit = FormattedText.HitTestPoint(point);
return hit.TextPosition + (hit.IsTrailing ? 1 : 0);
}
public override void Render(DrawingContext context)
{
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
if (selectionStart != selectionEnd)
{
var start = Math.Min(selectionStart, selectionEnd);
var length = Math.Max(selectionStart, selectionEnd) - start;
// issue #600: set constraint before any FormattedText manipulation
// see base.Render(...) implementation
FormattedText.Constraint = Bounds.Size;
var rects = FormattedText.HitTestTextRange(start, length);
if (_highlightBrush == null)
{
_highlightBrush = (IBrush)this.FindResource("HighlightBrush");
}
foreach (var rect in rects)
{
context.FillRectangle(_highlightBrush, rect);
}
}
base.Render(context);
if (selectionStart == selectionEnd)
{
var backgroundColor = (((Control)TemplatedParent).GetValue(BackgroundProperty) as SolidColorBrush)?.Color;
var caretBrush = Brushes.Black;
if (backgroundColor.HasValue)
{
byte red = (byte)~(backgroundColor.Value.R);
byte green = (byte)~(backgroundColor.Value.G);
byte blue = (byte)~(backgroundColor.Value.B);
caretBrush = new SolidColorBrush(Color.FromRgb(red, green, blue));
}
if (_caretBlink)
{
var charPos = FormattedText.HitTestTextPosition(CaretIndex);
var x = Math.Floor(charPos.X) + 0.5;
var y = Math.Floor(charPos.Y) + 0.5;
var b = Math.Ceiling(charPos.Bottom) - 0.5;
context.DrawLine(
new Pen(caretBrush, 1),
new Point(x, y),
new Point(x, b));
}
}
}
public void ShowCaret()
{
_caretBlink = true;
_caretTimer.Start();
InvalidateVisual();
}
public void HideCaret()
{
_caretBlink = false;
_caretTimer.Stop();
InvalidateVisual();
}
internal void CaretIndexChanged(int caretIndex)
{
if (this.GetVisualParent() != null)
{
if (_caretTimer.IsEnabled)
{
_caretBlink = true;
_caretTimer.Stop();
_caretTimer.Start();
InvalidateVisual();
}
else
{
_caretTimer.Start();
InvalidateVisual();
_caretTimer.Stop();
}
if (IsMeasureValid)
{
var rect = FormattedText.HitTestTextPosition(caretIndex);
this.BringIntoView(rect);
}
else
{
// The measure is currently invalid so there's no point trying to bring the
// current char into view until a measure has been carried out as the scroll
// viewer extents may not be up-to-date.
Dispatcher.UIThread.Post(
() =>
{
var rect = FormattedText.HitTestTextPosition(caretIndex);
this.BringIntoView(rect);
},
DispatcherPriority.Normal);
}
}
}
/// <summary>
/// Creates the <see cref="FormattedText"/> used to render the text.
/// </summary>
/// <param name="constraint">The constraint of the text.</param>
/// <param name="text">The text to generated the <see cref="FormattedText"/> for.</param>
/// <returns>A <see cref="FormattedText"/> object.</returns>
protected override FormattedText CreateFormattedText(Size constraint, string text)
{
FormattedText result = null;
if (PasswordChar != default(char))
{
result = base.CreateFormattedText(constraint, new string(PasswordChar, text?.Length ?? 0));
}
else
{
result = base.CreateFormattedText(constraint, text);
}
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd);
var length = Math.Max(selectionStart, selectionEnd) - start;
if (length > 0)
{
result.Spans = new[]
{
new FormattedTextStyleSpan(start, length, foregroundBrush: Brushes.White),
};
}
return result;
}
protected override Size MeasureOverride(Size availableSize)
{
var text = Text;
if (!string.IsNullOrEmpty(text))
{
return base.MeasureOverride(availableSize);
}
else
{
return new FormattedText
{
Text = "X",
Typeface = new Typeface(FontFamily, FontSize, FontStyle, FontWeight),
TextAlignment = TextAlignment,
Constraint = availableSize,
}.Measure();
}
}
private int CoerceCaretIndex(int value)
{
var text = Text;
var length = text?.Length ?? 0;
return Math.Max(0, Math.Min(length, value));
}
private void CaretTimerTick(object sender, EventArgs e)
{
_caretBlink = !_caretBlink;
InvalidateVisual();
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Moq.Language;
using Moq.Language.Flow;
namespace Moq
{
/// <summary>
/// Defines async extension methods on IReturns.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class GeneratedReturnsExtensions
{
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <typeparam name="T">Type of the function parameter.</typeparam>
/// <typeparam name="TMock">Mocked type.</typeparam>
/// <typeparam name="TResult">Type of the return value.</typeparam>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T t) => Task.FromResult(valueFunction(t)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2) => Task.FromResult(valueFunction(t1, t2)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3) => Task.FromResult(valueFunction(t1, t2, t3)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4) => Task.FromResult(valueFunction(t1, t2, t3, t4)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TMock, TResult>(this IReturns<TMock, Task<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult> valueFunction) where TMock : class
{
if (ReturnsExtensions.IsNullResult(valueFunction, typeof(TResult)))
{
return mock.ReturnsAsync(() => default);
}
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <typeparam name="T">Type of the function parameter.</typeparam>
/// <typeparam name="TMock">Mocked type.</typeparam>
/// <typeparam name="TResult">Type of the return value.</typeparam>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T, TResult> valueFunction) where TMock : class
{
return mock.Returns((T t) => new ValueTask<TResult>(valueFunction(t)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2) => new ValueTask<TResult>(valueFunction(t1, t2)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3) => new ValueTask<TResult>(valueFunction(t1, t2, t3)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5, t6)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5, t6, t7)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14)));
}
/// <summary>
/// Specifies a function that will calculate the value to return from the asynchronous method.
/// </summary>
/// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
/// <param name="valueFunction">The function that will calculate the return value.</param>
public static IReturnsResult<TMock> ReturnsAsync<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TMock, TResult>(this IReturns<TMock, ValueTask<TResult>> mock, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult> valueFunction) where TMock : class
{
return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15) => new ValueTask<TResult>(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15)));
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Families
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class DF : EduHubEntity
{
#region Navigation Property Cache
private KGL Cache_NATIVE_LANG_A_KGL;
private KGL Cache_OTHER_LANG_A_KGL;
private KGT Cache_BIRTH_COUNTRY_A_KGT;
private KGL Cache_LOTE_HOME_CODE_A_KGL;
private KGL Cache_NATIVE_LANG_B_KGL;
private KGL Cache_OTHER_LANG_B_KGL;
private KGT Cache_BIRTH_COUNTRY_B_KGT;
private KGL Cache_LOTE_HOME_CODE_B_KGL;
private KGL Cache_PREF_NOTICE_LANG_KGL;
private UM Cache_HOMEKEY_UM;
private UM Cache_MAILKEY_UM;
private UM Cache_BILLINGKEY_UM;
private KCD Cache_DOCTOR_KCD;
private KGL Cache_EMERG_LANG01_KGL;
private KGL Cache_EMERG_LANG02_KGL;
private KGL Cache_EMERG_LANG03_KGL;
private KGL Cache_EMERG_LANG04_KGL;
private KGL Cache_HOME_LANG_KGL;
#endregion
#region Foreign Navigation Properties
private IReadOnlyList<DFB> Cache_DFKEY_DFB_FAM_CODE;
private IReadOnlyList<DFF> Cache_DFKEY_DFF_CODE;
private IReadOnlyList<DFHI> Cache_DFKEY_DFHI_FKEY;
private IReadOnlyList<DFVT> Cache_DFKEY_DFVT_FAMILY;
private IReadOnlyList<ST> Cache_DFKEY_ST_FAMILY;
private IReadOnlyList<ST> Cache_DFKEY_ST_FAMB;
private IReadOnlyList<ST> Cache_DFKEY_ST_FAMC;
private IReadOnlyList<STSB> Cache_DFKEY_STSB_FAMILY;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Family ID
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string DFKEY { get; internal set; }
/// <summary>
/// (Was MNAME) Parent/guardian A first given name
/// [Alphanumeric (30)]
/// </summary>
public string NAME_A { get; internal set; }
/// <summary>
/// (Was MSURNAME) Parent/guardian A surname (default SURNAME)
/// [Uppercase Alphanumeric (30)]
/// </summary>
public string SURNAME_A { get; internal set; }
/// <summary>
/// (Was MTITLE) Parent/guardian A title
/// [Titlecase (4)]
/// </summary>
public string TITLE_A { get; internal set; }
/// <summary>
/// (Was MWORK_CONT) Can parent/guardian A be contacted at work? (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string WORK_CONT_A { get; internal set; }
/// <summary>
/// (Was MOCCUPATION) Parent/guardian A occupation
/// [Alphanumeric (35)]
/// </summary>
public string OCCUPATION_A { get; internal set; }
/// <summary>
/// (Was MEMPLOYER) Parent/guardian A employer
/// [Alphanumeric (30)]
/// </summary>
public string EMPLOYER_A { get; internal set; }
/// <summary>
/// (Was MNATIVE_LANG) Parent/guardian A native language
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string NATIVE_LANG_A { get; internal set; }
/// <summary>
/// (Was M_OTHER_LANG) Parent/guardian A other language
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string OTHER_LANG_A { get; internal set; }
/// <summary>
/// (Was M_INTERPRETER) Parent/guardian A requires interpreter? Y=Yes, N=No, S=Sometimes
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string INTERPRETER_A { get; internal set; }
/// <summary>
/// (Was MBIRTH_COUNTRY) Parent/guardian A country of birth
/// [Uppercase Alphanumeric (6)]
/// </summary>
public string BIRTH_COUNTRY_A { get; internal set; }
/// <summary>
/// Parent/guardian A at home during business hours? (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string BH_AT_HOME_A { get; internal set; }
/// <summary>
/// Parent/guardian A telephone contact if not at home during business hours
/// [Alphanumeric (20)]
/// </summary>
public string BH_CONTACT_A { get; internal set; }
/// <summary>
/// Parent/guardian A telephone contact if not at home during business hours
/// [Memo]
/// </summary>
public string BH_CONTACT_A_MEMO { get; internal set; }
/// <summary>
/// Parent/guardian A at home after hours? (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string AH_AT_HOME_A { get; internal set; }
/// <summary>
/// Parent/guardian A telephone contact if not at home after hours
/// [Alphanumeric (20)]
/// </summary>
public string AH_CONTACT_A { get; internal set; }
/// <summary>
/// Parent/guardian A telephone contact if not at home after hours
/// [Memo]
/// </summary>
public string AH_CONTACT_A_MEMO { get; internal set; }
/// <summary>
/// (Was M_E_MAIL) Parent/guardian A e-mail address
/// [Alphanumeric (60)]
/// </summary>
public string E_MAIL_A { get; internal set; }
/// <summary>
/// (Was PREF_COM_A) Parent/guardian A preferred mail mechanism: M=Mail, E=E-mail, F=Fax, P=Phone
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string PREF_MAIL_MECH_A { get; internal set; }
/// <summary>
/// Parent/guardian A fax number
/// [Uppercase Alphanumeric (20)]
/// </summary>
public string FAX_A { get; internal set; }
/// <summary>
/// Parent/guardian A gender: M=Male, F=Female
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string GENDER_A { get; internal set; }
/// <summary>
/// Parent/guardian A School Education
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string SCH_ED_A { get; internal set; }
/// <summary>
/// Parent/guardian A Non School Education (0,5-8)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string NON_SCH_ED_A { get; internal set; }
/// <summary>
/// Parent/guardian A Occupation Status (A,B,C,D,N,U)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string OCCUP_STATUS_A { get; internal set; }
/// <summary>
/// The Language other than English spoken at home by parent/guardian A
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string LOTE_HOME_CODE_A { get; internal set; }
/// <summary>
/// Parent/guardian A mobile number
/// [Uppercase Alphanumeric (20)]
/// </summary>
public string MOBILE_A { get; internal set; }
/// <summary>
/// SMS can be used to notify this parent
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string SMS_NOTIFY_A { get; internal set; }
/// <summary>
/// Email can be used to notify this parent
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string E_MAIL_NOTIFY_A { get; internal set; }
/// <summary>
/// Working With Children Check card number
/// [Uppercase Alphanumeric (11)]
/// </summary>
public string WWCC_NUMBER_A { get; internal set; }
/// <summary>
/// WWCC expiry date
/// </summary>
public DateTime? WWCC_EXPIRY_A { get; internal set; }
/// <summary>
/// WWCC card Type E=Employee, V=Volunteer
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string WWCC_TYPE_A { get; internal set; }
/// <summary>
/// (Was FNAME) Parent/guardian B first given name
/// [Alphanumeric (30)]
/// </summary>
public string NAME_B { get; internal set; }
/// <summary>
/// (Was FSURNAME) Parent/guardian B surname (default SURNAME)
/// [Uppercase Alphanumeric (30)]
/// </summary>
public string SURNAME_B { get; internal set; }
/// <summary>
/// (Was FTITLE) Parent/guardian B title
/// [Titlecase (4)]
/// </summary>
public string TITLE_B { get; internal set; }
/// <summary>
/// (Was FWORK_CONT) Can parent/guardian B be contacted at work? (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string WORK_CONT_B { get; internal set; }
/// <summary>
/// (Was FOCCUPATION) Parent/guardian B occupation
/// [Alphanumeric (35)]
/// </summary>
public string OCCUPATION_B { get; internal set; }
/// <summary>
/// (Was FEMPLOYER) Parent/guardian B employer
/// [Alphanumeric (30)]
/// </summary>
public string EMPLOYER_B { get; internal set; }
/// <summary>
/// (Was FNATIVE_LANG) Parent/guardian B native language
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string NATIVE_LANG_B { get; internal set; }
/// <summary>
/// (Was F_OTHER_LANG) Parent/guardian B other language
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string OTHER_LANG_B { get; internal set; }
/// <summary>
/// (Was F_INTERPRETER) Parent/guardian B requires interpreter? Y=Yes, N=No, S=Sometimes
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string INTERPRETER_B { get; internal set; }
/// <summary>
/// (Was FBIRTH_COUNTRY) Parent/guardian B country of birth
/// [Uppercase Alphanumeric (6)]
/// </summary>
public string BIRTH_COUNTRY_B { get; internal set; }
/// <summary>
/// Parent/guardian B at home during business hours? (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string BH_AT_HOME_B { get; internal set; }
/// <summary>
/// Parent/guardian B telephone contact if not at home during business hours
/// [Alphanumeric (20)]
/// </summary>
public string BH_CONTACT_B { get; internal set; }
/// <summary>
/// Parent/guardian B telephone contact if not at home during business hours
/// [Memo]
/// </summary>
public string BH_CONTACT_B_MEMO { get; internal set; }
/// <summary>
/// Parent/guardian B at home after hours? (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string AH_AT_HOME_B { get; internal set; }
/// <summary>
/// Parent/guardian B telephone contact if not at home after hours
/// [Alphanumeric (20)]
/// </summary>
public string AH_CONTACT_B { get; internal set; }
/// <summary>
/// Parent/guardian B telephone contact if not at home after hours
/// [Memo]
/// </summary>
public string AH_CONTACT_B_MEMO { get; internal set; }
/// <summary>
/// (Was F_E_MAIL) Parent/guardian B e-mail address
/// [Alphanumeric (60)]
/// </summary>
public string E_MAIL_B { get; internal set; }
/// <summary>
/// (Was PREF_COM_B) Parent/guardian B preferred mail mechanism: M=Mail, E=E-mail, F=Fax, P=Phone
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string PREF_MAIL_MECH_B { get; internal set; }
/// <summary>
/// Parent/guardian B fax number
/// [Uppercase Alphanumeric (20)]
/// </summary>
public string FAX_B { get; internal set; }
/// <summary>
/// Parent/guardian B gender: M=Male, F=Female
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string GENDER_B { get; internal set; }
/// <summary>
/// Parent/guardian B School Education (0-4)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string SCH_ED_B { get; internal set; }
/// <summary>
/// Parent/guardian B Non School Education (0,5-8)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string NON_SCH_ED_B { get; internal set; }
/// <summary>
/// Parent/guardian B Occupation Status (A,B,C,D,N,U)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string OCCUP_STATUS_B { get; internal set; }
/// <summary>
/// The Language other than English spoken at home by parent/guardian B
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string LOTE_HOME_CODE_B { get; internal set; }
/// <summary>
/// Parent/guardian B mobile number
/// [Uppercase Alphanumeric (20)]
/// </summary>
public string MOBILE_B { get; internal set; }
/// <summary>
/// SMS can be used to notify this parent
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string SMS_NOTIFY_B { get; internal set; }
/// <summary>
/// Email can be used to notify this parent
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string E_MAIL_NOTIFY_B { get; internal set; }
/// <summary>
/// Working With Children Check card number
/// [Uppercase Alphanumeric (11)]
/// </summary>
public string WWCC_NUMBER_B { get; internal set; }
/// <summary>
/// WWCC expiry date
/// </summary>
public DateTime? WWCC_EXPIRY_B { get; internal set; }
/// <summary>
/// WWCC card Type E=Employee, V=Volunteer
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string WWCC_TYPE_B { get; internal set; }
/// <summary>
/// Preferred language for notices
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string PREF_NOTICE_LANG { get; internal set; }
/// <summary>
/// (Was SG_PARTICIPATION) Special group participation: 1=Adult A, 2=Adult B, B=Both
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string GROUP_AVAILABILITY { get; internal set; }
/// <summary>
/// (Was FAM_OCCUP) Family occupation status group (1-5)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string OCCUP_STATUS_GRP { get; internal set; }
/// <summary>
/// Home addressee
/// [Titlecase (30)]
/// </summary>
public string HOMETITLE { get; internal set; }
/// <summary>
/// Home address ID
/// </summary>
public int? HOMEKEY { get; internal set; }
/// <summary>
/// Mail addressee
/// [Titlecase (30)]
/// </summary>
public string MAILTITLE { get; internal set; }
/// <summary>
/// Mail address ID
/// </summary>
public int? MAILKEY { get; internal set; }
/// <summary>
/// Billing name
/// [Titlecase (40)]
/// </summary>
public string BILLINGTITLE { get; internal set; }
/// <summary>
/// Billing address ID
/// </summary>
public int? BILLINGKEY { get; internal set; }
/// <summary>
/// Billing memo
/// [Memo]
/// </summary>
public string BILLING_MEMO { get; internal set; }
/// <summary>
/// Account type: 0=Brought forward, 1=Open item
/// </summary>
public short? ACCTYPE { get; internal set; }
/// <summary>
/// Aged balances
/// </summary>
public decimal? AGED01 { get; internal set; }
/// <summary>
/// Aged balances
/// </summary>
public decimal? AGED02 { get; internal set; }
/// <summary>
/// Aged balances
/// </summary>
public decimal? AGED03 { get; internal set; }
/// <summary>
/// Aged balances
/// </summary>
public decimal? AGED04 { get; internal set; }
/// <summary>
/// Aged balances
/// </summary>
public decimal? AGED05 { get; internal set; }
/// <summary>
/// Amount received in payment but not yet allocated to an invoice
/// </summary>
public decimal? ALLOCAMT { get; internal set; }
/// <summary>
/// Charges this year
/// </summary>
public decimal? CHARGES { get; internal set; }
/// <summary>
/// Last receipt amount
/// </summary>
public decimal? LASTREC { get; internal set; }
/// <summary>
/// Last receipt date
/// </summary>
public DateTime? LASTRECDATE { get; internal set; }
/// <summary>
/// Opening balance
/// </summary>
public decimal? OPBAL { get; internal set; }
/// <summary>
/// Opening balance at start of year
/// </summary>
public decimal? OPBAL_YEAR { get; internal set; }
/// <summary>
/// Auto access inventory price level: related to sale of stock items to families: to be retained at present
/// </summary>
public short? PRICELEVEL { get; internal set; }
/// <summary>
/// Seed number for BPAY reference
/// </summary>
public int? BPAY_SEQUENCE { get; internal set; }
/// <summary>
/// BPAY Reference number with check digit
/// [Alphanumeric (20)]
/// </summary>
public string BPAY_REFERENCE { get; internal set; }
/// <summary>
/// Number of current students for which this family is the PRIME family (automatically maintained by software) (cf NO_ASSOC_STUDENTS)
/// </summary>
public short? NO_STUDENTS { get; internal set; }
/// <summary>
/// Number of current students with which this family is associated (as Prime, Alternative or Additional family) (cf NO_STUDENTS)
/// </summary>
public short? NO_ASSOC_STUDENTS { get; internal set; }
/// <summary>
/// Credit limit
/// </summary>
public decimal? CREDIT_LIMIT { get; internal set; }
/// <summary>
/// Billing group
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string BILL_GROUP { get; internal set; }
/// <summary>
/// Reference to local doctor (default for each student)
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string DOCTOR { get; internal set; }
/// <summary>
/// Name(s) of person(s) to contact in an emergency
/// [Titlecase (30)]
/// </summary>
public string EMERG_NAME01 { get; internal set; }
/// <summary>
/// Name(s) of person(s) to contact in an emergency
/// [Titlecase (30)]
/// </summary>
public string EMERG_NAME02 { get; internal set; }
/// <summary>
/// Name(s) of person(s) to contact in an emergency
/// [Titlecase (30)]
/// </summary>
public string EMERG_NAME03 { get; internal set; }
/// <summary>
/// Name(s) of person(s) to contact in an emergency
/// [Titlecase (30)]
/// </summary>
public string EMERG_NAME04 { get; internal set; }
/// <summary>
/// Relationship to a student in this family of each person to contact in an emergency
/// [Alphanumeric (20)]
/// </summary>
public string EMERG_RELATION01 { get; internal set; }
/// <summary>
/// Relationship to a student in this family of each person to contact in an emergency
/// [Alphanumeric (20)]
/// </summary>
public string EMERG_RELATION02 { get; internal set; }
/// <summary>
/// Relationship to a student in this family of each person to contact in an emergency
/// [Alphanumeric (20)]
/// </summary>
public string EMERG_RELATION03 { get; internal set; }
/// <summary>
/// Relationship to a student in this family of each person to contact in an emergency
/// [Alphanumeric (20)]
/// </summary>
public string EMERG_RELATION04 { get; internal set; }
/// <summary>
/// Language spoken by person(s) to contact in an emergency
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string EMERG_LANG01 { get; internal set; }
/// <summary>
/// Language spoken by person(s) to contact in an emergency
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string EMERG_LANG02 { get; internal set; }
/// <summary>
/// Language spoken by person(s) to contact in an emergency
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string EMERG_LANG03 { get; internal set; }
/// <summary>
/// Language spoken by person(s) to contact in an emergency
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string EMERG_LANG04 { get; internal set; }
/// <summary>
/// Contact details for each person to contact in an emergency
/// [Alphanumeric (20)]
/// </summary>
public string EMERG_CONTACT01 { get; internal set; }
/// <summary>
/// Contact details for each person to contact in an emergency
/// [Alphanumeric (20)]
/// </summary>
public string EMERG_CONTACT02 { get; internal set; }
/// <summary>
/// Contact details for each person to contact in an emergency
/// [Alphanumeric (20)]
/// </summary>
public string EMERG_CONTACT03 { get; internal set; }
/// <summary>
/// Contact details for each person to contact in an emergency
/// [Alphanumeric (20)]
/// </summary>
public string EMERG_CONTACT04 { get; internal set; }
/// <summary>
/// Contact details for each person to contact in an emergency
/// [Memo]
/// </summary>
public string EMERG_CONTACT_MEMO01 { get; internal set; }
/// <summary>
/// Contact details for each person to contact in an emergency
/// [Memo]
/// </summary>
public string EMERG_CONTACT_MEMO02 { get; internal set; }
/// <summary>
/// Contact details for each person to contact in an emergency
/// [Memo]
/// </summary>
public string EMERG_CONTACT_MEMO03 { get; internal set; }
/// <summary>
/// Contact details for each person to contact in an emergency
/// [Memo]
/// </summary>
public string EMERG_CONTACT_MEMO04 { get; internal set; }
/// <summary>
/// School has received authority to react to accident? (Y/N) (default for each student)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string ACC_DECLARATION { get; internal set; }
/// <summary>
/// (Was CALL_AMBULANCE) Family has ambulance subscription? (Y/N) (default for each student)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string AMBULANCE_SUBSCRIBER { get; internal set; }
/// <summary>
/// Medicare No (default for each student)
/// [Uppercase Alphanumeric (12)]
/// </summary>
public string MEDICARE_NO { get; internal set; }
/// <summary>
/// The language spoken at home
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string HOME_LANG { get; internal set; }
/// <summary>
/// Cheque Account Name
/// [Alphanumeric (30)]
/// </summary>
public string DRAWER { get; internal set; }
/// <summary>
/// Cheque BSB Number
/// [Alphanumeric (6)]
/// </summary>
public string BSB { get; internal set; }
/// <summary>
/// Does debtor require tax invoices for GST? (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string TAX_INVOICE { get; internal set; }
/// <summary>
/// The ABN number for this debtor
/// [Uppercase Alphanumeric (15)]
/// </summary>
public string ABN { get; internal set; }
/// <summary>
/// General Email address for emailing financial statements direct to families
/// [Alphanumeric (60)]
/// </summary>
public string BILLING_EMAIL { get; internal set; }
/// <summary>
/// Preferred Email: A=Adult A e-mail, B=Adult B e-mail, C=Billing e-mail
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string PREF_EMAIL { get; internal set; }
/// <summary>
/// User Id for eMaze
/// [Alphanumeric (32)]
/// </summary>
public string USER_NAME { get; internal set; }
/// <summary>
/// Access from web allowed using USER_NAME
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string WEB_ENABLED { get; internal set; }
/// <summary>
/// ID of the record of this family in the CASES system
/// [Uppercase Alphanumeric (7)]
/// </summary>
public string CASES_KEY { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public DateTime? EMA_APPLY_DATE { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string EMA_APPLY { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Uppercase Alphanumeric (30)]
/// </summary>
public string DSS_SURNAME { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Titlecase (30)]
/// </summary>
public string DSS_FIRST_NAME { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Alphanumeric (5)]
/// </summary>
public string SSN_ELIG_CODE { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Uppercase Alphanumeric (15)]
/// </summary>
public string SSN { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public decimal? EMA_TOTAL1P { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public short? EMA_STAT1P { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public decimal? EMA_TOTAL2P { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public short? EMA_STAT2P { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string EMA_CLAIM_VN { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string EMA_SEND { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string EMA_CLAIM_PD { get; internal set; }
/// <summary>
/// CSEF identifier for existing families
/// [Alphanumeric (10)]
/// </summary>
public string CASES_EMA_ID { get; internal set; }
/// <summary>
/// Date last udpated
/// </summary>
public DateTime? SCH_ED_A_LU { get; internal set; }
/// <summary>
/// Date last udpated
/// </summary>
public DateTime? NON_SCH_ED_A_LU { get; internal set; }
/// <summary>
/// Date last udpated
/// </summary>
public DateTime? OCCUP_STATUS_A_LU { get; internal set; }
/// <summary>
/// Date last udpated
/// </summary>
public DateTime? SCH_ED_B_LU { get; internal set; }
/// <summary>
/// Date last udpated
/// </summary>
public DateTime? NON_SCH_ED_B_LU { get; internal set; }
/// <summary>
/// Date last udpated
/// </summary>
public DateTime? OCCUP_STATUS_B_LU { get; internal set; }
/// <summary>
/// Calculated Non School Education
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CNSE { get; internal set; }
/// <summary>
/// Calculated School Education
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CSE { get; internal set; }
/// <summary>
/// Final Education Value
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string FSE { get; internal set; }
/// <summary>
/// Parent/guardian A Self-described Gender
/// [Alphanumeric (100)]
/// </summary>
public string GENDER_DESC_A { get; internal set; }
/// <summary>
/// Parent/guardian B Self-described Gender
/// [Alphanumeric (100)]
/// </summary>
public string GENDER_DESC_B { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last write operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// KGL (Languages) related entity by [DF.NATIVE_LANG_A]->[KGL.KGLKEY]
/// (Was MNATIVE_LANG) Parent/guardian A native language
/// </summary>
public KGL NATIVE_LANG_A_KGL
{
get
{
if (NATIVE_LANG_A == null)
{
return null;
}
if (Cache_NATIVE_LANG_A_KGL == null)
{
Cache_NATIVE_LANG_A_KGL = Context.KGL.FindByKGLKEY(NATIVE_LANG_A);
}
return Cache_NATIVE_LANG_A_KGL;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.OTHER_LANG_A]->[KGL.KGLKEY]
/// (Was M_OTHER_LANG) Parent/guardian A other language
/// </summary>
public KGL OTHER_LANG_A_KGL
{
get
{
if (OTHER_LANG_A == null)
{
return null;
}
if (Cache_OTHER_LANG_A_KGL == null)
{
Cache_OTHER_LANG_A_KGL = Context.KGL.FindByKGLKEY(OTHER_LANG_A);
}
return Cache_OTHER_LANG_A_KGL;
}
}
/// <summary>
/// KGT (Countries) related entity by [DF.BIRTH_COUNTRY_A]->[KGT.COUNTRY]
/// (Was MBIRTH_COUNTRY) Parent/guardian A country of birth
/// </summary>
public KGT BIRTH_COUNTRY_A_KGT
{
get
{
if (BIRTH_COUNTRY_A == null)
{
return null;
}
if (Cache_BIRTH_COUNTRY_A_KGT == null)
{
Cache_BIRTH_COUNTRY_A_KGT = Context.KGT.FindByCOUNTRY(BIRTH_COUNTRY_A);
}
return Cache_BIRTH_COUNTRY_A_KGT;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.LOTE_HOME_CODE_A]->[KGL.KGLKEY]
/// The Language other than English spoken at home by parent/guardian A
/// </summary>
public KGL LOTE_HOME_CODE_A_KGL
{
get
{
if (LOTE_HOME_CODE_A == null)
{
return null;
}
if (Cache_LOTE_HOME_CODE_A_KGL == null)
{
Cache_LOTE_HOME_CODE_A_KGL = Context.KGL.FindByKGLKEY(LOTE_HOME_CODE_A);
}
return Cache_LOTE_HOME_CODE_A_KGL;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.NATIVE_LANG_B]->[KGL.KGLKEY]
/// (Was FNATIVE_LANG) Parent/guardian B native language
/// </summary>
public KGL NATIVE_LANG_B_KGL
{
get
{
if (NATIVE_LANG_B == null)
{
return null;
}
if (Cache_NATIVE_LANG_B_KGL == null)
{
Cache_NATIVE_LANG_B_KGL = Context.KGL.FindByKGLKEY(NATIVE_LANG_B);
}
return Cache_NATIVE_LANG_B_KGL;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.OTHER_LANG_B]->[KGL.KGLKEY]
/// (Was F_OTHER_LANG) Parent/guardian B other language
/// </summary>
public KGL OTHER_LANG_B_KGL
{
get
{
if (OTHER_LANG_B == null)
{
return null;
}
if (Cache_OTHER_LANG_B_KGL == null)
{
Cache_OTHER_LANG_B_KGL = Context.KGL.FindByKGLKEY(OTHER_LANG_B);
}
return Cache_OTHER_LANG_B_KGL;
}
}
/// <summary>
/// KGT (Countries) related entity by [DF.BIRTH_COUNTRY_B]->[KGT.COUNTRY]
/// (Was FBIRTH_COUNTRY) Parent/guardian B country of birth
/// </summary>
public KGT BIRTH_COUNTRY_B_KGT
{
get
{
if (BIRTH_COUNTRY_B == null)
{
return null;
}
if (Cache_BIRTH_COUNTRY_B_KGT == null)
{
Cache_BIRTH_COUNTRY_B_KGT = Context.KGT.FindByCOUNTRY(BIRTH_COUNTRY_B);
}
return Cache_BIRTH_COUNTRY_B_KGT;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.LOTE_HOME_CODE_B]->[KGL.KGLKEY]
/// The Language other than English spoken at home by parent/guardian B
/// </summary>
public KGL LOTE_HOME_CODE_B_KGL
{
get
{
if (LOTE_HOME_CODE_B == null)
{
return null;
}
if (Cache_LOTE_HOME_CODE_B_KGL == null)
{
Cache_LOTE_HOME_CODE_B_KGL = Context.KGL.FindByKGLKEY(LOTE_HOME_CODE_B);
}
return Cache_LOTE_HOME_CODE_B_KGL;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.PREF_NOTICE_LANG]->[KGL.KGLKEY]
/// Preferred language for notices
/// </summary>
public KGL PREF_NOTICE_LANG_KGL
{
get
{
if (PREF_NOTICE_LANG == null)
{
return null;
}
if (Cache_PREF_NOTICE_LANG_KGL == null)
{
Cache_PREF_NOTICE_LANG_KGL = Context.KGL.FindByKGLKEY(PREF_NOTICE_LANG);
}
return Cache_PREF_NOTICE_LANG_KGL;
}
}
/// <summary>
/// UM (Addresses) related entity by [DF.HOMEKEY]->[UM.UMKEY]
/// Home address ID
/// </summary>
public UM HOMEKEY_UM
{
get
{
if (HOMEKEY == null)
{
return null;
}
if (Cache_HOMEKEY_UM == null)
{
Cache_HOMEKEY_UM = Context.UM.FindByUMKEY(HOMEKEY.Value);
}
return Cache_HOMEKEY_UM;
}
}
/// <summary>
/// UM (Addresses) related entity by [DF.MAILKEY]->[UM.UMKEY]
/// Mail address ID
/// </summary>
public UM MAILKEY_UM
{
get
{
if (MAILKEY == null)
{
return null;
}
if (Cache_MAILKEY_UM == null)
{
Cache_MAILKEY_UM = Context.UM.FindByUMKEY(MAILKEY.Value);
}
return Cache_MAILKEY_UM;
}
}
/// <summary>
/// UM (Addresses) related entity by [DF.BILLINGKEY]->[UM.UMKEY]
/// Billing address ID
/// </summary>
public UM BILLINGKEY_UM
{
get
{
if (BILLINGKEY == null)
{
return null;
}
if (Cache_BILLINGKEY_UM == null)
{
Cache_BILLINGKEY_UM = Context.UM.FindByUMKEY(BILLINGKEY.Value);
}
return Cache_BILLINGKEY_UM;
}
}
/// <summary>
/// KCD (Doctors) related entity by [DF.DOCTOR]->[KCD.KCDKEY]
/// Reference to local doctor (default for each student)
/// </summary>
public KCD DOCTOR_KCD
{
get
{
if (DOCTOR == null)
{
return null;
}
if (Cache_DOCTOR_KCD == null)
{
Cache_DOCTOR_KCD = Context.KCD.FindByKCDKEY(DOCTOR);
}
return Cache_DOCTOR_KCD;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.EMERG_LANG01]->[KGL.KGLKEY]
/// Language spoken by person(s) to contact in an emergency
/// </summary>
public KGL EMERG_LANG01_KGL
{
get
{
if (EMERG_LANG01 == null)
{
return null;
}
if (Cache_EMERG_LANG01_KGL == null)
{
Cache_EMERG_LANG01_KGL = Context.KGL.FindByKGLKEY(EMERG_LANG01);
}
return Cache_EMERG_LANG01_KGL;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.EMERG_LANG02]->[KGL.KGLKEY]
/// Language spoken by person(s) to contact in an emergency
/// </summary>
public KGL EMERG_LANG02_KGL
{
get
{
if (EMERG_LANG02 == null)
{
return null;
}
if (Cache_EMERG_LANG02_KGL == null)
{
Cache_EMERG_LANG02_KGL = Context.KGL.FindByKGLKEY(EMERG_LANG02);
}
return Cache_EMERG_LANG02_KGL;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.EMERG_LANG03]->[KGL.KGLKEY]
/// Language spoken by person(s) to contact in an emergency
/// </summary>
public KGL EMERG_LANG03_KGL
{
get
{
if (EMERG_LANG03 == null)
{
return null;
}
if (Cache_EMERG_LANG03_KGL == null)
{
Cache_EMERG_LANG03_KGL = Context.KGL.FindByKGLKEY(EMERG_LANG03);
}
return Cache_EMERG_LANG03_KGL;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.EMERG_LANG04]->[KGL.KGLKEY]
/// Language spoken by person(s) to contact in an emergency
/// </summary>
public KGL EMERG_LANG04_KGL
{
get
{
if (EMERG_LANG04 == null)
{
return null;
}
if (Cache_EMERG_LANG04_KGL == null)
{
Cache_EMERG_LANG04_KGL = Context.KGL.FindByKGLKEY(EMERG_LANG04);
}
return Cache_EMERG_LANG04_KGL;
}
}
/// <summary>
/// KGL (Languages) related entity by [DF.HOME_LANG]->[KGL.KGLKEY]
/// The language spoken at home
/// </summary>
public KGL HOME_LANG_KGL
{
get
{
if (HOME_LANG == null)
{
return null;
}
if (Cache_HOME_LANG_KGL == null)
{
Cache_HOME_LANG_KGL = Context.KGL.FindByKGLKEY(HOME_LANG);
}
return Cache_HOME_LANG_KGL;
}
}
#endregion
#region Foreign Navigation Properties
/// <summary>
/// DFB (BPAY Receipts) related entities by [DF.DFKEY]->[DFB.FAM_CODE]
/// Family ID
/// </summary>
public IReadOnlyList<DFB> DFKEY_DFB_FAM_CODE
{
get
{
if (Cache_DFKEY_DFB_FAM_CODE == null &&
!Context.DFB.TryFindByFAM_CODE(DFKEY, out Cache_DFKEY_DFB_FAM_CODE))
{
Cache_DFKEY_DFB_FAM_CODE = new List<DFB>().AsReadOnly();
}
return Cache_DFKEY_DFB_FAM_CODE;
}
}
/// <summary>
/// DFF (Family Financial Transactions) related entities by [DF.DFKEY]->[DFF.CODE]
/// Family ID
/// </summary>
public IReadOnlyList<DFF> DFKEY_DFF_CODE
{
get
{
if (Cache_DFKEY_DFF_CODE == null &&
!Context.DFF.TryFindByCODE(DFKEY, out Cache_DFKEY_DFF_CODE))
{
Cache_DFKEY_DFF_CODE = new List<DFF>().AsReadOnly();
}
return Cache_DFKEY_DFF_CODE;
}
}
/// <summary>
/// DFHI (Family History) related entities by [DF.DFKEY]->[DFHI.FKEY]
/// Family ID
/// </summary>
public IReadOnlyList<DFHI> DFKEY_DFHI_FKEY
{
get
{
if (Cache_DFKEY_DFHI_FKEY == null &&
!Context.DFHI.TryFindByFKEY(DFKEY, out Cache_DFKEY_DFHI_FKEY))
{
Cache_DFKEY_DFHI_FKEY = new List<DFHI>().AsReadOnly();
}
return Cache_DFKEY_DFHI_FKEY;
}
}
/// <summary>
/// DFVT (Family Voluntary Transactions) related entities by [DF.DFKEY]->[DFVT.FAMILY]
/// Family ID
/// </summary>
public IReadOnlyList<DFVT> DFKEY_DFVT_FAMILY
{
get
{
if (Cache_DFKEY_DFVT_FAMILY == null &&
!Context.DFVT.TryFindByFAMILY(DFKEY, out Cache_DFKEY_DFVT_FAMILY))
{
Cache_DFKEY_DFVT_FAMILY = new List<DFVT>().AsReadOnly();
}
return Cache_DFKEY_DFVT_FAMILY;
}
}
/// <summary>
/// ST (Students) related entities by [DF.DFKEY]->[ST.FAMILY]
/// Family ID
/// </summary>
public IReadOnlyList<ST> DFKEY_ST_FAMILY
{
get
{
if (Cache_DFKEY_ST_FAMILY == null &&
!Context.ST.TryFindByFAMILY(DFKEY, out Cache_DFKEY_ST_FAMILY))
{
Cache_DFKEY_ST_FAMILY = new List<ST>().AsReadOnly();
}
return Cache_DFKEY_ST_FAMILY;
}
}
/// <summary>
/// ST (Students) related entities by [DF.DFKEY]->[ST.FAMB]
/// Family ID
/// </summary>
public IReadOnlyList<ST> DFKEY_ST_FAMB
{
get
{
if (Cache_DFKEY_ST_FAMB == null &&
!Context.ST.TryFindByFAMB(DFKEY, out Cache_DFKEY_ST_FAMB))
{
Cache_DFKEY_ST_FAMB = new List<ST>().AsReadOnly();
}
return Cache_DFKEY_ST_FAMB;
}
}
/// <summary>
/// ST (Students) related entities by [DF.DFKEY]->[ST.FAMC]
/// Family ID
/// </summary>
public IReadOnlyList<ST> DFKEY_ST_FAMC
{
get
{
if (Cache_DFKEY_ST_FAMC == null &&
!Context.ST.TryFindByFAMC(DFKEY, out Cache_DFKEY_ST_FAMC))
{
Cache_DFKEY_ST_FAMC = new List<ST>().AsReadOnly();
}
return Cache_DFKEY_ST_FAMC;
}
}
/// <summary>
/// STSB (Family Invoice Allocations) related entities by [DF.DFKEY]->[STSB.FAMILY]
/// Family ID
/// </summary>
public IReadOnlyList<STSB> DFKEY_STSB_FAMILY
{
get
{
if (Cache_DFKEY_STSB_FAMILY == null &&
!Context.STSB.TryFindByFAMILY(DFKEY, out Cache_DFKEY_STSB_FAMILY))
{
Cache_DFKEY_STSB_FAMILY = new List<STSB>().AsReadOnly();
}
return Cache_DFKEY_STSB_FAMILY;
}
}
#endregion
}
}
| |
//
// DiskUtils.cs
//
// Author:
// Alexander Matsibarov (macasun) <amatsibarov@gmail.com>
//
// Copyright (c) 2013 Alexander Matsibarov
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.IO;
using FileExplorerMobile.Core.Interfaces;
using FileExplorerMobile.Core.Data.Enums;
namespace FileExplorerMobile.Core.Managers
{
public class DiskUtils : BaseManager, IDiskUtils
{
#region Test data creation
#if DEBUG
/// <summary>
/// Creates the test data.
/// </summary>
public void CreateTestData()
{
Directory.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Personal), true);
CreateFileEntry(FileEntryTypes.Folder, false, "Root folder 1");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 1", "PDF file 1-1.pdf");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 1", "PDF file 1-2.pdf");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 1", "PDF file 1-3.pdf");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 1", "Doc file 1-1.doc");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 1", "Doc file 1-2.docx");
CreateFileEntry(FileEntryTypes.Folder, false, "Root folder 1", "Subfolder 1");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 1", "Subfolder 1", "Excel file 1-1-1.xls");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 1", "Subfolder 1", "PowerPoint file 1-1-1.ppt");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 1", "Subfolder 1", "PowerPoint file 1-1-2.pptx");
CreateFileEntry(FileEntryTypes.Folder, false, "Root folder 2");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 2", "PDF file 2-1.pdf");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 2", "PDF file 2-2.pdf");
CreateFileEntry(FileEntryTypes.Folder, false, "Root folder 3");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 3", "PDF file 3-1.pdf");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 3", "PowerPoint file 3-1.ppt");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 3", "PowerPoint file 3-2.pptx");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 3", "Doc file 1-1.doc");
CreateFileEntry(FileEntryTypes.Unknown, false, "Root folder 3", "Doc file 1-2.docx");
CreateFileEntry(FileEntryTypes.Unknown, false, "PDF file 1.pdf");
CreateFileEntry(FileEntryTypes.Unknown, false, "PDF file 2.pdf");
CreateFileEntry(FileEntryTypes.Unknown, false, "PDF file 3.pdf");
CreateFileEntry(FileEntryTypes.Unknown, false, "Doc file 1.doc");
CreateFileEntry(FileEntryTypes.Unknown, false, "Doc file 2.docx");
CreateFileEntry(FileEntryTypes.Unknown, false, "Excel file 1.xls");
CreateFileEntry(FileEntryTypes.Unknown, false, "PowerPoint file 1.ppt");
CreateFileEntry(FileEntryTypes.Unknown, false, "PowerPoint file 2.pptx");
}
#endif
#endregion
#region Logic
/// <summary>
/// Gets the file entries by the <see cref="path"/>.
/// </summary>
/// <param name='path'>The path.</param>
/// <returns>The file entries.</returns>
public string[] GetFileEntries(string path)
{
if (path == null) {
path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
}
return Directory.GetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
/// <summary>
/// Gets the value indicates, the FileSystemInfo is a directory.
/// </summary>
/// <param name='path'>The path.</param>
/// <returns><c>true</c>, if the FileSystemInfo is directory, <c>false</c> otherwise.</returns>
public bool FileSystemInfoIsIsDirectory(string path)
{
var fileAttrs = File.GetAttributes(path);
return (fileAttrs & FileAttributes.Directory) == FileAttributes.Directory;
}
/// <summary>
/// Gets the file name without extension.
/// </summary>
/// <param name='path'>The path.</param>
/// <returns>The file name without extension.</returns>
public string GetFileNameWithoutExtension(string path)
{
return Path.GetFileNameWithoutExtension(path);
}
/// <summary>
/// Gets the file extension.
/// </summary>
/// <param name='name'>The file name.</param>
/// <returns>The file extension.</returns>
public string GetFileExtension(string name)
{
return Path.GetExtension(name);
}
/// <summary>
/// Gets the size of the file.
/// </summary>
/// <param name='path'>The file path.</param>
/// <returns>The file size.</returns>
public long GetFileSize(string path)
{
var fileInfo = new FileInfo(path);
if ((fileInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory) {
return 0;
}
return fileInfo.Length;
}
/// <summary>
/// Creates the file entry.
/// </summary>
/// <param name="type">The FileEntry type.</param>
/// <param name="showAlertOnException">Indicates should be or not appears the alert window if an exception raise.</param>
/// <param name="pathes">The pathes.</param>
/// <returns><c>true</c>, if FileSystemInfo was created, <c>false</c> otherwise./returns>
public bool CreateFileEntry(FileEntryTypes type, bool showAlertOnException = true, params string[] pathes)
{
var root = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = Path.Combine(root, Path.Combine(pathes));
var success = false;
try {
if (type == FileEntryTypes.Folder) {
if (!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
} else {
if (!File.Exists(path)) {
File.WriteAllText(path, path);
}
}
success = true;
} catch (Exception) {
if (showAlertOnException) {
MgrAccessor.CommonUtils.ShowAlert("Warning", "The error occurs when created FileEntry", "Ok");
}
}
return success;
}
/// <summary>
/// Renames the FileSystemInfo.
/// </summary>
/// <param name='path'>The FileSystemInfo path.</param>
/// <param name='newName'>The new FileSystemInfo name.</param>
/// <param name='pathAfterRename'>The FileSystemInfo path after rename.</param>
/// <returns><c>true</c>, if FileSystemInfo was renamed, <c>false</c> otherwise./returns>
public bool RenameFileSystemInfo(string path, string newName, out string pathAfterRename, bool showAlertOnException = true)
{
var name = Path.GetFileNameWithoutExtension(path);
var ext = Path.GetExtension(path);
if (string.IsNullOrEmpty(newName) || newName == name || newName == name + ext) {
pathAfterRename = null;
return false;
}
var parentDirPath = Path.GetDirectoryName(path);
pathAfterRename = Path.Combine(parentDirPath, newName + ext);
var success = false;
try {
var fileInfo = new FileInfo(path);
if ((fileInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory) {
Directory.Move(path, pathAfterRename);
} else {
File.Move(path, pathAfterRename);
}
// TODO! Write to LogWriter
success = true;
} catch (Exception) {
if (showAlertOnException) {
MgrAccessor.CommonUtils.ShowAlert("Warning", "The error occurs when renamed FileEntry", "Ok");
}
}
return success;
}
/// <summary>
/// Deletes the FileSystemInfo.
/// </summary>
/// <param name='path'>The FileSystemInfo path.</param>
/// <returns><c>true</c>, if FileSystemInfo was deleted, <c>false</c> otherwise.</returns>
public bool DeleteFileSystemInfo(string path, bool showAlertOnException = true)
{
var success = false;
try {
var fileInfo = new FileInfo(path);
if ((fileInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory) {
if (Directory.Exists(path)) {
Directory.Delete(path, true);
}
} else {
if (File.Exists(path)) {
File.Delete(path);
}
}
// TODO! Write to LogWriter
success = true;
} catch (Exception) {
if (showAlertOnException) {
MgrAccessor.CommonUtils.ShowAlert("Warning", "The error occurs when deleted FileEntry", "Ok");
}
}
return success;
}
#endregion
}
}
| |
using System.Collections.Generic;
using System;
namespace UnuGames {
public class UIEventController
{
//
// Properties
//
public Dictionary<string, Delegate> Routers { get; set; }
public List<string> PermanentEvents { get; set; }
//
// Constructors
//
public UIEventController ()
{
Routers = new Dictionary<string, Delegate> ();
PermanentEvents = new List<string> ();
}
//
// Methods
//
public void AddEventListener<T> (string eventType, Action<T> handler)
{
OnListenerAdding (eventType, handler);
Routers [eventType] = Delegate.Combine (Routers [eventType], handler);
}
public void AddEventListener<T0, T1, T2, T3> (string eventType, Action<T0, T1, T2, T3> handler)
{
OnListenerAdding (eventType, handler);
Routers [eventType] = Delegate.Combine (Routers [eventType], handler);
}
public void AddEventListener<T0, T1, T2> (string eventType, Action<T0, T1, T2> handler)
{
OnListenerAdding (eventType, handler);
Routers [eventType] = Delegate.Combine (Routers [eventType], handler);
}
public void AddEventListener<T0, T1> (string eventType, Action<T0, T1> handler)
{
OnListenerAdding (eventType, handler);
Routers [eventType] = Delegate.Combine (Routers [eventType], handler);
}
public void AddEventListener (string eventType, Action handler)
{
OnListenerAdding (eventType, handler);
Routers [eventType] = Delegate.Combine (Routers [eventType], handler);
}
public void Cleanup ()
{
List<string> list = new List<string> ();
foreach (KeyValuePair<string, Delegate> current in Routers)
{
bool flag = false;
foreach (string current2 in PermanentEvents)
{
if (current.Key == current2)
{
flag = true;
break;
}
}
if (!flag)
{
list.Add (current.Key);
}
}
foreach (string current2 in list)
{
Routers.Remove (current2);
}
}
public bool ContainsEvent (string eventType)
{
return Routers.ContainsKey (eventType);
}
public void MarkAsPermanent (string eventType)
{
PermanentEvents.Add (eventType);
}
public void RemoveEventListener<T0, T1, T2, T3> (string eventType, Action<T0, T1, T2, T3> handler)
{
if (OnListenerRemoving (eventType, handler))
{
Routers [eventType] = Delegate.Remove (Routers [eventType], handler);
OnListenerRemoved (eventType);
}
}
public void RemoveEventListener (string eventType, Action handler)
{
if (OnListenerRemoving (eventType, handler))
{
Routers [eventType] = Delegate.Remove (Routers [eventType], handler);
OnListenerRemoved (eventType);
}
}
public void RemoveEventListener<T0, T1, T2> (string eventType, Action<T0, T1, T2> handler)
{
if (OnListenerRemoving (eventType, handler))
{
Routers [eventType] = Delegate.Remove (Routers [eventType] as Action<T0, T1, T2>, handler) as Action<T0, T1, T2>;
OnListenerRemoved (eventType);
}
}
public void RemoveEventListener<T> (string eventType, Action<T> handler)
{
if (OnListenerRemoving (eventType, handler))
{
Routers [eventType] = Delegate.Remove (Routers [eventType] as Action<T>, handler) as Action<T>;
OnListenerRemoved (eventType);
}
}
public void RemoveEventListener<T0, T1> (string eventType, Action<T0, T1> handler)
{
if (OnListenerRemoving (eventType, handler))
{
Routers [eventType] = Delegate.Remove (Routers [eventType] as Action<T0, T1>, handler) as Action<T0, T1>;
OnListenerRemoved (eventType);
}
}
public void TriggerEvent<T0, T1, T2, T3> (string eventType, T0 arg1, T1 arg2, T2 arg3, T3 arg4)
{
Delegate @delegate;
if (Routers.TryGetValue (eventType, out @delegate))
{
Delegate[] invocationList = @delegate.GetInvocationList ();
for (int i = 0; i < invocationList.Length; i++)
{
Action<T0, T1, T2, T3> action = invocationList [i] as Action<T0, T1, T2, T3>;
if (action == null)
{
throw new EventException (string.Format ("TriggerEvent {0} error: types of parameters are not match.", eventType));
}
try
{
action (arg1, arg2, arg3, arg4);
}
catch (Exception ex)
{
UnuLogger.LogError(ex.StackTrace);
}
}
}
}
public void TriggerEvent<T0, T1> (string eventType, T0 arg1, T1 arg2)
{
Delegate @delegate;
if (Routers.TryGetValue (eventType, out @delegate))
{
Delegate[] invocationList = @delegate.GetInvocationList ();
for (int i = 0; i < invocationList.Length; i++)
{
Action<T0, T1> action = invocationList [i] as Action<T0, T1>;
if (action == null)
{
throw new EventException (string.Format ("TriggerEvent {0} error: types of parameters are not match.", eventType));
}
try
{
action (arg1, arg2);
}
catch (Exception ex)
{
UnuLogger.LogError(ex.StackTrace);
}
}
}
}
public void TriggerEvent<T0, T1, T2> (string eventType, T0 arg1, T1 arg2, T2 arg3)
{
Delegate @delegate;
if (Routers.TryGetValue (eventType, out @delegate))
{
Delegate[] invocationList = @delegate.GetInvocationList ();
for (int i = 0; i < invocationList.Length; i++)
{
Action<T0, T1, T2> action = invocationList [i] as Action<T0, T1, T2>;
if (action == null)
{
throw new EventException (string.Format ("TriggerEvent {0} error: types of parameters are not match.", eventType));
}
try
{
action (arg1, arg2, arg3);
}
catch (Exception ex)
{
UnuLogger.LogError(ex.StackTrace);
}
}
}
}
public void TriggerEvent<T> (string eventType, T arg1)
{
Delegate @delegate;
if (Routers.TryGetValue (eventType, out @delegate))
{
Delegate[] invocationList = @delegate.GetInvocationList ();
for (int i = 0; i < invocationList.Length; i++)
{
Action<T> action = invocationList [i] as Action<T>;
if (action == null)
{
throw new EventException (string.Format ("TriggerEvent {0} error: types of parameters are not match.", eventType));
}
try
{
action (arg1);
}
catch (Exception ex)
{
UnuLogger.LogError(ex.StackTrace);
}
}
}
}
public void TriggerEvent (string eventType)
{
Delegate @delegate;
if (Routers.TryGetValue (eventType, out @delegate))
{
Delegate[] invocationList = @delegate.GetInvocationList ();
for (int i = 0; i < invocationList.Length; i++)
{
Action action = invocationList [i] as Action;
if (action == null)
{
throw new EventException (string.Format ("TriggerEvent {0} error: types of parameters are not match.", eventType));
}
try
{
action ();
}
catch (Exception ex)
{
UnuLogger.LogError(ex.StackTrace);
}
}
}
}
public void OnListenerAdding(string eventType, Delegate listenerBeingAdded) {
#if LOG_ALL_MESSAGES || LOG_ADD_LISTENER
Debug.Log("MESSENGER OnListenerAdding \t\"" + eventType + "\"\t{" + listenerBeingAdded.Target + " -> " + listenerBeingAdded.Method + "}");
#endif
if (!Routers.ContainsKey(eventType)) {
Routers.Add(eventType, null );
}
Delegate d = Routers[eventType];
if (d != null && d.GetType() != listenerBeingAdded.GetType()) {
throw new ListenerException(string.Format("Attempting to add listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being added has type {2}", eventType, d.GetType().Name, listenerBeingAdded.GetType().Name));
}
}
public bool OnListenerRemoving(string eventType, Delegate listenerBeingRemoved) {
#if LOG_ALL_MESSAGES
Debug.Log("MESSENGER OnListenerRemoving \t\"" + eventType + "\"\t{" + listenerBeingRemoved.Target + " -> " + listenerBeingRemoved.Method + "}");
#endif
bool success = true;
if (Routers.ContainsKey(eventType)) {
Delegate d = Routers[eventType];
if (d == null) {
success = false;
throw new ListenerException(string.Format("Attempting to remove listener with for event type \"{0}\" but current listener is null.", eventType));
} else if (d.GetType() != listenerBeingRemoved.GetType()) {
success = false;
throw new ListenerException(string.Format("Attempting to remove listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being removed has type {2}", eventType, d.GetType().Name, listenerBeingRemoved.GetType().Name));
}
} else {
success = false;
throw new ListenerException(string.Format("Attempting to remove listener for type \"{0}\" but Messenger doesn't know about this event type.", eventType));
}
return success;
}
public void OnListenerRemoved(string eventType) {
if (Routers[eventType] == null) {
Routers.Remove(eventType);
}
}
}
public class ListenerException: Exception
{
public ListenerException () {
}
public ListenerException (string exception) {
}
}
public class EventException: Exception
{
public EventException () {
}
public EventException (string exception) {
}
}
}
| |
// 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 gcssv = Google.Cloud.SecurityCenter.Settings.V1Beta1;
using sys = System;
namespace Google.Cloud.SecurityCenter.Settings.V1Beta1
{
/// <summary>Resource name for the <c>ComponentSettings</c> resource.</summary>
public sealed partial class ComponentSettingsName : gax::IResourceName, sys::IEquatable<ComponentSettingsName>
{
/// <summary>The possible contents of <see cref="ComponentSettingsName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>organizations/{organization}/components/{component}/settings</c>.
/// </summary>
OrganizationComponent = 1,
/// <summary>A resource name with pattern <c>folders/{folder}/components/{component}/settings</c>.</summary>
FolderComponent = 2,
/// <summary>
/// A resource name with pattern <c>projects/{project}/components/{component}/settings</c>.
/// </summary>
ProjectComponent = 3,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings</c>.
/// </summary>
ProjectLocationClusterComponent = 4,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings</c>.
/// </summary>
ProjectRegionClusterComponent = 5,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings</c>.
/// </summary>
ProjectZoneClusterComponent = 6,
}
private static gax::PathTemplate s_organizationComponent = new gax::PathTemplate("organizations/{organization}/components/{component}/settings");
private static gax::PathTemplate s_folderComponent = new gax::PathTemplate("folders/{folder}/components/{component}/settings");
private static gax::PathTemplate s_projectComponent = new gax::PathTemplate("projects/{project}/components/{component}/settings");
private static gax::PathTemplate s_projectLocationClusterComponent = new gax::PathTemplate("projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings");
private static gax::PathTemplate s_projectRegionClusterComponent = new gax::PathTemplate("projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings");
private static gax::PathTemplate s_projectZoneClusterComponent = new gax::PathTemplate("projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings");
/// <summary>Creates a <see cref="ComponentSettingsName"/> 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="ComponentSettingsName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ComponentSettingsName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ComponentSettingsName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ComponentSettingsName"/> with the pattern
/// <c>organizations/{organization}/components/{component}/settings</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ComponentSettingsName"/> constructed from the provided ids.</returns>
public static ComponentSettingsName FromOrganizationComponent(string organizationId, string componentId) =>
new ComponentSettingsName(ResourceNameType.OrganizationComponent, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), componentId: gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Creates a <see cref="ComponentSettingsName"/> with the pattern
/// <c>folders/{folder}/components/{component}/settings</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ComponentSettingsName"/> constructed from the provided ids.</returns>
public static ComponentSettingsName FromFolderComponent(string folderId, string componentId) =>
new ComponentSettingsName(ResourceNameType.FolderComponent, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), componentId: gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Creates a <see cref="ComponentSettingsName"/> with the pattern
/// <c>projects/{project}/components/{component}/settings</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ComponentSettingsName"/> constructed from the provided ids.</returns>
public static ComponentSettingsName FromProjectComponent(string projectId, string componentId) =>
new ComponentSettingsName(ResourceNameType.ProjectComponent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), componentId: gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Creates a <see cref="ComponentSettingsName"/> with the pattern
/// <c>projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ComponentSettingsName"/> constructed from the provided ids.</returns>
public static ComponentSettingsName FromProjectLocationClusterComponent(string projectId, string locationId, string clusterId, string componentId) =>
new ComponentSettingsName(ResourceNameType.ProjectLocationClusterComponent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), clusterId: gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), componentId: gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Creates a <see cref="ComponentSettingsName"/> with the pattern
/// <c>projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ComponentSettingsName"/> constructed from the provided ids.</returns>
public static ComponentSettingsName FromProjectRegionClusterComponent(string projectId, string regionId, string clusterId, string componentId) =>
new ComponentSettingsName(ResourceNameType.ProjectRegionClusterComponent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), regionId: gax::GaxPreconditions.CheckNotNullOrEmpty(regionId, nameof(regionId)), clusterId: gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), componentId: gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Creates a <see cref="ComponentSettingsName"/> with the pattern
/// <c>projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ComponentSettingsName"/> constructed from the provided ids.</returns>
public static ComponentSettingsName FromProjectZoneClusterComponent(string projectId, string zoneId, string clusterId, string componentId) =>
new ComponentSettingsName(ResourceNameType.ProjectZoneClusterComponent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), zoneId: gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), clusterId: gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), componentId: gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>organizations/{organization}/components/{component}/settings</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>organizations/{organization}/components/{component}/settings</c>.
/// </returns>
public static string Format(string organizationId, string componentId) =>
FormatOrganizationComponent(organizationId, componentId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>organizations/{organization}/components/{component}/settings</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>organizations/{organization}/components/{component}/settings</c>.
/// </returns>
public static string FormatOrganizationComponent(string organizationId, string componentId) =>
s_organizationComponent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>folders/{folder}/components/{component}/settings</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>folders/{folder}/components/{component}/settings</c>.
/// </returns>
public static string FormatFolderComponent(string folderId, string componentId) =>
s_folderComponent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>projects/{project}/components/{component}/settings</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>projects/{project}/components/{component}/settings</c>.
/// </returns>
public static string FormatProjectComponent(string projectId, string componentId) =>
s_projectComponent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings</c>.
/// </returns>
public static string FormatProjectLocationClusterComponent(string projectId, string locationId, string clusterId, string componentId) =>
s_projectLocationClusterComponent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="regionId">The <c>Region</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings</c>.
/// </returns>
public static string FormatProjectRegionClusterComponent(string projectId, string regionId, string clusterId, string componentId) =>
s_projectRegionClusterComponent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(regionId, nameof(regionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ComponentSettingsName"/> with pattern
/// <c>projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings</c>.
/// </returns>
public static string FormatProjectZoneClusterComponent(string projectId, string zoneId, string clusterId, string componentId) =>
s_projectZoneClusterComponent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ComponentSettingsName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/components/{component}/settings</c></description></item>
/// <item><description><c>folders/{folder}/components/{component}/settings</c></description></item>
/// <item><description><c>projects/{project}/components/{component}/settings</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="componentSettingsName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ComponentSettingsName"/> if successful.</returns>
public static ComponentSettingsName Parse(string componentSettingsName) => Parse(componentSettingsName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ComponentSettingsName"/> 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>organizations/{organization}/components/{component}/settings</c></description></item>
/// <item><description><c>folders/{folder}/components/{component}/settings</c></description></item>
/// <item><description><c>projects/{project}/components/{component}/settings</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="componentSettingsName">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="ComponentSettingsName"/> if successful.</returns>
public static ComponentSettingsName Parse(string componentSettingsName, bool allowUnparsed) =>
TryParse(componentSettingsName, allowUnparsed, out ComponentSettingsName 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="ComponentSettingsName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/components/{component}/settings</c></description></item>
/// <item><description><c>folders/{folder}/components/{component}/settings</c></description></item>
/// <item><description><c>projects/{project}/components/{component}/settings</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="componentSettingsName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ComponentSettingsName"/>, 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 componentSettingsName, out ComponentSettingsName result) =>
TryParse(componentSettingsName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ComponentSettingsName"/> 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>organizations/{organization}/components/{component}/settings</c></description></item>
/// <item><description><c>folders/{folder}/components/{component}/settings</c></description></item>
/// <item><description><c>projects/{project}/components/{component}/settings</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="componentSettingsName">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="ComponentSettingsName"/>, 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 componentSettingsName, bool allowUnparsed, out ComponentSettingsName result)
{
gax::GaxPreconditions.CheckNotNull(componentSettingsName, nameof(componentSettingsName));
gax::TemplatedResourceName resourceName;
if (s_organizationComponent.TryParseName(componentSettingsName, out resourceName))
{
result = FromOrganizationComponent(resourceName[0], resourceName[1]);
return true;
}
if (s_folderComponent.TryParseName(componentSettingsName, out resourceName))
{
result = FromFolderComponent(resourceName[0], resourceName[1]);
return true;
}
if (s_projectComponent.TryParseName(componentSettingsName, out resourceName))
{
result = FromProjectComponent(resourceName[0], resourceName[1]);
return true;
}
if (s_projectLocationClusterComponent.TryParseName(componentSettingsName, out resourceName))
{
result = FromProjectLocationClusterComponent(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (s_projectRegionClusterComponent.TryParseName(componentSettingsName, out resourceName))
{
result = FromProjectRegionClusterComponent(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (s_projectZoneClusterComponent.TryParseName(componentSettingsName, out resourceName))
{
result = FromProjectZoneClusterComponent(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(componentSettingsName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ComponentSettingsName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string clusterId = null, string componentId = null, string folderId = null, string locationId = null, string organizationId = null, string projectId = null, string regionId = null, string zoneId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ClusterId = clusterId;
ComponentId = componentId;
FolderId = folderId;
LocationId = locationId;
OrganizationId = organizationId;
ProjectId = projectId;
RegionId = regionId;
ZoneId = zoneId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ComponentSettingsName"/> class from the component parts of pattern
/// <c>organizations/{organization}/components/{component}/settings</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="componentId">The <c>Component</c> ID. Must not be <c>null</c> or empty.</param>
public ComponentSettingsName(string organizationId, string componentId) : this(ResourceNameType.OrganizationComponent, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), componentId: gax::GaxPreconditions.CheckNotNullOrEmpty(componentId, nameof(componentId)))
{
}
/// <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>Cluster</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ClusterId { get; }
/// <summary>
/// The <c>Component</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ComponentId { 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>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { 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>
/// The <c>Region</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string RegionId { get; }
/// <summary>
/// The <c>Zone</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ZoneId { 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.OrganizationComponent: return s_organizationComponent.Expand(OrganizationId, ComponentId);
case ResourceNameType.FolderComponent: return s_folderComponent.Expand(FolderId, ComponentId);
case ResourceNameType.ProjectComponent: return s_projectComponent.Expand(ProjectId, ComponentId);
case ResourceNameType.ProjectLocationClusterComponent: return s_projectLocationClusterComponent.Expand(ProjectId, LocationId, ClusterId, ComponentId);
case ResourceNameType.ProjectRegionClusterComponent: return s_projectRegionClusterComponent.Expand(ProjectId, RegionId, ClusterId, ComponentId);
case ResourceNameType.ProjectZoneClusterComponent: return s_projectZoneClusterComponent.Expand(ProjectId, ZoneId, ClusterId, ComponentId);
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 ComponentSettingsName);
/// <inheritdoc/>
public bool Equals(ComponentSettingsName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ComponentSettingsName a, ComponentSettingsName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ComponentSettingsName a, ComponentSettingsName b) => !(a == b);
}
public partial class ComponentSettings
{
/// <summary>
/// <see cref="gcssv::ComponentSettingsName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcssv::ComponentSettingsName ComponentSettingsName
{
get => string.IsNullOrEmpty(Name) ? null : gcssv::ComponentSettingsName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software; you can redistribute it and/or modify
* it under the terms of The MIT License (MIT).
*
* You should have received a copy of the MIT License
* along with SharpNEAT; if not, see https://opensource.org/licenses/MIT.
*/
using System.Diagnostics;
using SharpNeat.Core;
using SharpNeat.Phenomes;
namespace SharpNeat.Domains
{
/// <summary>
/// A black box evaluator for the XOR logic gate problem domain.
///
/// XOR (also known as Exclusive OR) is a type of logical disjunction on two operands that results in
/// a value of true if and only if exactly one of the operands has a value of 'true'. A simple way
/// to state this is 'one or the other but not both.'.
///
/// This evaluator therefore requires that the black box to be evaluated has two inputs and one
/// output all using the range 0..1
///
/// In turn each of the four possible test cases are applied to the two inputs, the network is activated
/// and the output is evaluated. If a 'false' response is required we expect an output of zero, for true
/// we expect a 1.0. Fitness for each test case is the difference between the output and the wrong output,
/// thus a maximum of 1 can be scored on each test case giving a maximum of 4. In addition each outputs is
/// compared against a threshold of 0.5, if all four outputs are on the correct side of the threshold then
/// 10.0 is added to the total fitness. Therefore a black box that answers correctly but very close to the
/// threshold will score just above 10, and a black box that answers correctly with perfect 0.0 and 1.0
/// answers will score a maximum of 14.0.
///
/// The first type of evaluation punishes for difference from the required outputs and therefore represents
/// a smooth fitness space (we can evolve gradually towards better scores). The +10 score for 4 correct
/// responses is 'all or nothing', in other words it is a fitness space with a large step and no indication
/// of where the step is, which on it's own would be a poor fitness space as it required evolution to stumble
/// on the correct network by random rather than ascending a gradient in the fitness space. If however we do
/// stumble on a black box that answers correctly but close to the threshold, then we would like that box to
/// obtain a higher score than a network with, say, 3 strong correct responses and but wrong overall. We can
/// improve the correct box's output difference from threshold value gradually, while the box with 3 correct
/// responses may actually be in the wrong area of the fitness space altogether - in the wrong 'ballpark'.
/// </summary>
public class XorBlackBoxEvaluator : IPhenomeEvaluator<IBlackBox>
{
const double StopFitness = 10.0;
ulong _evalCount;
bool _stopConditionSatisfied;
#region IPhenomeEvaluator<IBlackBox> Members
/// <summary>
/// Gets the total number of evaluations that have been performed.
/// </summary>
public ulong EvaluationCount
{
get { return _evalCount; }
}
/// <summary>
/// Gets a value indicating whether some goal fitness has been achieved and that
/// the evolutionary algorithm/search should stop. This property's value can remain false
/// to allow the algorithm to run indefinitely.
/// </summary>
public bool StopConditionSatisfied
{
get { return _stopConditionSatisfied; }
}
/// <summary>
/// Evaluate the provided IBlackBox against the XOR problem domain and return its fitness score.
/// </summary>
public FitnessInfo Evaluate(IBlackBox box)
{
double fitness = 0;
double output;
double pass = 1.0;
ISignalArray inputArr = box.InputSignalArray;
ISignalArray outputArr = box.OutputSignalArray;
_evalCount++;
//----- Test 0,0
box.ResetState();
// Set the input values
inputArr[0] = 0.0;
inputArr[1] = 0.0;
// Activate the black box.
box.Activate();
if(!box.IsStateValid)
{ // Any black box that gets itself into an invalid state is unlikely to be
// any good, so lets just bail out here.
return FitnessInfo.Zero;
}
// Read output signal.
output = outputArr[0];
Debug.Assert(output >= 0.0, "Unexpected negative output.");
// Calculate this test case's contribution to the overall fitness score.
//fitness += 1.0 - output; // Use this line to punish absolute error instead of squared error.
fitness += 1.0-(output*output);
if(output > 0.5) {
pass = 0.0;
}
//----- Test 1,1
// Reset any black box state from the previous test case.
box.ResetState();
// Set the input values
inputArr[0] = 1.0;
inputArr[1] = 1.0;
// Activate the black box.
box.Activate();
if(!box.IsStateValid)
{ // Any black box that gets itself into an invalid state is unlikely to be
// any good, so lets just bail out here.
return FitnessInfo.Zero;
}
// Read output signal.
output = outputArr[0];
Debug.Assert(output >= 0.0, "Unexpected negative output.");
// Calculate this test case's contribution to the overall fitness score.
//fitness += 1.0 - output; // Use this line to punish absolute error instead of squared error.
fitness += 1.0-(output*output);
if(output > 0.5) {
pass = 0.0;
}
//----- Test 0,1
// Reset any black box state from the previous test case.
box.ResetState();
// Set the input values
inputArr[0] = 0.0;
inputArr[1] = 1.0;
// Activate the black box.
box.Activate();
if(!box.IsStateValid)
{ // Any black box that gets itself into an invalid state is unlikely to be
// any good, so lets just bail out here.
return FitnessInfo.Zero;
}
// Read output signal.
output = outputArr[0];
Debug.Assert(output >= 0.0, "Unexpected negative output.");
// Calculate this test case's contribution to the overall fitness score.
// fitness += output; // Use this line to punish absolute error instead of squared error.
fitness += 1.0-((1.0-output)*(1.0-output));
if(output <= 0.5) {
pass = 0.0;
}
//----- Test 1,0
// Reset any black box state from the previous test case.
box.ResetState();
// Set the input values
inputArr[0] = 1.0;
inputArr[1] = 0.0;
// Activate the black box.
box.Activate();
if(!box.IsStateValid)
{ // Any black box that gets itself into an invalid state is unlikely to be
// any good, so lets just bail out here.
return FitnessInfo.Zero;
}
// Read output signal.
output = outputArr[0];
Debug.Assert(output >= 0.0, "Unexpected negative output.");
// Calculate this test case's contribution to the overall fitness score.
// fitness += output; // Use this line to punish absolute error instead of squared error.
fitness += 1.0-((1.0-output)*(1.0-output));
if(output <= 0.5) {
pass = 0.0;
}
// If all four outputs were correct, that is, all four were on the correct side of the
// threshold level - then we add 10 to the fitness.
fitness += pass * 10.0;
if(fitness >= StopFitness) {
_stopConditionSatisfied = true;
}
return new FitnessInfo(fitness, fitness);
}
/// <summary>
/// Reset the internal state of the evaluation scheme if any exists.
/// Note. The XOR problem domain has no internal state. This method does nothing.
/// </summary>
public void Reset()
{
}
#endregion
}
}
| |
// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using Lucene.Net.Diagnostics;
using Lucene.Net.Util;
using Lucene.Net.Util.Fst;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Lucene.Net.Analysis.CharFilters
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Simplistic <see cref="CharFilter"/> that applies the mappings
/// contained in a <see cref="NormalizeCharMap"/> to the character
/// stream, and correcting the resulting changes to the
/// offsets. Matching is greedy (longest pattern matching at
/// a given point wins). Replacement is allowed to be the
/// empty string.
/// </summary>
public class MappingCharFilter : BaseCharFilter
{
private readonly Outputs<CharsRef> outputs = CharSequenceOutputs.Singleton;
private readonly FST<CharsRef> map;
private readonly FST.BytesReader fstReader;
private readonly RollingCharBuffer buffer = new RollingCharBuffer();
private readonly FST.Arc<CharsRef> scratchArc = new FST.Arc<CharsRef>();
private readonly IDictionary<char?, FST.Arc<CharsRef>> cachedRootArcs;
private CharsRef replacement;
private int replacementPointer;
private int inputOff;
/// <summary>
/// LUCENENET specific support to buffer the reader.
/// </summary>
private readonly BufferedCharFilter _input;
/// <summary>
/// Default constructor that takes a <see cref="TextReader"/>. </summary>
public MappingCharFilter(NormalizeCharMap normMap, TextReader @in)
: base(@in)
{
//LUCENENET support to reset the reader.
_input = GetBufferedReader(@in);
_input.Mark(BufferedCharFilter.DEFAULT_CHAR_BUFFER_SIZE);
buffer.Reset(_input);
//buffer.Reset(@in);
map = normMap.map;
cachedRootArcs = normMap.cachedRootArcs;
if (map != null)
{
fstReader = map.GetBytesReader();
}
else
{
fstReader = null;
}
}
/// <summary>
/// LUCENENET: Copied this method from the <see cref="WordlistLoader"/> class - this class requires readers
/// with a Reset() method (which .NET readers don't support). So, we use the <see cref="BufferedCharFilter"/>
/// (which is similar to Java BufferedReader) as a wrapper for whatever reader the user passes
/// (unless it is already a <see cref="BufferedCharFilter"/>).
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static BufferedCharFilter GetBufferedReader(TextReader reader)
{
return (reader is BufferedCharFilter) ? (BufferedCharFilter)reader : new BufferedCharFilter(reader);
}
public override void Reset()
{
// LUCENENET: reset the BufferedCharFilter.
_input.Reset();
buffer.Reset(_input);
replacement = null;
inputOff = 0;
}
public override int Read()
{
//System.out.println("\nread");
while (true)
{
if (replacement != null && replacementPointer < replacement.Length)
{
//System.out.println(" return repl[" + replacementPointer + "]=" + replacement.chars[replacement.offset + replacementPointer]);
return replacement.Chars[replacement.Offset + replacementPointer++];
}
// TODO: a more efficient approach would be Aho/Corasick's
// algorithm
// (http://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm)
// or this generalizatio: www.cis.uni-muenchen.de/people/Schulz/Pub/dictle5.ps
//
// I think this would be (almost?) equivalent to 1) adding
// epsilon arcs from all final nodes back to the init
// node in the FST, 2) adding a .* (skip any char)
// loop on the initial node, and 3) determinizing
// that. Then we would not have to Restart matching
// at each position.
int lastMatchLen = -1;
CharsRef lastMatch = null;
int firstCH = buffer.Get(inputOff);
if (firstCH != -1)
{
// LUCENENET fix: Check the dictionary to ensure it contains a key before reading it.
char key = Convert.ToChar((char)firstCH);
if (cachedRootArcs.TryGetValue(key, out FST.Arc<CharsRef> arc) && arc != null)
{
if (!FST.TargetHasArcs(arc))
{
// Fast pass for single character match:
if (Debugging.AssertsEnabled) Debugging.Assert(arc.IsFinal);
lastMatchLen = 1;
lastMatch = arc.Output;
}
else
{
int lookahead = 0;
CharsRef output = arc.Output;
while (true)
{
lookahead++;
if (arc.IsFinal)
{
// Match! (to node is final)
lastMatchLen = lookahead;
lastMatch = outputs.Add(output, arc.NextFinalOutput);
// Greedy: keep searching to see if there's a
// longer match...
}
if (!FST.TargetHasArcs(arc))
{
break;
}
int ch = buffer.Get(inputOff + lookahead);
if (ch == -1)
{
break;
}
if ((arc = map.FindTargetArc(ch, arc, scratchArc, fstReader)) is null)
{
// Dead end
break;
}
output = outputs.Add(output, arc.Output);
}
}
}
}
if (lastMatch != null)
{
inputOff += lastMatchLen;
//System.out.println(" match! len=" + lastMatchLen + " repl=" + lastMatch);
int diff = lastMatchLen - lastMatch.Length;
if (diff != 0)
{
int prevCumulativeDiff = LastCumulativeDiff;
if (diff > 0)
{
// Replacement is shorter than matched input:
AddOffCorrectMap(inputOff - diff - prevCumulativeDiff, prevCumulativeDiff + diff);
}
else
{
// Replacement is longer than matched input: remap
// the "extra" chars all back to the same input
// offset:
int outputStart = inputOff - prevCumulativeDiff;
for (int extraIDX = 0; extraIDX < -diff; extraIDX++)
{
AddOffCorrectMap(outputStart + extraIDX, prevCumulativeDiff - extraIDX - 1);
}
}
}
replacement = lastMatch;
replacementPointer = 0;
}
else
{
int ret = buffer.Get(inputOff);
if (ret != -1)
{
inputOff++;
buffer.FreeBefore(inputOff);
}
return ret;
}
}
}
public override int Read(char[] cbuf, int off, int len)
{
int numRead = 0;
for (int i = off; i < off + len; i++)
{
int c = Read();
if (c == -1)
{
break;
}
cbuf[i] = (char)c;
numRead++;
}
return numRead == 0 ? -1 : numRead;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Commons.Music.Midi
{
public enum PlayerState
{
Stopped,
Playing,
Paused,
}
// Event loop implementation.
class MidiEventLooper : IDisposable
{
public MidiEventLooper (IList<MidiMessage> messages, IMidiPlayerTimeManager timeManager, int deltaTimeSpec)
{
if (messages == null)
throw new ArgumentNullException ("messages");
if (deltaTimeSpec < 0)
throw new NotSupportedException ("SMPTe-based delta time is not implemented in this player.");
delta_time_spec = deltaTimeSpec;
time_manager = timeManager;
this.messages = messages;
state = PlayerState.Stopped;
}
public MidiEventAction EventReceived;
public event Action Starting;
public event Action Finished;
public event Action PlaybackCompletedToEnd;
readonly IMidiPlayerTimeManager time_manager;
readonly IList<MidiMessage> messages;
readonly int delta_time_spec;
// FIXME: I prefer ManualResetEventSlim (but it causes some regressions)
readonly ManualResetEvent pause_handle = new ManualResetEvent (false);
bool do_pause, do_stop;
internal double tempo_ratio = 1.0;
internal PlayerState state;
int event_idx = 0;
internal int current_tempo = MidiMetaType.DefaultTempo;
internal byte [] current_time_signature = new byte [4];
internal int play_delta_time;
public virtual void Dispose ()
{
if (state != PlayerState.Stopped)
Stop ();
Mute ();
}
public void Play ()
{
pause_handle.Set ();
state = PlayerState.Playing;
}
void Mute ()
{
for (int i = 0; i < 16; i++)
OnEvent (new MidiEvent ((byte) (i + 0xB0), 0x78, 0, null, 0, 0));
}
public void Pause ()
{
do_pause = true;
Mute ();
}
public void PlayerLoop ()
{
Starting?.Invoke ();
event_idx = 0;
play_delta_time = 0;
while (true) {
pause_handle.WaitOne ();
if (do_stop)
break;
if (do_pause) {
pause_handle.Reset ();
do_pause = false;
state = PlayerState.Paused;
continue;
}
if (event_idx == messages.Count)
break;
ProcessMessage (messages [event_idx++]);
}
do_stop = false;
Mute ();
state = PlayerState.Stopped;
if (event_idx == messages.Count)
PlaybackCompletedToEnd?.Invoke ();
Finished?.Invoke ();
}
int GetContextDeltaTimeInMilliseconds (int deltaTime) => (int) (current_tempo / 1000 * deltaTime / delta_time_spec / tempo_ratio);
void ProcessMessage (MidiMessage m)
{
if (seek_processor != null) {
var result = seek_processor.FilterMessage (m);
switch (result) {
case SeekFilterResult.PassAndTerminate:
case SeekFilterResult.BlockAndTerminate:
seek_processor = null;
break;
}
switch (result) {
case SeekFilterResult.Block:
case SeekFilterResult.BlockAndTerminate:
return; // ignore this event
}
}
else if (m.DeltaTime != 0) {
var ms = GetContextDeltaTimeInMilliseconds (m.DeltaTime);
time_manager.WaitBy (ms);
play_delta_time += m.DeltaTime;
}
if (m.Event.StatusByte == 0xFF) {
if (m.Event.Msb == MidiMetaType.Tempo)
current_tempo = MidiMetaType.GetTempo (m.Event.ExtraData, m.Event.ExtraDataOffset);
else if (m.Event.Msb == MidiMetaType.TimeSignature && m.Event.ExtraDataLength == 4)
Array.Copy (m.Event.ExtraData, current_time_signature, 4);
}
OnEvent (m.Event);
}
void OnEvent (MidiEvent m)
{
if (EventReceived != null)
EventReceived (m);
}
public void Stop ()
{
if (state != PlayerState.Stopped) {
do_stop = true;
if (pause_handle != null)
pause_handle.Set ();
if (Finished != null)
Finished ();
}
}
private ISeekProcessor seek_processor;
// not sure about the interface, so make it non-public yet.
internal void Seek (ISeekProcessor seekProcessor, int ticks)
{
seek_processor = seekProcessor ?? new SimpleSeekProcessor (ticks);
event_idx = 0;
play_delta_time = ticks;
Mute ();
}
}
// Provides asynchronous player control.
public class MidiPlayer : IDisposable
{
public MidiPlayer (MidiMusic music)
: this (music, MidiAccessManager.Empty)
{
}
public MidiPlayer (MidiMusic music, IMidiAccess access)
: this (music, access, new SimpleAdjustingMidiPlayerTimeManager ())
{
}
public MidiPlayer (MidiMusic music, IMidiOutput output)
: this (music, output, new SimpleAdjustingMidiPlayerTimeManager ())
{
}
public MidiPlayer (MidiMusic music, IMidiPlayerTimeManager timeManager)
: this (music, MidiAccessManager.Empty, timeManager)
{
}
public MidiPlayer (MidiMusic music, IMidiAccess access, IMidiPlayerTimeManager timeManager)
: this (music, access.OpenOutputAsync (access.Outputs.First ().Id).Result, timeManager)
{
should_dispose_output = true;
}
public MidiPlayer (MidiMusic music, IMidiOutput output, IMidiPlayerTimeManager timeManager)
{
if (music == null)
throw new ArgumentNullException ("music");
if (output == null)
throw new ArgumentNullException ("output");
if (timeManager == null)
throw new ArgumentNullException ("timeManager");
this.music = music;
this.output = output;
messages = SmfTrackMerger.Merge (music).Tracks [0].Messages;
player = new MidiEventLooper (messages, timeManager, music.DeltaTimeSpec);
player.Starting += () => {
// all control reset on all channels.
for (int i = 0; i < 16; i++) {
buffer [0] = (byte) (i + 0xB0);
buffer [1] = 0x79;
buffer [2] = 0;
output.Send (buffer, 0, 3, 0);
}
};
EventReceived += (m) => {
switch (m.EventType) {
case MidiEvent.NoteOn:
case MidiEvent.NoteOff:
if (channel_mask != null && channel_mask [m.Channel])
return; // ignore messages for the masked channel.
goto default;
case MidiEvent.SysEx1:
case MidiEvent.SysEx2:
if (buffer.Length <= m.ExtraDataLength)
buffer = new byte [buffer.Length * 2];
buffer [0] = m.StatusByte;
Array.Copy (m.ExtraData, m.ExtraDataOffset, buffer, 1, m.ExtraDataLength);
output.Send (buffer, 0, m.ExtraDataLength + 1, 0);
break;
case MidiEvent.Meta:
// do nothing.
break;
default:
var size = MidiEvent.FixedDataSize (m.StatusByte);
buffer [0] = m.StatusByte;
buffer [1] = m.Msb;
buffer [2] = m.Lsb;
output.Send (buffer, 0, size + 1, 0);
break;
}
};
}
MidiEventLooper player;
// FIXME: it is still awkward to have it here. Move it into MidiEventLooper.
Task sync_player_task;
IMidiOutput output;
IList<MidiMessage> messages;
MidiMusic music;
bool should_dispose_output;
byte [] buffer = new byte [0x100];
bool [] channel_mask;
public event Action Finished {
add { player.Finished += value; }
remove { player.Finished -= value; }
}
public event Action PlaybackCompletedToEnd {
add { player.PlaybackCompletedToEnd += value; }
remove { player.PlaybackCompletedToEnd -= value; }
}
public PlayerState State {
get { return player.state; }
}
public double TempoChangeRatio {
get => player.tempo_ratio;
set => player.tempo_ratio = value;
}
public int Tempo {
get { return player.current_tempo; }
}
public int Bpm {
get { return (int) (60.0 / Tempo * 1000000.0); }
}
// You can break the data at your own risk but I take performance precedence.
public byte [] TimeSignature {
get { return player.current_time_signature; }
}
public int PlayDeltaTime {
get { return player.play_delta_time; }
}
public TimeSpan PositionInTime => TimeSpan.FromMilliseconds (music.GetTimePositionInMillisecondsForTick (PlayDeltaTime));
public int GetTotalPlayTimeMilliseconds ()
{
return MidiMusic.GetTotalPlayTimeMilliseconds (messages, music.DeltaTimeSpec);
}
public event MidiEventAction EventReceived {
add { player.EventReceived += value; }
remove { player.EventReceived -= value; }
}
public virtual void Dispose ()
{
player.Stop ();
if (should_dispose_output)
output.Dispose ();
}
[Obsolete ("This should not be callable externally. It will be removed in the next API-breaking update.")]
public void StartLoop ()
{
sync_player_task = Task.Run (() => { player.PlayerLoop (); });
}
[Obsolete ("Its naming is misleading. It starts playing asynchronously, but won't return any results unlike typical async API. Use new Play() method instead")]
public void PlayAsync () => Play ();
public void Play ()
{
switch (State) {
case PlayerState.Playing:
return; // do nothing
case PlayerState.Paused:
player.Play ();
return;
case PlayerState.Stopped:
if (sync_player_task == null || sync_player_task.Status != TaskStatus.Running)
#pragma warning disable 618
StartLoop ();
#pragma warning restore 618
player.Play ();
return;
}
}
[Obsolete ("Its naming is misleading. It starts playing asynchronously, but won't return any results unlike typical async API. Use new Pause() method instead")]
public void PauseAsync () => Pause ();
public void Pause ()
{
switch (State) {
case PlayerState.Playing:
player.Pause ();
return;
default: // do nothing
return;
}
}
public void Stop ()
{
switch (State) {
case PlayerState.Paused:
case PlayerState.Playing:
player.Stop ();
break;
}
}
[Obsolete ("Its naming is misleading. It starts seeking asynchronously, but won't return any results unlike typical async API. Use new Seek() method instead")]
public void SeekAsync (int ticks) => Seek (ticks);
public void Seek (int ticks)
{
player.Seek (null, ticks);
}
public void SetChannelMask (bool [] channelMask)
{
if (channelMask != null && channelMask.Length != 16)
throw new ArgumentException ("Unexpected length of channelMask array; it must be an array of 16 elements.");
channel_mask = channelMask;
// additionally send all sound off for the muted channels.
for (int ch = 0; ch < channelMask.Length; ch++)
if (channelMask [ch])
output.Send (new byte[] {(byte) (0xB0 + ch), 120, 0}, 0, 3, 0);
}
}
interface ISeekProcessor
{
SeekFilterResult FilterMessage (MidiMessage message);
}
enum SeekFilterResult
{
Pass,
Block,
PassAndTerminate,
BlockAndTerminate,
}
class SimpleSeekProcessor : ISeekProcessor
{
public SimpleSeekProcessor (int ticks)
{
this.seek_to = ticks;
}
private int seek_to, current;
public SeekFilterResult FilterMessage (MidiMessage message)
{
current += message.DeltaTime;
if (current >= seek_to)
return SeekFilterResult.PassAndTerminate;
switch (message.Event.EventType) {
case MidiEvent.NoteOn:
case MidiEvent.NoteOff:
return SeekFilterResult.Block;
}
return SeekFilterResult.Pass;
}
}
}
| |
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Web;
namespace RedditSharp
{
public class WebAgent : IWebAgent
{
/// <summary>
/// Additional values to append to the default RedditSharp user agent.
/// </summary>
public static string UserAgent { get; set; }
/// <summary>
/// It is strongly advised that you leave this enabled. Reddit bans excessive
/// requests with extreme predjudice.
/// </summary>
public static bool EnableRateLimit { get; set; }
/// <summary>
/// web protocol "http", "https"
/// </summary>
public static string Protocol { get; set; }
/// <summary>
/// It is strongly advised that you leave this set to Burst or Pace. Reddit bans excessive
/// requests with extreme predjudice.
/// </summary>
public static RateLimitMode RateLimit { get; set; }
/// <summary>
/// The method by which the WebAgent will limit request rate
/// </summary>
public enum RateLimitMode
{
/// <summary>
/// Limits requests to one every two seconds (one if OAuth)
/// </summary>
Pace,
/// <summary>
/// Restricts requests to five per ten seconds (ten if OAuth)
/// </summary>
SmallBurst,
/// <summary>
/// Restricts requests to thirty per minute (sixty if OAuth)
/// </summary>
Burst,
/// <summary>
/// Does not restrict request rate. ***NOT RECOMMENDED***
/// </summary>
None
}
/// <summary>
/// The root domain RedditSharp uses to address Reddit.
/// www.reddit.com by default
/// </summary>
public static string RootDomain { get; set; }
/// <summary>
/// Used to make calls against Reddit's API using OAuth2
/// </summary>
public string AccessToken { get; set; }
public CookieContainer Cookies { get; set; }
public string AuthCookie { get; set; }
private static DateTimeOffset _lastRequest;
private static DateTimeOffset _burstStart;
private static int _requestsThisBurst;
/// <summary>
/// UTC date and time of last request made to Reddit API
/// </summary>
public DateTimeOffset LastRequest
{
get { return _lastRequest; }
}
/// <summary>
/// UTC date and time of when the last burst started
/// </summary>
public DateTimeOffset BurstStart
{
get { return _burstStart; }
}
/// <summary>
/// Number of requests made during the current burst
/// </summary>
public int RequestsThisBurst
{
get { return _requestsThisBurst; }
}
/// <summary>
/// Whether or not to use a proxy when executing web requests
/// </summary>
public bool UseProxy { get; set; }
/// <summary>
/// Proxy for executing web requests, will not be used unless <see cref="UseProxy"/> is true
/// </summary>
public WebProxy Proxy { get; set; }
static WebAgent()
{
UserAgent = "";
RateLimit = RateLimitMode.Pace;
Protocol = "https";
RootDomain = "www.reddit.com";
}
/// <summary>
/// Execute a request and return a <see cref="JToken"/>
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public virtual JToken CreateAndExecuteRequest(string url)
{
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
{
if (!Uri.TryCreate(string.Format("{0}://{1}{2}", Protocol, RootDomain, url), UriKind.Absolute, out uri))
throw new Exception("Could not parse Uri");
}
var request = CreateGet(uri);
try { return ExecuteRequest(request); }
catch (Exception)
{
var tempProtocol = Protocol;
var tempRootDomain = RootDomain;
Protocol = "http";
RootDomain = "www.reddit.com";
var retval = CreateAndExecuteRequest(url);
Protocol = tempProtocol;
RootDomain = tempRootDomain;
return retval;
}
}
/// <summary>
/// Executes the web request and handles errors in the response
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public virtual JToken ExecuteRequest(HttpWebRequest request)
{
EnforceRateLimit();
if(UseProxy)
{
request.Proxy = Proxy;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var result = GetResponseString(response.GetResponseStream());
JToken json;
if (!string.IsNullOrEmpty(result))
{
json = JToken.Parse(result);
try
{
if (json["json"] != null)
{
json = json["json"]; //get json object if there is a root node
}
if (json["error"] != null)
{
switch (json["error"].ToString())
{
case "404":
throw new Exception("File Not Found");
case "403":
throw new Exception("Restricted");
case "invalid_grant":
//Refresh authtoken
//AccessToken = authProvider.GetRefreshToken();
//ExecuteRequest(request);
break;
}
}
}
catch
{
}
}
else
{
json = JToken.Parse("{'method':'" + response.Method + "','uri':'" + response.ResponseUri.AbsoluteUri + "','status':'" + response.StatusCode.ToString() + "'}");
}
return json;
}
/// <summary>
/// Enforce the api throttle.
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
protected virtual void EnforceRateLimit()
{
var limitRequestsPerMinute = IsOAuth() ? 60.0 : 30.0;
switch (RateLimit)
{
case RateLimitMode.Pace:
while ((DateTimeOffset.UtcNow - _lastRequest).TotalSeconds < 60.0 / limitRequestsPerMinute)// Rate limiting
Thread.Sleep(250);
_lastRequest = DateTimeOffset.UtcNow;
break;
case RateLimitMode.SmallBurst:
if (_requestsThisBurst == 0 || (DateTimeOffset.UtcNow - _burstStart).TotalSeconds >= 10) //this is first request OR the burst expired
{
_burstStart = DateTimeOffset.UtcNow;
_requestsThisBurst = 0;
}
if (_requestsThisBurst >= limitRequestsPerMinute / 6.0) //limit has been reached
{
while ((DateTimeOffset.UtcNow - _burstStart).TotalSeconds < 10)
Thread.Sleep(250);
_burstStart = DateTimeOffset.UtcNow;
_requestsThisBurst = 0;
}
_lastRequest = DateTimeOffset.UtcNow;
_requestsThisBurst++;
break;
case RateLimitMode.Burst:
if (_requestsThisBurst == 0 || (DateTimeOffset.UtcNow - _burstStart).TotalSeconds >= 60) //this is first request OR the burst expired
{
_burstStart = DateTimeOffset.UtcNow;
_requestsThisBurst = 0;
}
if (_requestsThisBurst >= limitRequestsPerMinute) //limit has been reached
{
while ((DateTimeOffset.UtcNow - _burstStart).TotalSeconds < 60)
Thread.Sleep(250);
_burstStart = DateTimeOffset.UtcNow;
_requestsThisBurst = 0;
}
_lastRequest = DateTimeOffset.UtcNow;
_requestsThisBurst++;
break;
}
}
/// <summary>
/// Create a <see cref="HttpWebRequest"/>
/// </summary>
/// <param name="url">target uri</param>
/// <param name="method">http method</param>
/// <returns></returns>
public virtual HttpWebRequest CreateRequest(string url, string method)
{
EnforceRateLimit();
bool prependDomain;
// IsWellFormedUriString returns true on Mono for some reason when using a string like "/api/me"
// additionally, doing this fixes an InvalidCastException
if (Type.GetType("Mono.Runtime") != null)
prependDomain = !url.StartsWith("http://") && !url.StartsWith("https://");
else
prependDomain = !Uri.IsWellFormedUriString(url, UriKind.Absolute);
HttpWebRequest request;
if (prependDomain)
request = (HttpWebRequest)WebRequest.Create(string.Format("{0}://{1}{2}", Protocol, RootDomain, url));
else
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = Cookies;
if (Type.GetType("Mono.Runtime") != null)
{
var cookieHeader = Cookies.GetCookieHeader(new Uri("http://reddit.com"));
request.Headers.Set("Cookie", cookieHeader);
}
if (IsOAuth() && request.Host.ToLower() == "oauth.reddit.com")// use OAuth
{
request.Headers.Set("Authorization", "bearer " + AccessToken);//Must be included in OAuth calls
}
request.Method = method;
request.UserAgent = UserAgent + " - with RedditSharp by /u/meepster23";
request = InjectProxy(request);
return request;
}
/// <summary>
/// Create a <see cref="HttpWebRequest"/>
/// </summary>
/// <param name="uri">target uri</param>
/// <param name="method">http method</param>
/// <returns></returns>
protected virtual HttpWebRequest CreateRequest(Uri uri, string method)
{
EnforceRateLimit();
var request = (HttpWebRequest)WebRequest.Create(uri);
request.CookieContainer = Cookies;
if (Type.GetType("Mono.Runtime") != null)
{
var cookieHeader = Cookies.GetCookieHeader(new Uri("http://reddit.com"));
request.Headers.Set("Cookie", cookieHeader);
}
if (IsOAuth() && uri.Host.ToLower() == "oauth.reddit.com")// use OAuth
{
request.Headers.Set("Authorization", "bearer " + AccessToken);//Must be included in OAuth calls
}
request.Method = method;
request.UserAgent = UserAgent + " - with RedditSharp by /u/meepster23";
request = InjectProxy(request);
return request;
}
/// <summary>
/// Create a http GET <see cref="HttpWebRequest"/>
/// </summary>
/// <param name="url">target url</param>
/// <returns></returns>
public virtual HttpWebRequest CreateGet(string url)
{
return CreateRequest(url, "GET");
}
/// <summary>
/// Create a http GET <see cref="HttpWebRequest"/>
/// </summary>
/// <param name="url">target uri</param>
/// <returns></returns>
private HttpWebRequest CreateGet(Uri url)
{
return CreateRequest(url, "GET");
}
/// <summary>
/// Create a http POST <see cref="HttpWebRequest"/>
/// </summary>
/// <param name="url">target url</param>
/// <returns></returns>
public virtual HttpWebRequest CreatePost(string url)
{
var request = CreateRequest(url, "POST");
request.ContentType = "application/x-www-form-urlencoded";
return request;
}
/// <summary>
/// Create a http PUT <see cref="HttpWebRequest"/>
/// </summary>
/// <param name="url">target url</param>
/// <returns></returns>
public virtual HttpWebRequest CreatePut(string url)
{
var request = CreateRequest(url, "PUT");
request.ContentType = "application/x-www-form-urlencoded";
return request;
}
/// <summary>
/// Create a http DELETE <see cref="HttpWebRequest"/>
/// </summary>
/// <param name="url">target url</param>
/// <returns></returns>
public virtual HttpWebRequest CreateDelete(string url)
{
var request = CreateRequest(url, "DELETE");
request.ContentType = "application/x-www-form-urlencoded";
return request;
}
/// <summary>
/// Read a string from a stream.
/// </summary>
/// <param name="stream">response stream</param>
/// <returns></returns>
public virtual string GetResponseString(Stream stream)
{
var data = new StreamReader(stream).ReadToEnd();
stream.Close();
return data;
}
/// <summary>
/// Write an object to a stream.
/// </summary>
/// <param name="stream">output stream</param>
/// <param name="data">input object</param>
/// <param name="additionalFields">additional fields to write</param>
public virtual void WritePostBody(Stream stream, object data, params string[] additionalFields)
{
var type = data.GetType();
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
string value = "";
foreach (var property in properties)
{
var attr = property.GetCustomAttributes(typeof(RedditAPINameAttribute), false).FirstOrDefault() as RedditAPINameAttribute;
string name = attr == null ? property.Name : attr.Name;
var entry = Convert.ToString(property.GetValue(data, null));
value += name + "=" + HttpUtility.UrlEncode(entry).Replace(";", "%3B").Replace("&", "%26") + "&";
}
for (int i = 0; i < additionalFields.Length; i += 2)
{
var entry = Convert.ToString(additionalFields[i + 1]) ?? string.Empty;
value += additionalFields[i] + "=" + HttpUtility.UrlEncode(entry).Replace(";", "%3B").Replace("&", "%26") + "&";
}
value = value.Remove(value.Length - 1); // Remove trailing &
var raw = Encoding.UTF8.GetBytes(value);
stream.Write(raw, 0, raw.Length);
stream.Close();
}
private static bool IsOAuth()
{
return RootDomain == "oauth.reddit.com";
}
/// <summary>
/// Inject the web proxy <see cref="Proxy"/> into the provided request
/// </summary>
/// <param name="request">The request object to inject the proxy into</param>
public virtual HttpWebRequest InjectProxy(HttpWebRequest request)
{
if (this.UseProxy)
{
request.Proxy = this.Proxy;
}
return request;
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.CSharp.RenameTracking;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Editor.VisualBasic.RenameTracking;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
internal sealed class RenameTrackingTestState : IDisposable
{
private readonly ITagger<RenameTrackingTag> _tagger;
public readonly TestWorkspace Workspace;
private readonly IWpfTextView _view;
private readonly ITextUndoHistoryRegistry _historyRegistry;
private string _notificationMessage = null;
private readonly TestHostDocument _hostDocument;
public TestHostDocument HostDocument { get { return _hostDocument; } }
private readonly IEditorOperations _editorOperations;
public IEditorOperations EditorOperations { get { return _editorOperations; } }
private readonly MockRefactorNotifyService _mockRefactorNotifyService;
public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } }
private readonly CodeFixProvider _codeFixProvider;
private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler();
public RenameTrackingTestState(
string markup,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
this.Workspace = CreateTestWorkspace(markup, languageName, TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic());
_hostDocument = Workspace.Documents.First();
_view = _hostDocument.GetTextView();
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value));
_editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view);
_historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value;
_mockRefactorNotifyService = new MockRefactorNotifyService
{
OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue,
OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue
};
var optionService = this.Workspace.Services.GetService<IOptionService>();
// Mock the action taken by the workspace INotificationService
var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback;
var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message);
notificationService.NotificationCallback = callback;
var tracker = new RenameTrackingTaggerProvider(
_historyRegistry,
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
Workspace.ExportProvider.GetExport<IInlineRenameService>().Value,
Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService),
Workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>());
_tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer());
if (languageName == LanguageNames.CSharp)
{
_codeFixProvider = new CSharpRenameTrackingCodeFixProvider(
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else if (languageName == LanguageNames.VisualBasic)
{
_codeFixProvider = new VisualBasicRenameTrackingCodeFixProvider(
Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else
{
throw new ArgumentException("Invalid language name: " + languageName, "languageName");
}
}
private static TestWorkspace CreateTestWorkspace(string code, string languageName, ExportProvider exportProvider = null)
{
var xml = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document>{1}</Document>
</Project>
</Workspace>", languageName, code);
return TestWorkspaceFactory.CreateWorkspace(xml, exportProvider: exportProvider);
}
public void SendEscape()
{
_commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), () => { });
}
public void MoveCaret(int delta)
{
var position = _view.Caret.Position.BufferPosition.Position;
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta));
}
public void Undo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Undo(count);
}
public void Redo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Redo(count);
}
public void AssertNoTag()
{
WaitForAsyncOperations();
var tags = _tagger.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(_view.TextBuffer.CurrentSnapshot, new Span(0, _view.TextBuffer.CurrentSnapshot.Length))));
Assert.Equal(0, tags.Count());
}
public IList<Diagnostic> GetDocumentDiagnostics(Document document = null)
{
document = document ?? this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var analyzer = new RenameTrackingDiagnosticAnalyzer();
return DiagnosticProviderTestUtilities.GetDocumentDiagnostics(analyzer, document, document.GetSyntaxRootAsync(CancellationToken.None).Result.FullSpan).ToList();
}
public void AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false)
{
WaitForAsyncOperations();
var tags = _tagger.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(_view.TextBuffer.CurrentSnapshot, new Span(0, _view.TextBuffer.CurrentSnapshot.Length))));
// There should only ever be one tag
Assert.Equal(1, tags.Count());
var tag = tags.Single();
var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var diagnostics = GetDocumentDiagnostics(document);
// There should be a single rename tracking diagnostic
Assert.Equal(1, diagnostics.Count);
Assert.Equal(RenameTrackingDiagnosticAnalyzer.DiagnosticId, diagnostics[0].Id);
var actions = new List<CodeAction>();
var context = new CodeFixContext(document, diagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
_codeFixProvider.RegisterCodeFixesAsync(context).Wait();
// There should only be one code action
Assert.Equal(1, actions.Count);
Assert.Equal(string.Format(EditorFeaturesResources.RenameTo, expectedFromName, expectedToName), actions[0].Title);
if (invokeAction)
{
var operations = actions[0]
.GetOperationsAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None)
.ToArray();
Assert.Equal(1, operations.Length);
operations[0].Apply(this.Workspace, CancellationToken.None);
}
}
public void AssertNoNotificationMessage()
{
Assert.Null(_notificationMessage);
}
public void AssertNotificationMessage()
{
Assert.NotNull(_notificationMessage);
}
private void WaitForAsyncOperations()
{
var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>();
var tasks = waiters.Select(w => w.CreateWaitTask()).ToList();
tasks.PumpingWaitAll();
}
public void Dispose()
{
Workspace.Dispose();
}
}
}
| |
using System;
using System.Collections.Generic;
using Sep.Git.Tfs.Core.TfsInterop;
using Sep.Git.Tfs.Commands;
namespace Sep.Git.Tfs.Core
{
class DerivedGitTfsRemote : IGitTfsRemote
{
private readonly string _tfsUrl;
private readonly string _tfsRepositoryPath;
public DerivedGitTfsRemote(string tfsUrl, string tfsRepositoryPath)
{
_tfsUrl = tfsUrl;
_tfsRepositoryPath = tfsRepositoryPath;
}
GitTfsException DerivedRemoteException
{
get
{
return new GitTfsException("Unable to locate a remote for <" + _tfsUrl + ">" + _tfsRepositoryPath)
.WithRecommendation("Try using `git tfs bootstrap` to auto-init TFS remotes.")
.WithRecommendation("Try setting a legacy-url for an existing remote.");
}
}
public bool IsDerived
{
get { return true; }
}
public string Id
{
get { return "(derived)"; }
set { throw DerivedRemoteException; }
}
public string TfsUrl
{
get { return _tfsUrl; }
set { throw DerivedRemoteException; }
}
public bool Autotag
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public string TfsUsername
{
get
{
throw DerivedRemoteException;
}
set
{
throw DerivedRemoteException;
}
}
public string TfsPassword
{
get
{
throw DerivedRemoteException;
}
set
{
throw DerivedRemoteException;
}
}
public string TfsRepositoryPath
{
get { return _tfsRepositoryPath; }
set { throw DerivedRemoteException; }
}
public string[] TfsSubtreePaths
{
get
{
throw DerivedRemoteException;
}
}
#region Equality
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(DerivedGitTfsRemote)) return false;
return Equals((DerivedGitTfsRemote)obj);
}
private bool Equals(DerivedGitTfsRemote other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other._tfsUrl, _tfsUrl) && Equals(other._tfsRepositoryPath, _tfsRepositoryPath);
}
public override int GetHashCode()
{
unchecked
{
return ((_tfsUrl != null ? _tfsUrl.GetHashCode() : 0) * 397) ^ (_tfsRepositoryPath != null ? _tfsRepositoryPath.GetHashCode() : 0);
}
}
public static bool operator ==(DerivedGitTfsRemote left, DerivedGitTfsRemote right)
{
return Equals(left, right);
}
public static bool operator !=(DerivedGitTfsRemote left, DerivedGitTfsRemote right)
{
return !Equals(left, right);
}
#endregion
#region All this is not implemented
public string IgnoreRegexExpression
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public string IgnoreExceptRegexExpression
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public IGitRepository Repository
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public ITfsHelper Tfs
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public int MaxChangesetId
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public string MaxCommitHash
{
get { throw DerivedRemoteException; }
set { throw DerivedRemoteException; }
}
public string RemoteRef
{
get { throw DerivedRemoteException; }
}
public bool IsSubtree
{
get { return false; }
}
public bool IsSubtreeOwner
{
get { return false; }
}
public string OwningRemoteId
{
get { return null; }
}
public string Prefix
{
get { return null; }
}
public bool ExportMetadatas { get; set; }
public Dictionary<string, string> ExportWorkitemsMapping { get; set; }
public bool ShouldSkip(string path)
{
throw DerivedRemoteException;
}
public IGitTfsRemote InitBranch(RemoteOptions remoteOptions, string tfsRepositoryPath, int shaRootChangesetId, bool fetchParentBranch, string gitBranchNameExpected = null, IRenameResult renameResult = null)
{
throw new NotImplementedException();
}
public string GetPathInGitRepo(string tfsPath)
{
throw DerivedRemoteException;
}
public IFetchResult Fetch(bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null)
{
throw DerivedRemoteException;
}
public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, IRenameResult renameResult = null, params string[] parentCommitsHashes)
{
throw DerivedRemoteException;
}
public void QuickFetch()
{
throw DerivedRemoteException;
}
public void QuickFetch(int changesetId)
{
throw DerivedRemoteException;
}
public void Unshelve(string a, string b, string c, Action<Exception> h, bool force)
{
throw DerivedRemoteException;
}
public void Shelve(string shelvesetName, string treeish, TfsChangesetInfo parentChangeset, CheckinOptions options, bool evaluateCheckinPolicies)
{
throw DerivedRemoteException;
}
public bool HasShelveset(string shelvesetName)
{
throw DerivedRemoteException;
}
public int CheckinTool(string head, TfsChangesetInfo parentChangeset)
{
throw DerivedRemoteException;
}
public int Checkin(string treeish, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null)
{
throw DerivedRemoteException;
}
public int Checkin(string head, string parent, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null)
{
throw DerivedRemoteException;
}
public void CleanupWorkspace()
{
throw DerivedRemoteException;
}
public void CleanupWorkspaceDirectory()
{
throw DerivedRemoteException;
}
public ITfsChangeset GetChangeset(int changesetId)
{
throw DerivedRemoteException;
}
public void UpdateTfsHead(string commitHash, int changesetId)
{
throw DerivedRemoteException;
}
public void EnsureTfsAuthenticated()
{
throw DerivedRemoteException;
}
public bool MatchesUrlAndRepositoryPath(string tfsUrl, string tfsRepositoryPath)
{
throw DerivedRemoteException;
}
public RemoteInfo RemoteInfo
{
get { throw DerivedRemoteException; }
}
public void Merge(string sourceTfsPath, string targetTfsPath)
{
throw DerivedRemoteException;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
using Microsoft.Build.Utilities;
namespace Microsoft.Build.Tasks
{
/// <summary>
/// This class defines an "Exec" MSBuild task, which simply invokes the specified process with the specified arguments, waits
/// for it to complete, and then returns True if the process completed successfully, and False if an error occurred.
/// </summary>
/// <comments>
/// UNDONE: ToolTask has a "UseCommandProcessor" flag that duplicates much of the code in this class. Remove the duplication.
/// </comments>
public class Exec : ToolTaskExtension
{
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public Exec()
{
Command = string.Empty;
// Console-based output uses the current system OEM code page by default. Note that we should not use Console.OutputEncoding
// here since processes we run don't really have much to do with our console window (and also Console.OutputEncoding
// doesn't return the OEM code page if the running application that hosts MSBuild is not a console application).
// If the cmd file contains non-ANSI characters encoding may change.
_standardOutputEncoding = EncodingUtilities.CurrentSystemOemEncoding;
_standardErrorEncoding = EncodingUtilities.CurrentSystemOemEncoding;
}
#endregion
#region Fields
private const string UseUtf8Always = "ALWAYS";
private const string UseUtf8Never = "NEVER";
private const string UseUtf8Detect = "DETECT";
// Are the encodings for StdErr and StdOut streams valid
private bool _encodingParametersValid = true;
private string _workingDirectory;
private ITaskItem[] _outputs;
internal bool workingDirectoryIsUNC; // internal for unit testing
private string _batchFile;
private string _customErrorRegex;
private string _customWarningRegex;
private readonly List<ITaskItem> _nonEmptyOutput = new List<ITaskItem>();
private Encoding _standardErrorEncoding;
private Encoding _standardOutputEncoding;
private string _command;
#endregion
#region Properties
[Required]
public string Command
{
get => _command;
set
{
_command = value;
if (NativeMethodsShared.IsUnixLike)
{
_command = _command.Replace("\r\n", "\n");
}
}
}
public string WorkingDirectory { get; set; }
public bool IgnoreExitCode { get; set; }
/// <summary>
/// Enable the pipe of the standard out to an item (StandardOutput).
/// </summary>
/// <Remarks>
/// Even thought this is called a pipe, it is in fact a Tee. Use StandardOutputImportance to adjust the visibility of the stdout.
/// </Remarks>
public bool ConsoleToMSBuild { get; set; }
/// <summary>
/// Users can supply a regular expression that we should
/// use to spot error lines in the tool output. This is
/// useful for tools that produce unusually formatted output
/// </summary>
public string CustomErrorRegularExpression
{
get => _customErrorRegex;
set => _customErrorRegex = value;
}
/// <summary>
/// Users can supply a regular expression that we should
/// use to spot warning lines in the tool output. This is
/// useful for tools that produce unusually formatted output
/// </summary>
public string CustomWarningRegularExpression
{
get => _customWarningRegex;
set => _customWarningRegex = value;
}
/// <summary>
/// Whether to use pick out lines in the output that match
/// the standard error/warning format, and log them as errors/warnings.
/// Defaults to false.
/// </summary>
public bool IgnoreStandardErrorWarningFormat { get; set; }
/// <summary>
/// Property specifying the encoding of the captured task standard output stream
/// </summary>
protected override Encoding StandardOutputEncoding => _standardOutputEncoding;
/// <summary>
/// Property specifying the encoding of the captured task standard error stream
/// </summary>
protected override Encoding StandardErrorEncoding => _standardErrorEncoding;
/// <summary>
/// Whether or not to use UTF8 encoding for the cmd file and console window.
/// Values: Always, Never, Detect
/// If set to Detect, the current code page will be used unless it cannot represent
/// the Command string. In that case, UTF-8 is used.
/// </summary>
public string UseUtf8Encoding { get; set; }
/// <summary>
/// Project visible property specifying the encoding of the captured task standard output stream
/// </summary>
[Output]
public string StdOutEncoding
{
get => StandardOutputEncoding.EncodingName;
set
{
try
{
_standardOutputEncoding = Encoding.GetEncoding(value);
}
catch (ArgumentException)
{
Log.LogErrorWithCodeFromResources("General.InvalidValue", "StdOutEncoding", "Exec");
_encodingParametersValid = false;
}
}
}
/// <summary>
/// Project visible property specifying the encoding of the captured task standard error stream
/// </summary>
[Output]
public string StdErrEncoding
{
get => StandardErrorEncoding.EncodingName;
set
{
try
{
_standardErrorEncoding = Encoding.GetEncoding(value);
}
catch (ArgumentException)
{
Log.LogErrorWithCodeFromResources("General.InvalidValue", "StdErrEncoding", "Exec");
_encodingParametersValid = false;
}
}
}
[Output]
public ITaskItem[] Outputs
{
get => _outputs ?? Array.Empty<ITaskItem>();
set => _outputs = value;
}
/// <summary>
/// Returns the output as an Item. Whitespace are trimmed.
/// ConsoleOutput is enabled when ConsoleToMSBuild is true. This avoids holding lines in memory
/// if they aren't used. ConsoleOutput is a combination of stdout and stderr.
/// </summary>
[Output]
public ITaskItem[] ConsoleOutput => !ConsoleToMSBuild ? Array.Empty<ITaskItem>(): _nonEmptyOutput.ToArray();
#endregion
#region Methods
/// <summary>
/// Write out a temporary batch file with the user-specified command in it.
/// </summary>
private void CreateTemporaryBatchFile()
{
var encoding = BatchFileEncoding();
// Temporary file with the extension .Exec.bat
_batchFile = FileUtilities.GetTemporaryFile(".exec.cmd");
// UNICODE Batch files are not allowed as of WinXP. We can't use normal ANSI code pages either,
// since console-related apps use OEM code pages "for historical reasons". Sigh.
// We need to get the current OEM code page which will be the same language as the current ANSI code page,
// just the OEM version.
// See http://www.microsoft.com/globaldev/getWR/steps/wrg_codepage.mspx for a discussion of ANSI vs OEM
// Note: 8/12/15 - Switched to use UTF8 on OS newer than 6.1 (Windows 7)
// Note: 1/12/16 - Only use UTF8 when we detect we need to or the user specifies 'Always'
using (StreamWriter sw = FileUtilities.OpenWrite(_batchFile, false, encoding))
{
if (!NativeMethodsShared.IsUnixLike)
{
// In some wierd setups, users may have set an env var actually called "errorlevel"
// this would cause our "exit %errorlevel%" to return false.
// This is because the actual errorlevel value is not an environment variable, but some commands,
// such as "exit %errorlevel%" will use the environment variable with that name if it exists, instead
// of the actual errorlevel value. So we must temporarily reset errorlevel locally first.
sw.WriteLine("setlocal");
// One more wrinkle.
// "set foo=" has odd behavior: it sets errorlevel to 1 if there was no environment variable named
// "foo" defined.
// This has the effect of making "set errorlevel=" set an errorlevel of 1 if an environment
// variable named "errorlevel" didn't already exist!
// To avoid this problem, set errorlevel locally to a dummy value first.
sw.WriteLine("set errorlevel=dummy");
sw.WriteLine("set errorlevel=");
// We may need to change the code page and console encoding.
if (encoding.CodePage != EncodingUtilities.CurrentSystemOemEncoding.CodePage)
{
// Output to nul so we don't change output and logs.
sw.WriteLine($@"%SystemRoot%\System32\chcp.com {encoding.CodePage}>nul");
// Ensure that the console encoding is correct.
_standardOutputEncoding = encoding;
_standardErrorEncoding = encoding;
}
// if the working directory is a UNC path, bracket the exec command with pushd and popd, because pushd
// automatically maps the network path to a drive letter, and then popd disconnects it.
// This is required because Cmd.exe does not support UNC names as the current directory:
// https://support.microsoft.com/en-us/kb/156276
if (workingDirectoryIsUNC)
{
sw.WriteLine("pushd " + _workingDirectory);
}
}
else
{
// Use sh rather than bash, as not all 'nix systems necessarily have Bash installed
sw.WriteLine("#!/bin/sh");
}
if (NativeMethodsShared.IsUnixLike && NativeMethodsShared.IsMono)
{
// Extract the command we are going to run. Note that the command name may
// be preceded by whitespace
var m = Regex.Match(Command, @"^\s*((?:(?:(?<!\\)[^\0 !$`&*()+])|(?:(?<=\\)[^\0]))+)(.*)");
if (m.Success && m.Groups.Count > 1 && m.Groups[1].Captures.Count > 0)
{
string exe = m.Groups[1].Captures[0].ToString();
string commandLine = (m.Groups.Count > 2 && m.Groups[2].Captures.Count > 0) ?
m.Groups[2].Captures[0].Value : "";
// If we are trying to run a .exe file, prepend mono as the file may
// not be runnable
if (exe.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
|| exe.EndsWith(".exe\"", StringComparison.OrdinalIgnoreCase)
|| exe.EndsWith(".exe'", StringComparison.OrdinalIgnoreCase))
{
Command = "mono " + FileUtilities.FixFilePath(exe) + commandLine;
}
}
}
sw.WriteLine(Command);
if (!NativeMethodsShared.IsUnixLike)
{
if (workingDirectoryIsUNC)
{
sw.WriteLine("popd");
}
// NOTES:
// 1) there's a bug in the Process class where the exit code is not returned properly i.e. if the command
// fails with exit code 9009, Process.ExitCode returns 1 -- the statement below forces it to return the
// correct exit code
// 2) also because of another (or perhaps the same) bug in the Process class, when we use pushd/popd for a
// UNC path, even if the command fails, the exit code comes back as 0 (seemingly reflecting the success
// of popd) -- the statement below fixes that too
// 3) the above described behaviour is most likely bugs in the Process class because batch files in a
// console window do not hide or change the exit code a.k.a. errorlevel, esp. since the popd command is
// a no-fail command, and it never changes the previous errorlevel
sw.WriteLine("exit %errorlevel%");
}
}
}
#endregion
#region Overridden methods
/// <summary>
/// Executes cmd.exe and waits for it to complete
/// </summary>
/// <remarks>
/// Overridden to clean up the batch file afterwards.
/// </remarks>
/// <returns>Upon completion of the process, returns True if successful, False if not.</returns>
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
try
{
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
finally
{
DeleteTempFile(_batchFile);
}
}
/// <summary>
/// Allows tool to handle the return code.
/// This method will only be called with non-zero exitCode set to true.
/// </summary>
/// <remarks>
/// Overridden to make sure we display the command we put in the batch file, not the cmd.exe command
/// used to run the batch file.
/// </remarks>
protected override bool HandleTaskExecutionErrors()
{
if (IgnoreExitCode)
{
Log.LogMessageFromResources(MessageImportance.Normal, "Exec.CommandFailedNoErrorCode", Command, ExitCode);
return true;
}
if (ExitCode == NativeMethods.SE_ERR_ACCESSDENIED)
{
Log.LogErrorWithCodeFromResources("Exec.CommandFailedAccessDenied", Command, ExitCode);
}
else
{
Log.LogErrorWithCodeFromResources("Exec.CommandFailed", Command, ExitCode);
}
return false;
}
/// <summary>
/// Logs the tool name and the path from where it is being run.
/// </summary>
/// <remarks>
/// Overridden to avoid logging the path to "cmd.exe", which is not interesting.
/// </remarks>
protected override void LogPathToTool(string toolName, string pathToTool)
{
// Do nothing
}
/// <summary>
/// Logs the command to be executed.
/// </summary>
/// <remarks>
/// Overridden to log the batch file command instead of the cmd.exe command.
/// </remarks>
/// <param name="message"></param>
protected override void LogToolCommand(string message)
{
//Dont print the command line if Echo is Off.
if (!EchoOff)
{
base.LogToolCommand(Command);
}
}
/// <summary>
/// Calls a method on the TaskLoggingHelper to parse a single line of text to
/// see if there are any errors or warnings in canonical format.
/// </summary>
/// <remarks>
/// Overridden to handle any custom regular expressions supplied.
/// </remarks>
protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
{
if (OutputMatchesRegex(singleLine, ref _customErrorRegex))
{
Log.LogError(singleLine);
}
else if (OutputMatchesRegex(singleLine, ref _customWarningRegex))
{
Log.LogWarning(singleLine);
}
else if (IgnoreStandardErrorWarningFormat)
{
// Not detecting regular format errors and warnings, and it didn't
// match any regexes either -- log as a regular message
Log.LogMessage(messageImportance, singleLine, null);
}
else
{
// This is the normal code path: match standard format errors and warnings
Log.LogMessageFromText(singleLine, messageImportance);
}
if (ConsoleToMSBuild)
{
string trimmedTextLine = singleLine.Trim();
if (trimmedTextLine.Length > 0)
{
// The lines read may be unescaped, so we need to escape them
// before passing them to the TaskItem.
_nonEmptyOutput.Add(new TaskItem(EscapingUtilities.Escape(trimmedTextLine)));
}
}
}
/// <summary>
/// Returns true if the string is matched by the regular expression.
/// If the regular expression is invalid, logs an error, then clears it out to
/// prevent more errors.
/// </summary>
private bool OutputMatchesRegex(string singleLine, ref string regularExpression)
{
if (regularExpression == null)
{
return false;
}
bool match = false;
try
{
match = Regex.IsMatch(singleLine, regularExpression);
}
catch (ArgumentException ex)
{
Log.LogErrorWithCodeFromResources("Exec.InvalidRegex", regularExpression, ex.Message);
// Clear out the regex so there won't be any more errors; let the tool continue,
// then it will fail because of the error we just logged
regularExpression = null;
}
return match;
}
/// <summary>
/// Validate the task arguments, log any warnings/errors
/// </summary>
/// <returns>true if arguments are corrent enough to continue processing, false otherwise</returns>
protected override bool ValidateParameters()
{
// If either of the encoding parameters passed to the task were
// invalid, then we should report that fact back to tooltask
if (!_encodingParametersValid)
{
return false;
}
// Make sure that at least the Command property was set
if (Command.Trim().Length == 0)
{
Log.LogErrorWithCodeFromResources("Exec.MissingCommandError");
return false;
}
// determine what the working directory for the exec command is going to be -- if the user specified a working
// directory use that, otherwise it's the current directory
_workingDirectory = !string.IsNullOrEmpty(WorkingDirectory)
? WorkingDirectory
: Directory.GetCurrentDirectory();
// check if the working directory we're going to use for the exec command is a UNC path
workingDirectoryIsUNC = FileUtilitiesRegex.StartsWithUncPattern.IsMatch(_workingDirectory);
// if the working directory is a UNC path, and all drive letters are mapped, bail out, because the pushd command
// will not be able to auto-map to the UNC path
if (workingDirectoryIsUNC && NativeMethods.AllDrivesMapped())
{
Log.LogErrorWithCodeFromResources("Exec.AllDriveLettersMappedError", _workingDirectory);
return false;
}
return true;
}
/// <summary>
/// Accessor for ValidateParameters purely for unit-test use
/// </summary>
/// <returns></returns>
internal bool ValidateParametersAccessor()
{
return ValidateParameters();
}
/// <summary>
/// Determining the path to cmd.exe
/// </summary>
/// <returns>path to cmd.exe</returns>
protected override string GenerateFullPathToTool()
{
return CommandProcessorPath.Value;
}
private static readonly Lazy<string> CommandProcessorPath = new Lazy<string>(() =>
{
// Get the fully qualified path to cmd.exe
if (NativeMethodsShared.IsWindows)
{
var systemCmd = ToolLocationHelper.GetPathToSystemFile("cmd.exe");
#if WORKAROUND_COREFX_19110
// Work around https://github.com/Microsoft/msbuild/issues/2273 and
// https://github.com/dotnet/corefx/issues/19110, which result in
// a bad path being returned above on Nano Server SKUs of Windows.
if (!FileSystems.Default.FileExists(systemCmd))
{
return Environment.GetEnvironmentVariable("ComSpec");
}
#endif
return systemCmd;
}
else
{
return "sh";
}
});
/// <summary>
/// Gets the working directory to use for the process. Should return null if ToolTask should use the
/// current directory.
/// May throw an IOException if the directory to be used is somehow invalid.
/// </summary>
/// <returns>working directory</returns>
protected override string GetWorkingDirectory()
{
// If the working directory is UNC, we're going to use "pushd" in the batch file to set it.
// If it's invalid, pushd won't fail: it will just go ahead and use the system folder.
// So verify it's valid here.
if (!FileSystems.Default.DirectoryExists(_workingDirectory))
{
throw new DirectoryNotFoundException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Exec.InvalidWorkingDirectory", _workingDirectory));
}
if (workingDirectoryIsUNC)
{
// if the working directory for the exec command is UNC, set the process working directory to the system path
// so that it doesn't display this silly error message:
// '\\<server>\<share>'
// CMD.EXE was started with the above path as the current directory.
// UNC paths are not supported. Defaulting to Windows directory.
return ToolLocationHelper.PathToSystem;
}
else
{
return _workingDirectory;
}
}
/// <summary>
/// Accessor for GetWorkingDirectory purely for unit-test use
/// </summary>
/// <returns></returns>
internal string GetWorkingDirectoryAccessor()
{
return GetWorkingDirectory();
}
/// <summary>
/// Adds the arguments for cmd.exe
/// </summary>
/// <param name="commandLine">command line builder class to add arguments to</param>
protected internal override void AddCommandLineCommands(CommandLineBuilderExtension commandLine)
{
// Create the batch file now,
// so we have the file name for the cmd.exe command line
CreateTemporaryBatchFile();
string batchFileForCommandLine = _batchFile;
// Unix consoles cannot have their encodings changed in place (like chcp on windows).
// Instead, unix scripts receive encoding information via environment variables before invocation.
// In consequence, encoding setup has to be performed outside the script, not inside it.
if (NativeMethodsShared.IsUnixLike)
{
commandLine.AppendSwitch("-c");
commandLine.AppendTextUnquoted(" \"");
commandLine.AppendTextUnquoted("export LANG=en_US.UTF-8; export LC_ALL=en_US.UTF-8; . ");
commandLine.AppendFileNameIfNotNull(batchFileForCommandLine);
commandLine.AppendTextUnquoted("\"");
}
else
{
if (NativeMethodsShared.IsWindows)
{
commandLine.AppendSwitch("/Q"); // echo off
if(!Traits.Instance.EscapeHatches.UseAutoRunWhenLaunchingProcessUnderCmd)
{
commandLine.AppendSwitch("/D"); // do not load AutoRun configuration from the registry (perf)
}
commandLine.AppendSwitch("/C"); // run then terminate
// If for some crazy reason the path has a & character and a space in it
// then get the short path of the temp path, which should not have spaces in it
// and then escape the &
if (batchFileForCommandLine.Contains("&") && !batchFileForCommandLine.Contains("^&"))
{
batchFileForCommandLine = NativeMethodsShared.GetShortFilePath(batchFileForCommandLine);
batchFileForCommandLine = batchFileForCommandLine.Replace("&", "^&");
}
}
commandLine.AppendFileNameIfNotNull(batchFileForCommandLine);
}
}
#endregion
#region Overridden properties
/// <summary>
/// The name of the tool to execute
/// </summary>
protected override string ToolName => NativeMethodsShared.IsWindows ? "cmd.exe" : "sh";
/// <summary>
/// Importance with which to log ordinary messages in the
/// standard error stream.
/// </summary>
protected override MessageImportance StandardErrorLoggingImportance => MessageImportance.High;
/// <summary>
/// Importance with which to log ordinary messages in the
/// standard out stream.
/// </summary>
/// <remarks>
/// Overridden to increase from the default "Low" up to "High".
/// </remarks>
protected override MessageImportance StandardOutputLoggingImportance => MessageImportance.High;
#endregion
private static readonly Encoding s_utf8WithoutBom = new UTF8Encoding(false);
/// <summary>
/// Find the encoding for the batch file.
/// </summary>
/// <remarks>
/// The "best" encoding is the current OEM encoding, unless it's not capable of representing
/// the characters we plan to put in the file. If it isn't, we can fall back to UTF-8.
///
/// Why not always UTF-8? Because tools don't always handle it well. See
/// https://github.com/Microsoft/msbuild/issues/397
/// </remarks>
private Encoding BatchFileEncoding()
{
if (!NativeMethodsShared.IsWindows)
{
return s_utf8WithoutBom;
}
var defaultEncoding = EncodingUtilities.CurrentSystemOemEncoding;
string useUtf8 = string.IsNullOrEmpty(UseUtf8Encoding) ? UseUtf8Detect : UseUtf8Encoding;
#if FEATURE_OSVERSION
// UTF8 is only supposed in Windows 7 (6.1) or greater.
var windows7 = new Version(6, 1);
if (Environment.OSVersion.Version < windows7)
{
useUtf8 = UseUtf8Never;
}
#endif
switch (useUtf8.ToUpperInvariant())
{
case UseUtf8Always:
return s_utf8WithoutBom;
case UseUtf8Never:
return EncodingUtilities.CurrentSystemOemEncoding;
default:
return CanEncodeString(defaultEncoding.CodePage, Command + WorkingDirectory)
? defaultEncoding
: s_utf8WithoutBom;
}
}
/// <summary>
/// Checks to see if a string can be encoded in a specified code page.
/// </summary>
/// <remarks>Internal for testing purposes.</remarks>
/// <param name="codePage">Code page for encoding.</param>
/// <param name="stringToEncode">String to encode.</param>
/// <returns>True if the string can be encoded in the specified code page.</returns>
internal static bool CanEncodeString(int codePage, string stringToEncode)
{
// We have a System.String that contains some characters. Get a lossless representation
// in byte-array form.
var unicodeEncoding = new UnicodeEncoding();
var unicodeBytes = unicodeEncoding.GetBytes(stringToEncode);
// Create an Encoding using the desired code page, but throws if there's a
// character that can't be represented.
var systemEncoding = Encoding.GetEncoding(codePage, EncoderFallback.ExceptionFallback,
DecoderFallback.ExceptionFallback);
try
{
var oemBytes = Encoding.Convert(unicodeEncoding, systemEncoding, unicodeBytes);
// If Convert didn't throw, we can represent everything in the desired encoding.
return true;
}
catch (EncoderFallbackException)
{
// If a fallback encoding was attempted, we need to go to Unicode.
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE;
using System.Collections;
using System.Xml;
using System.IO;
using System.Resources;
namespace SPALM.SPSF.Library
{
public class SharePointConfigurationHelper
{
static string resourcefolder = "";
static string sharepointpath = "";
static string sharepointwebtemppath = "";
//static string defaultlocal = "en-US";
static Dictionary<string, CustomResXResourceReader> resourcesDictionary;
/// <summary>
/// Creates a new sharepoint configuration file in the current solution
/// </summary>
/// <param name="dte"></param>
internal static void CreateSharePointConfigurationFile(DTE dte)
{
resourcefolder = Helpers.GetSharePointHive();
//defaultlocal = "en-US";
sharepointpath = Path.Combine(Helpers.GetSharePointHive(), @"TEMPLATE\FEATURES");
sharepointwebtemppath = Path.Combine(Helpers.GetSharePointHive(), @"TEMPLATE\1033\XML");
//reloading sharepoint configuration
//load resouces
resourcesDictionary = new Dictionary<string, CustomResXResourceReader>();
Helpers.LoadResources(resourcefolder, resourcesDictionary);
//open the existing sharepoint configuration file
string solutionDirectory = Path.GetDirectoryName((string)dte.Solution.Properties.Item("Path").Value);
string toPath = Path.Combine(solutionDirectory, "SharepointConfiguration.xml");
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineHandling = NewLineHandling.Entitize;
settings.Encoding = Encoding.UTF8;
MemoryStream memStream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(memStream, settings);
writer.WriteStartDocument();
writer.WriteStartElement("SharePointConfiguration");
UpdateContentTypes(writer);
UpdateSiteColumns(writer);
UpdateListTemplates(writer);
UpdateWebTemplates(writer);
UpdateFeatures(writer);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
StreamReader reader = new StreamReader(memStream, Encoding.UTF8, true);
memStream.Seek(0, SeekOrigin.Begin);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
doc.Save(toPath);
}
private static void UpdateFeatures(XmlWriter writer)
{
writer.WriteStartElement("Features");
if (Directory.Exists(sharepointpath))
{
foreach (string s in Directory.GetFiles(sharepointpath, "Feature.xml", SearchOption.AllDirectories))
{
if (File.Exists(s))
{
try
{
XmlDocument featurexml = new XmlDocument();
featurexml.Load(s);
string featurename = Directory.GetParent(s).Name;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(featurexml.NameTable);
nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/sharepoint/");
XmlNode featurenode = featurexml.SelectSingleNode("/ns:Feature", nsmgr);
if (featurenode != null)
{
writer.WriteStartElement("Feature");
writer.WriteAttributeString("Id", featurenode.Attributes["Id"].Value);
writer.WriteAttributeString("Title", Helpers.GetResourceString(GetAttribute(featurenode, "Title"), featurename, resourcesDictionary));
writer.WriteAttributeString("Description", Helpers.GetResourceString(GetAttribute(featurenode, "Description"), featurename, resourcesDictionary));
writer.WriteAttributeString("Scope", featurenode.Attributes["Scope"].Value);
writer.WriteEndElement();
}
}
catch (Exception)
{
}
}
}
}
writer.WriteEndElement();
}
private static void UpdateWebTemplates(XmlWriter writer)
{
writer.WriteStartElement("SiteTemplates");
if (Directory.Exists(sharepointwebtemppath))
{
foreach (string s in Directory.GetFiles(sharepointwebtemppath, "webtemp*.xml", SearchOption.TopDirectoryOnly))
{
if (File.Exists(s))
{
try
{
XmlDocument webtempxml = new XmlDocument();
webtempxml.Load(s);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(webtempxml.NameTable);
nsmgr.AddNamespace("ows", "Microsoft SharePoint");
foreach (XmlNode webnode in webtempxml.SelectNodes("/Templates/Template"))
{
//jetzt alle configuration nodes
foreach (XmlNode confignode in webnode.SelectNodes("Configuration"))
{
writer.WriteStartElement("SiteTemplate");
writer.WriteAttributeString("Id", GetAttribute(webnode, "Name") + "#" + GetAttribute(confignode, "ID"));
writer.WriteAttributeString("Title", GetAttribute(confignode, "Title"));
writer.WriteAttributeString("Description", GetAttribute(confignode, "Description"));
writer.WriteAttributeString("DisplayCategory", GetAttribute(confignode, "DisplayCategory"));
writer.WriteEndElement();
}
}
}
catch (Exception)
{
}
}
}
}
writer.WriteEndElement();
}
private static string GetAttribute(XmlNode node, string attribute)
{
if (node.Attributes[attribute] != null)
{
return node.Attributes[attribute].Value;
}
return "";
}
private static void UpdateListTemplates(XmlWriter writer)
{
writer.WriteStartElement("ListTemplates");
if (Directory.Exists(sharepointpath))
{
foreach (string s in Directory.GetFiles(sharepointpath, "*.xml", SearchOption.AllDirectories))
{
if (File.Exists(s))
{
try
{
XmlDocument featurexml = new XmlDocument();
featurexml.Load(s);
string featurename = Directory.GetParent(s).Name;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(featurexml.NameTable);
nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/sharepoint/");
foreach (XmlNode webnode in featurexml.SelectNodes("/ns:Elements/ns:ListTemplate", nsmgr))
{
writer.WriteStartElement("ListTemplate");
writer.WriteAttributeString("Type", GetAttribute(webnode, "Type"));
writer.WriteAttributeString("DisplayName", Helpers.GetResourceString(GetAttribute(webnode, "DisplayName"), featurename, resourcesDictionary));
writer.WriteAttributeString("Description", Helpers.GetResourceString(GetAttribute(webnode, "Description"), featurename, resourcesDictionary));
//get the parent feature id
string featureId = GetFeatureId(Directory.GetParent(s));
writer.WriteAttributeString("FeatureId", featureId);
writer.WriteEndElement();
}
}
catch (Exception)
{
}
}
}
}
writer.WriteEndElement();
}
private static string GetFeatureId(DirectoryInfo currentDir)
{
string featureId = "";
//is the parent directory "FEATURES"?
if (currentDir.Parent.Name.Equals("features", StringComparison.InvariantCultureIgnoreCase))
{
//currentDir is a feature directory
string featureXml = Path.Combine(currentDir.FullName, "feature.xml");
if (File.Exists(featureXml))
{
featureId = GetFeatureFromFeatureXml(featureXml);
}
}
else if (currentDir.Parent != null)
{
featureId = GetFeatureId(currentDir.Parent);
}
return featureId;
}
private static string GetFeatureFromFeatureXml(string featureXml)
{
try
{
XmlDocument featurexml = new XmlDocument();
featurexml.Load(featureXml);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(featurexml.NameTable);
nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/sharepoint/");
XmlNode featurenode = featurexml.SelectSingleNode("/ns:Feature", nsmgr);
if (featurenode != null)
{
return featurenode.Attributes["Id"].Value;
}
}
catch (Exception)
{
}
return "";
}
private static void UpdateSiteColumns(XmlWriter writer)
{
writer.WriteStartElement("Fields");
if (Directory.Exists(sharepointpath))
{
foreach (string s in Directory.GetFiles(sharepointpath, "*.xml", SearchOption.AllDirectories))
{
if (File.Exists(s))
{
try
{
XmlDocument featurexml = new XmlDocument();
featurexml.Load(s);
string featurename = Directory.GetParent(s).Name;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(featurexml.NameTable);
nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/sharepoint/");
foreach (XmlNode webnode in featurexml.SelectNodes("/ns:Elements/ns:Field", nsmgr))
{
writer.WriteStartElement("Field");
writer.WriteAttributeString("ID", GetAttribute(webnode, "ID"));
writer.WriteAttributeString("DisplayName", Helpers.GetResourceString(GetAttribute(webnode, "DisplayName"), featurename, resourcesDictionary));
writer.WriteAttributeString("Description", Helpers.GetResourceString(GetAttribute(webnode, "Description"), featurename, resourcesDictionary));
writer.WriteAttributeString("Group", Helpers.GetResourceString(GetAttribute(webnode, "Group"), featurename, resourcesDictionary));
writer.WriteEndElement();
}
}
catch (Exception)
{
}
}
}
}
writer.WriteEndElement();
}
private static void UpdateContentTypes(XmlWriter writer)
{
writer.WriteStartElement("ContentTypes");
if (Directory.Exists(sharepointpath))
{
foreach (string s in Directory.GetFiles(sharepointpath, "*.xml", SearchOption.AllDirectories))
{
if (File.Exists(s))
{
try
{
XmlDocument featurexml = new XmlDocument();
featurexml.Load(s);
string featurename = Directory.GetParent(s).Name;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(featurexml.NameTable);
nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/sharepoint/");
foreach (XmlNode webnode in featurexml.SelectNodes("/ns:Elements/ns:ContentType", nsmgr))
{
writer.WriteStartElement("ContentType");
writer.WriteAttributeString("ID", GetAttribute(webnode, "ID"));
writer.WriteAttributeString("Name", Helpers.GetResourceString(GetAttribute(webnode, "Name"), featurename, resourcesDictionary));
writer.WriteAttributeString("Description", Helpers.GetResourceString(GetAttribute(webnode, "Description"), featurename, resourcesDictionary));
writer.WriteAttributeString("Group", Helpers.GetResourceString(GetAttribute(webnode, "Group"), featurename, resourcesDictionary));
writer.WriteEndElement();
}
}
catch (Exception)
{
}
}
}
}
writer.WriteEndElement();
}
}
}
| |
// 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,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using System.Windows;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Project;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Shell;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Commands {
/// <summary>
/// Provides the command for starting a file or the start item of a project in the REPL window.
/// </summary>
internal sealed class ExecuteInReplCommand : Command {
private readonly IServiceProvider _serviceProvider;
public ExecuteInReplCommand(IServiceProvider serviceProvider) {
_serviceProvider = serviceProvider;
}
internal static IVsInteractiveWindow/*!*/ EnsureReplWindow(IServiceProvider serviceProvider, VsProjectAnalyzer analyzer, PythonProjectNode project, IPythonWorkspaceContext workspace) {
return EnsureReplWindow(serviceProvider, analyzer.InterpreterFactory.Configuration, project, workspace);
}
internal static IVsInteractiveWindow/*!*/ EnsureReplWindow(IServiceProvider serviceProvider, InterpreterConfiguration config, PythonProjectNode project, IPythonWorkspaceContext workspace) {
var compModel = serviceProvider.GetComponentModel();
var provider = compModel.GetService<InteractiveWindowProvider>();
var vsProjectContext = compModel.GetService<VsProjectContextProvider>();
var projectId = project != null ? PythonReplEvaluatorProvider.GetEvaluatorId(project) : null;
var workspaceId = workspace != null ? PythonReplEvaluatorProvider.GetEvaluatorId(workspace) : null;
var configId = config != null ? PythonReplEvaluatorProvider.GetEvaluatorId(config) : null;
if (config?.IsRunnable() == false) {
throw new MissingInterpreterException(
Strings.MissingEnvironment.FormatUI(config.Description, config.Version)
);
}
IVsInteractiveWindow window;
// If we find an open window for the project, prefer that to a per-config one
if (!string.IsNullOrEmpty(projectId)) {
window = provider.Open(
projectId,
e => ((e as SelectableReplEvaluator)?.Evaluator as PythonCommonInteractiveEvaluator)?.AssociatedProjectHasChanged != true
);
if (window != null) {
return window;
}
}
// If we find an open window for the workspace, prefer that to a per config one
if (!string.IsNullOrEmpty(workspaceId)) {
window = provider.Open(
workspaceId,
e => ((e as SelectableReplEvaluator)?.Evaluator as PythonCommonInteractiveEvaluator)?.AssociatedWorkspaceHasChanged != true
);
if (window != null) {
return window;
}
}
// If we find an open window for the configuration, return that
if (!string.IsNullOrEmpty(configId)) {
window = provider.Open(configId);
if (window != null) {
return window;
}
}
// No window found, so let's create one
if (!string.IsNullOrEmpty(projectId)) {
window = provider.Create(projectId);
project.AddActionOnClose(window, w => InteractiveWindowProvider.CloseIfEvaluatorMatches(w, projectId));
} else if (!string.IsNullOrEmpty(workspaceId)) {
window = provider.Create(workspaceId);
workspace.AddActionOnClose(window, w => InteractiveWindowProvider.CloseIfEvaluatorMatches(w, workspaceId));
} else if (!string.IsNullOrEmpty(configId)) {
window = provider.Create(configId);
} else {
var interpService = compModel.GetService<IInterpreterOptionsService>();
window = provider.Create(PythonReplEvaluatorProvider.GetEvaluatorId(interpService.DefaultInterpreter.Configuration));
}
return window;
}
public override EventHandler BeforeQueryStatus {
get {
return QueryStatusMethod;
}
}
private void QueryStatusMethod(object sender, EventArgs args) {
var oleMenu = sender as OleMenuCommand;
if (oleMenu == null) {
Debug.Fail("Unexpected command type " + sender == null ? "(null)" : sender.GetType().FullName);
return;
}
var workspace = _serviceProvider.GetWorkspace();
var pyProj = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
var textView = CommonPackage.GetActiveTextView(_serviceProvider);
oleMenu.Supported = true;
if (pyProj != null) {
// startup project, so visible in Project mode
oleMenu.Visible = true;
oleMenu.Text = Strings.ExecuteInReplCommand_ExecuteProject;
// Only enable if runnable
oleMenu.Enabled = pyProj.GetInterpreterFactory().IsRunnable();
} else if (textView != null && textView.TextBuffer.ContentType.IsOfType(PythonCoreConstants.ContentType)) {
// active file, so visible in File mode
oleMenu.Visible = true;
oleMenu.Text = Strings.ExecuteInReplCommand_ExecuteFile;
// Only enable if runnable
if (workspace != null) {
oleMenu.Enabled = workspace.CurrentFactory.IsRunnable();
} else {
var interpreterService = _serviceProvider.GetComponentModel().GetService<IInterpreterOptionsService>();
oleMenu.Enabled = interpreterService != null && interpreterService.DefaultInterpreter.IsRunnable();
}
} else {
// Python is not active, so hide the command
oleMenu.Visible = false;
oleMenu.Enabled = false;
}
}
public override void DoCommand(object sender, EventArgs e) {
DoCommand().HandleAllExceptions(_serviceProvider, GetType()).DoNotWait();
}
private async System.Threading.Tasks.Task DoCommand() {
var workspace = _serviceProvider.GetWorkspace();
var pyProj = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
var textView = CommonPackage.GetActiveTextView(_serviceProvider);
var scriptName = textView?.GetFilePath();
if (!string.IsNullOrEmpty(scriptName) && pyProj != null) {
if (pyProj.FindNodeByFullPath(scriptName) == null) {
// Starting a script that isn't in the project.
// Try and find the project. If we fail, we will
// use the default environment.
pyProj = _serviceProvider.GetProjectFromFile(scriptName);
}
}
LaunchConfiguration config = null;
try {
if (workspace != null) {
config = PythonCommonInteractiveEvaluator.GetWorkspaceLaunchConfigurationOrThrow(workspace);
} else {
config = pyProj?.GetLaunchConfigurationOrThrow();
}
} catch (MissingInterpreterException ex) {
MessageBox.Show(ex.Message, Strings.ProductTitle);
return;
}
if (config == null) {
var interpreters = _serviceProvider.GetComponentModel().GetService<IInterpreterOptionsService>();
config = new LaunchConfiguration(interpreters.DefaultInterpreter.Configuration);
} else {
config = config.Clone();
}
if (!string.IsNullOrEmpty(scriptName)) {
config.ScriptName = scriptName;
// Only overwrite the working dir for a loose file, don't do it for workspaces
if (workspace == null) {
config.WorkingDirectory = PathUtils.GetParent(scriptName);
}
}
if (config == null) {
Debug.Fail("Should not be executing command when it is invisible");
return;
}
IVsInteractiveWindow window;
try {
window = EnsureReplWindow(_serviceProvider, config.Interpreter, pyProj, workspace);
} catch (MissingInterpreterException ex) {
MessageBox.Show(ex.Message, Strings.ProductTitle);
return;
}
window.Show(true);
var eval = (IPythonInteractiveEvaluator)window.InteractiveWindow.Evaluator;
// The interpreter may take some time to startup, do this off the UI thread.
await ThreadHelper.JoinableTaskFactory.RunAsync(async () => {
await ((IInteractiveEvaluator)eval).ResetAsync();
window.InteractiveWindow.WriteLine(Strings.ExecuteInReplCommand_RunningMessage.FormatUI(config.ScriptName));
await eval.ExecuteFileAsync(config.ScriptName, config.ScriptArguments);
});
}
public override int CommandId {
get { return (int)PkgCmdIDList.cmdidExecuteFileInRepl; }
}
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using System;
using System.Collections.Generic;
using PlayFab.EconomyModels;
using PlayFab.Internal;
using PlayFab.SharedModels;
namespace PlayFab
{
/// <summary>
/// API methods for managing the catalog. Inventory manages in-game assets for any given entity.
/// </summary>
public class PlayFabEconomyInstanceAPI : IPlayFabInstanceApi
{
public readonly PlayFabApiSettings apiSettings = null;
public readonly PlayFabAuthenticationContext authenticationContext = null;
public PlayFabEconomyInstanceAPI(PlayFabAuthenticationContext context)
{
if (context == null)
throw new PlayFabException(PlayFabExceptionCode.AuthContextRequired, "Context cannot be null, create a PlayFabAuthenticationContext for each player in advance, or call <PlayFabClientInstanceAPI>.GetAuthenticationContext()");
authenticationContext = context;
}
public PlayFabEconomyInstanceAPI(PlayFabApiSettings settings, PlayFabAuthenticationContext context)
{
if (context == null)
throw new PlayFabException(PlayFabExceptionCode.AuthContextRequired, "Context cannot be null, create a PlayFabAuthenticationContext for each player in advance, or call <PlayFabClientInstanceAPI>.GetAuthenticationContext()");
apiSettings = settings;
authenticationContext = context;
}
/// <summary>
/// Verify entity login.
/// </summary>
public bool IsEntityLoggedIn()
{
return authenticationContext == null ? false : authenticationContext.IsEntityLoggedIn();
}
/// <summary>
/// Clear the Client SessionToken which allows this Client to call API calls requiring login.
/// A new/fresh login will be required after calling this.
/// </summary>
public void ForgetAllCredentials()
{
if (authenticationContext != null)
{
authenticationContext.ForgetAllCredentials();
}
}
/// <summary>
/// Creates a new item in the working catalog using provided metadata.
/// </summary>
public void CreateDraftItem(CreateDraftItemRequest request, Action<CreateDraftItemResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/CreateDraftItem", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Creates one or more upload URLs which can be used by the client to upload raw file data.
/// </summary>
public void CreateUploadUrls(CreateUploadUrlsRequest request, Action<CreateUploadUrlsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/CreateUploadUrls", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Deletes all reviews, helpfulness votes, and ratings submitted by the entity specified.
/// </summary>
public void DeleteEntityItemReviews(DeleteEntityItemReviewsRequest request, Action<DeleteEntityItemReviewsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/DeleteEntityItemReviews", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Removes an item from working catalog and all published versions from the public catalog.
/// </summary>
public void DeleteItem(DeleteItemRequest request, Action<DeleteItemResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/DeleteItem", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Gets the configuration for the catalog.
/// </summary>
public void GetCatalogConfig(GetCatalogConfigRequest request, Action<GetCatalogConfigResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetCatalogConfig", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Retrieves an item from the working catalog. This item represents the current working state of the item.
/// </summary>
public void GetDraftItem(GetDraftItemRequest request, Action<GetDraftItemResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetDraftItem", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Retrieves a paginated list of the items from the draft catalog.
/// </summary>
public void GetDraftItems(GetDraftItemsRequest request, Action<GetDraftItemsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetDraftItems", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Retrieves a paginated list of the items from the draft catalog created by the Entity.
/// </summary>
public void GetEntityDraftItems(GetEntityDraftItemsRequest request, Action<GetEntityDraftItemsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetEntityDraftItems", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Gets the submitted review for the specified item by the authenticated entity.
/// </summary>
public void GetEntityItemReview(GetEntityItemReviewRequest request, Action<GetEntityItemReviewResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetEntityItemReview", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Retrieves an item from the public catalog.
/// </summary>
public void GetItem(GetItemRequest request, Action<GetItemResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetItem", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Gets the moderation state for an item, including the concern category and string reason.
/// </summary>
public void GetItemModerationState(GetItemModerationStateRequest request, Action<GetItemModerationStateResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetItemModerationState", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Gets the status of a publish of an item.
/// </summary>
public void GetItemPublishStatus(GetItemPublishStatusRequest request, Action<GetItemPublishStatusResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetItemPublishStatus", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Get a paginated set of reviews associated with the specified item.
/// </summary>
public void GetItemReviews(GetItemReviewsRequest request, Action<GetItemReviewsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetItemReviews", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Get a summary of all reviews associated with the specified item.
/// </summary>
public void GetItemReviewSummary(GetItemReviewSummaryRequest request, Action<GetItemReviewSummaryResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetItemReviewSummary", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Retrieves items from the public catalog.
/// </summary>
public void GetItems(GetItemsRequest request, Action<GetItemsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/GetItems", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Initiates a publish of an item from the working catalog to the public catalog.
/// </summary>
public void PublishDraftItem(PublishDraftItemRequest request, Action<PublishDraftItemResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/PublishDraftItem", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Submit a report for an item, indicating in what way the item is inappropriate.
/// </summary>
public void ReportItem(ReportItemRequest request, Action<ReportItemResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/ReportItem", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Submit a report for a review
/// </summary>
public void ReportItemReview(ReportItemReviewRequest request, Action<ReportItemReviewResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/ReportItemReview", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Creates or updates a review for the specified item.
/// </summary>
public void ReviewItem(ReviewItemRequest request, Action<ReviewItemResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/ReviewItem", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Executes a search against the public catalog using the provided search parameters and returns a set of paginated
/// results.
/// </summary>
public void SearchItems(SearchItemsRequest request, Action<SearchItemsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/SearchItems", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Sets the moderation state for an item, including the concern category and string reason.
/// </summary>
public void SetItemModerationState(SetItemModerationStateRequest request, Action<SetItemModerationStateResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/SetItemModerationState", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Submit a vote for a review, indicating whether the review was helpful or unhelpful.
/// </summary>
public void SubmitItemReviewVote(SubmitItemReviewVoteRequest request, Action<SubmitItemReviewVoteResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/SubmitItemReviewVote", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Submit a request to takedown one or more reviews.
/// </summary>
public void TakedownItemReviews(TakedownItemReviewsRequest request, Action<TakedownItemReviewsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/TakedownItemReviews", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Updates the configuration for the catalog.
/// </summary>
public void UpdateCatalogConfig(UpdateCatalogConfigRequest request, Action<UpdateCatalogConfigResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/UpdateCatalogConfig", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
/// <summary>
/// Update the metadata for an item in the working catalog.
/// </summary>
public void UpdateDraftItem(UpdateDraftItemRequest request, Action<UpdateDraftItemResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
var context = (request == null ? null : request.AuthenticationContext) ?? authenticationContext;
var callSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method");
PlayFabHttp.MakeApiCall("/Catalog/UpdateDraftItem", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings, this);
}
}
}
#endif
| |
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudioTools.Project {
internal enum tagDVASPECT {
DVASPECT_CONTENT = 1,
DVASPECT_THUMBNAIL = 2,
DVASPECT_ICON = 4,
DVASPECT_DOCPRINT = 8
}
internal enum tagTYMED {
TYMED_HGLOBAL = 1,
TYMED_FILE = 2,
TYMED_ISTREAM = 4,
TYMED_ISTORAGE = 8,
TYMED_GDI = 16,
TYMED_MFPICT = 32,
TYMED_ENHMF = 64,
TYMED_NULL = 0
}
internal sealed class DataCacheEntry : IDisposable {
#region fields
/// <summary>
/// Defines an object that will be a mutex for this object for synchronizing thread calls.
/// </summary>
private static volatile object Mutex = new object();
private FORMATETC format;
private long data;
private DATADIR dataDir;
private bool isDisposed;
#endregion
#region properties
internal FORMATETC Format {
get {
return this.format;
}
}
internal long Data {
get {
return this.data;
}
}
internal DATADIR DataDir {
get {
return this.dataDir;
}
}
#endregion
/// <summary>
/// The IntPtr is data allocated that should be removed. It is allocated by the ProcessSelectionData method.
/// </summary>
internal DataCacheEntry(FORMATETC fmt, IntPtr data, DATADIR dir) {
this.format = fmt;
this.data = (long)data;
this.dataDir = dir;
}
#region Dispose
~DataCacheEntry() {
Dispose(false);
}
/// <summary>
/// The IDispose interface Dispose method for disposing the object determinastically.
/// </summary>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// The method that does the cleanup.
/// </summary>
/// <param name="disposing"></param>
private void Dispose(bool disposing) {
// Everybody can go here.
if (!this.isDisposed) {
// Synchronize calls to the Dispose simulteniously.
lock (Mutex) {
if (disposing && this.data != 0) {
Marshal.FreeHGlobal((IntPtr)this.data);
this.data = 0;
}
this.isDisposed = true;
}
}
}
#endregion
}
/// <summary>
/// Unfortunately System.Windows.Forms.IDataObject and
/// Microsoft.VisualStudio.OLE.Interop.IDataObject are different...
/// </summary>
internal sealed class DataObject : IDataObject {
#region fields
internal const int DATA_S_SAMEFORMATETC = 0x00040130;
EventSinkCollection map;
ArrayList entries;
#endregion
internal DataObject() {
this.map = new EventSinkCollection();
this.entries = new ArrayList();
}
internal void SetData(FORMATETC format, IntPtr data) {
this.entries.Add(new DataCacheEntry(format, data, DATADIR.DATADIR_SET));
}
#region IDataObject methods
int IDataObject.DAdvise(FORMATETC[] e, uint adv, IAdviseSink sink, out uint cookie) {
Utilities.ArgumentNotNull("e", e);
STATDATA sdata = new STATDATA();
sdata.ADVF = adv;
sdata.FORMATETC = e[0];
sdata.pAdvSink = sink;
cookie = this.map.Add(sdata);
sdata.dwConnection = cookie;
return 0;
}
void IDataObject.DUnadvise(uint cookie) {
this.map.RemoveAt(cookie);
}
int IDataObject.EnumDAdvise(out IEnumSTATDATA e) {
e = new EnumSTATDATA((IEnumerable)this.map);
return 0; //??
}
int IDataObject.EnumFormatEtc(uint direction, out IEnumFORMATETC penum) {
penum = new EnumFORMATETC((DATADIR)direction, (IEnumerable)this.entries);
return 0;
}
int IDataObject.GetCanonicalFormatEtc(FORMATETC[] format, FORMATETC[] fmt) {
throw new System.Runtime.InteropServices.COMException("", DATA_S_SAMEFORMATETC);
}
void IDataObject.GetData(FORMATETC[] fmt, STGMEDIUM[] m) {
STGMEDIUM retMedium = new STGMEDIUM();
if (fmt == null || fmt.Length < 1)
return;
foreach (DataCacheEntry e in this.entries) {
if (e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/) {
retMedium.tymed = e.Format.tymed;
// Caller must delete the memory.
retMedium.unionmember = DragDropHelper.CopyHGlobal(new IntPtr(e.Data));
break;
}
}
if (m != null && m.Length > 0)
m[0] = retMedium;
}
void IDataObject.GetDataHere(FORMATETC[] fmt, STGMEDIUM[] m) {
}
int IDataObject.QueryGetData(FORMATETC[] fmt) {
if (fmt == null || fmt.Length < 1)
return VSConstants.S_FALSE;
foreach (DataCacheEntry e in this.entries) {
if (e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/)
return VSConstants.S_OK;
}
return VSConstants.S_FALSE;
}
void IDataObject.SetData(FORMATETC[] fmt, STGMEDIUM[] m, int fRelease) {
}
#endregion
}
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
internal static class DragDropHelper {
#pragma warning disable 414
internal static readonly ushort CF_VSREFPROJECTITEMS;
internal static readonly ushort CF_VSSTGPROJECTITEMS;
internal static readonly ushort CF_VSPROJECTCLIPDESCRIPTOR;
#pragma warning restore 414
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static DragDropHelper() {
CF_VSREFPROJECTITEMS = (ushort)UnsafeNativeMethods.RegisterClipboardFormat("CF_VSREFPROJECTITEMS");
CF_VSSTGPROJECTITEMS = (ushort)UnsafeNativeMethods.RegisterClipboardFormat("CF_VSSTGPROJECTITEMS");
CF_VSPROJECTCLIPDESCRIPTOR = (ushort)UnsafeNativeMethods.RegisterClipboardFormat("CF_PROJECTCLIPBOARDDESCRIPTOR");
}
public static FORMATETC CreateFormatEtc(ushort iFormat) {
FORMATETC fmt = new FORMATETC();
fmt.cfFormat = iFormat;
fmt.ptd = IntPtr.Zero;
fmt.dwAspect = (uint)DVASPECT.DVASPECT_CONTENT;
fmt.lindex = -1;
fmt.tymed = (uint)TYMED.TYMED_HGLOBAL;
return fmt;
}
public static int QueryGetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc) {
FORMATETC[] af = new FORMATETC[1];
af[0] = fmtetc;
int result = pDataObject.QueryGetData(af);
if (result == VSConstants.S_OK) {
fmtetc = af[0];
return VSConstants.S_OK;
}
return result;
}
public static STGMEDIUM GetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc) {
FORMATETC[] af = new FORMATETC[1];
af[0] = fmtetc;
STGMEDIUM[] sm = new STGMEDIUM[1];
pDataObject.GetData(af, sm);
fmtetc = af[0];
return sm[0];
}
/// <summary>
/// Retrieves data from a VS format.
/// </summary>
public static List<string> GetDroppedFiles(ushort format, Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject, out DropDataType ddt) {
ddt = DropDataType.None;
List<string> droppedFiles = new List<string>();
// try HDROP
FORMATETC fmtetc = CreateFormatEtc(format);
if (QueryGetData(dataObject, ref fmtetc) == VSConstants.S_OK) {
STGMEDIUM stgmedium = DragDropHelper.GetData(dataObject, ref fmtetc);
if (stgmedium.tymed == (uint)TYMED.TYMED_HGLOBAL) {
// We are releasing the cloned hglobal here.
IntPtr dropInfoHandle = stgmedium.unionmember;
if (dropInfoHandle != IntPtr.Zero) {
ddt = DropDataType.Shell;
try {
uint numFiles = UnsafeNativeMethods.DragQueryFile(dropInfoHandle, 0xFFFFFFFF, null, 0);
// We are a directory based project thus a projref string is placed on the clipboard.
// We assign the maximum length of a projref string.
// The format of a projref is : <Proj Guid>|<project rel path>|<file path>
uint lenght = (uint)Guid.Empty.ToString().Length + 2 * NativeMethods.MAX_PATH + 2;
char[] moniker = new char[lenght + 1];
for (uint fileIndex = 0; fileIndex < numFiles; fileIndex++) {
uint queryFileLength = UnsafeNativeMethods.DragQueryFile(dropInfoHandle, fileIndex, moniker, lenght);
string filename = new String(moniker, 0, (int)queryFileLength);
droppedFiles.Add(filename);
}
} finally {
Marshal.FreeHGlobal(dropInfoHandle);
}
}
}
}
return droppedFiles;
}
public static string GetSourceProjectPath(Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject) {
string projectPath = null;
FORMATETC fmtetc = CreateFormatEtc(CF_VSPROJECTCLIPDESCRIPTOR);
if (QueryGetData(dataObject, ref fmtetc) == VSConstants.S_OK) {
STGMEDIUM stgmedium = DragDropHelper.GetData(dataObject, ref fmtetc);
if (stgmedium.tymed == (uint)TYMED.TYMED_HGLOBAL) {
// We are releasing the cloned hglobal here.
IntPtr dropInfoHandle = stgmedium.unionmember;
if (dropInfoHandle != IntPtr.Zero) {
try {
string path = GetData(dropInfoHandle);
// Clone the path that we can release our memory.
if (!String.IsNullOrEmpty(path)) {
projectPath = String.Copy(path);
}
} finally {
Marshal.FreeHGlobal(dropInfoHandle);
}
}
}
}
return projectPath;
}
/// <summary>
/// Returns the data packed after the DROPFILES structure.
/// </summary>
/// <param name="dropHandle"></param>
/// <returns></returns>
internal static string GetData(IntPtr dropHandle) {
IntPtr data = UnsafeNativeMethods.GlobalLock(dropHandle);
try {
_DROPFILES df = (_DROPFILES)Marshal.PtrToStructure(data, typeof(_DROPFILES));
if (df.fWide != 0) {
IntPtr pdata = new IntPtr((long)data + df.pFiles);
return Marshal.PtrToStringUni(pdata);
}
} finally {
if (data != IntPtr.Zero) {
UnsafeNativeMethods.GlobalUnLock(data);
}
}
return null;
}
internal static IntPtr CopyHGlobal(IntPtr data) {
IntPtr src = UnsafeNativeMethods.GlobalLock(data);
var size = UnsafeNativeMethods.GlobalSize(data).ToInt32();
IntPtr ptr = Marshal.AllocHGlobal(size);
IntPtr buffer = UnsafeNativeMethods.GlobalLock(ptr);
try {
for (int i = 0; i < size; i++) {
byte val = Marshal.ReadByte(new IntPtr((long)src + i));
Marshal.WriteByte(new IntPtr((long)buffer + i), val);
}
} finally {
if (buffer != IntPtr.Zero) {
UnsafeNativeMethods.GlobalUnLock(buffer);
}
if (src != IntPtr.Zero) {
UnsafeNativeMethods.GlobalUnLock(src);
}
}
return ptr;
}
internal static void CopyStringToHGlobal(string s, IntPtr data, int bufferSize) {
Int16 nullTerminator = 0;
int dwSize = Marshal.SizeOf(nullTerminator);
if ((s.Length + 1) * Marshal.SizeOf(s[0]) > bufferSize)
throw new System.IO.InternalBufferOverflowException();
// IntPtr memory already locked...
for (int i = 0, len = s.Length; i < len; i++) {
Marshal.WriteInt16(data, i * dwSize, s[i]);
}
// NULL terminate it
Marshal.WriteInt16(new IntPtr((long)data + (s.Length * dwSize)), nullTerminator);
}
} // end of dragdrophelper
internal class EnumSTATDATA : IEnumSTATDATA {
IEnumerable i;
IEnumerator e;
public EnumSTATDATA(IEnumerable i) {
this.i = i;
this.e = i.GetEnumerator();
}
void IEnumSTATDATA.Clone(out IEnumSTATDATA clone) {
clone = new EnumSTATDATA(i);
}
int IEnumSTATDATA.Next(uint celt, STATDATA[] d, out uint fetched) {
uint rc = 0;
//uint size = (fetched != null) ? fetched[0] : 0;
for (uint i = 0; i < celt; i++) {
if (e.MoveNext()) {
STATDATA sdata = (STATDATA)e.Current;
rc++;
if (d != null && d.Length > i) {
d[i] = sdata;
}
}
}
fetched = rc;
return 0;
}
int IEnumSTATDATA.Reset() {
e.Reset();
return 0;
}
int IEnumSTATDATA.Skip(uint celt) {
for (uint i = 0; i < celt; i++) {
e.MoveNext();
}
return 0;
}
}
internal class EnumFORMATETC : IEnumFORMATETC {
IEnumerable cache; // of DataCacheEntrys.
DATADIR dir;
IEnumerator e;
public EnumFORMATETC(DATADIR dir, IEnumerable cache) {
this.cache = cache;
this.dir = dir;
e = cache.GetEnumerator();
}
void IEnumFORMATETC.Clone(out IEnumFORMATETC clone) {
clone = new EnumFORMATETC(dir, cache);
}
int IEnumFORMATETC.Next(uint celt, FORMATETC[] d, uint[] fetched) {
uint rc = 0;
//uint size = (fetched != null) ? fetched[0] : 0;
for (uint i = 0; i < celt; i++) {
if (e.MoveNext()) {
DataCacheEntry entry = (DataCacheEntry)e.Current;
rc++;
if (d != null && d.Length > i) {
d[i] = entry.Format;
}
} else {
return VSConstants.S_FALSE;
}
}
if (fetched != null && fetched.Length > 0)
fetched[0] = rc;
return VSConstants.S_OK;
}
int IEnumFORMATETC.Reset() {
e.Reset();
return 0;
}
int IEnumFORMATETC.Skip(uint celt) {
for (uint i = 0; i < celt; i++) {
e.MoveNext();
}
return 0;
}
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mysb.Models.Shared;
using Mysb.DataAccess;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Extensions.Options;
using System.Linq;
using System.IO;
using Microsoft.Extensions.Logging;
using Moq;
using Mysb.Models.Options;
namespace MysbTest
{
[TestClass]
public class FirmwareDAOTest
{
[TestMethod]
public async Task FirmwareConfigAsyncTest()
{
var tests = new[]
{
new
{
Payload = "010001005000D446",
Node = new NodeFirmwareInfoMapping { NodeId = string.Empty, Type = 1, Version = 1},
Expected = "010001005000D446"
}
};
foreach (var test in tests)
{
var logger = new Mock<ILogger<ExposedFirmwareDAO>>().Object;
var opts = Options.Create(new SharedOpts
{
Resources = new List<NodeFirmwareInfoMapping> { test.Node },
FirmwareBasePath = Const.TestFilesBasePath,
});
var dao = new ExposedFirmwareDAO(logger, opts);
var actual = await dao.FirmwareConfigAsync(string.Empty, test.Payload);
Assert.AreEqual(test.Expected, actual);
}
}
[TestMethod]
public async Task FirmwareAsyncTest()
{
var tests = new[]
{
new
{
Payload = "010001000100",
Node = new NodeFirmwareInfoMapping { NodeId = string.Empty, Type = 1, Version = 1},
Expected = "0100010001000C946E000C946E000C946E000C946E00"
},
new
{
Payload = "0B0001000100",
Node = new NodeFirmwareInfoMapping { NodeId = string.Empty, Type = 11, Version = 1},
Expected = "0B000100010052C1000050C10000EEC200004CC10000"
}
};
foreach (var test in tests)
{
var logger = new Mock<ILogger<ExposedFirmwareDAO>>().Object;
var opts = Options.Create(new SharedOpts
{
Resources = new List<NodeFirmwareInfoMapping> { test.Node },
FirmwareBasePath = Const.TestFilesBasePath,
});
var dao = new ExposedFirmwareDAO(logger, opts);
var actual = await dao.FirmwareAsync(string.Empty, test.Payload);
Assert.AreEqual(test.Expected, actual);
}
}
[TestMethod]
public async Task LoadFromFileAsyncTest()
{
var tests = new[]
{
new
{
Path = $"{Const.TestFilesBasePath}/1/1/firmware.hex",
ExpectedBlocks = 80,
ExpectedCrc = 18132
},
new
{
Path = $"{Const.TestFilesBasePath}/11/1/firmware.hex",
ExpectedBlocks = 1072,
ExpectedCrc = 64648
}
};
foreach (var test in tests)
{
var logger = new Mock<ILogger<ExposedFirmwareDAO>>().Object;
var opts = Options.Create(new SharedOpts
{
FirmwareBasePath = Const.TestFilesBasePath,
});
var dao = new ExposedFirmwareDAO(logger, opts);
var firmware = await dao.LoadFromFileTestAsync(test.Path);
Assert.AreEqual(test.ExpectedBlocks, firmware.Blocks);
Assert.AreEqual(test.ExpectedCrc, firmware.Crc);
}
}
[TestMethod]
public async Task LoadFromFileContentAsyncTest()
{
var tests = new[]
{
new { Type = 1, Blocks = 80, Path = $"{Const.TestFilesBasePath}/1/1/firmware.encoded" },
new { Type = 11, Blocks = 1072, Path = $"{Const.TestFilesBasePath}/11/1/firmware.encoded" }
};
foreach (var test in tests)
{
var logger = new Mock<ILogger<ExposedFirmwareDAO>>().Object;
var opts = Options.Create(new SharedOpts
{
FirmwareBasePath = Const.TestFilesBasePath,
});
var dao = new ExposedFirmwareDAO(logger, opts);
var lines = await File.ReadAllLinesAsync(test.Path);
foreach (var blockNo in Enumerable.Range(0, test.Blocks))
{
var lineNo = test.Blocks - blockNo - 1;
var payload = dao.PackTest(new FirmwareReqResp
{
Type = (ushort)test.Type,
Version = 1,
Block = (ushort)blockNo,
});
var actual = await dao.FirmwareAsync(string.Empty, payload);
var expected = lines[lineNo];
Assert.AreEqual(expected, actual, $"Type: {test.Type}, Line: {lineNo}, Block: {blockNo}");
}
}
}
[TestMethod]
public void BootloaderTest()
{
var tests = new[]
{
new
{
Description = "Erase EEPROM",
Topic = "mysensors/bootloader/1/1",
Payload = "",
Expected = "0100000000007ADA"
},
new
{
Description = "Set NodeID",
Topic = "mysensors/bootloader/2/2",
Payload = "9",
Expected = "0200090000007ADA"
},
new
{
Description = "Set ParentID",
Topic = "mysensors/bootloader/3/3",
Payload = "11",
Expected = "03000B0000007ADA"
},
};
foreach (var test in tests)
{
var logger = new Mock<ILogger<ExposedFirmwareDAO>>().Object;
var opts = Options.Create(new SharedOpts
{
FirmwareBasePath = Const.TestFilesBasePath,
});
var dao = new ExposedFirmwareDAO(logger, opts);
var (_, actual) = dao.BootloaderCommand(test.Topic, test.Payload);
Assert.AreEqual(test.Expected, actual, test.Description);
}
}
}
public class ExposedFirmwareDAO : FirmwareDAO
{
public ExposedFirmwareDAO(ILogger<ExposedFirmwareDAO> logger, IOptions<SharedOpts> sharedOpts) :
base(logger, sharedOpts.Value.FirmwareBasePath, sharedOpts.Value.Resources)
{
}
public Task<Firmware> LoadFromFileTestAsync(string path, CancellationToken cancellationToken = default) =>
this.LoadFromFileAsync(path, cancellationToken);
public string PackTest<T>(T obj) where T : struct => this.Pack(obj);
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
// ForestEditorGui Script Methods
function ForestEditorGui::setActiveTool( %this, %tool )
{
if ( %tool == ForestTools->BrushTool )
ForestEditTabBook.selectPage(0);
Parent::setActiveTool( %this, %tool );
}
/// This is called by the editor when the active forest has
/// changed giving us a chance to update the GUI.
function ForestEditorGui::onActiveForestUpdated( %this, %forest, %createNew )
{
%gotForest = isObject( %forest );
// Give the user a chance to add a forest.
if ( !%gotForest && %createNew )
{
MessageBoxYesNo( "Forest",
"There is not a Forest in this mission. Do you want to add one?",
%this @ ".createForest();", "" );
return;
}
}
/// Called from a message box when a forest is not found.
function ForestEditorGui::createForest( %this )
{
%forestObject = parseMissionGroupForIds("Forest", "");
if ( isObject( %forestObject ) )
{
error( "Cannot create a second 'theForest' Forest!" );
return;
}
// Allocate the Forest and make it undoable.
new Forest( theForest )
{
dataFile = "";
parentGroup = "MissionGroup";
};
MECreateUndoAction::submit( theForest );
ForestEditorGui.setActiveForest( theForest );
//Re-initialize the editor settings so we can start using it immediately.
%tool = ForestEditorGui.getActiveTool();
if ( isObject( %tool ) )
%tool.onActivated();
if ( %tool == ForestTools->SelectionTool )
{
%mode = GlobalGizmoProfile.mode;
switch$ (%mode)
{
case "None":
ForestEditorSelectModeBtn.performClick();
case "Move":
ForestEditorMoveModeBtn.performClick();
case "Rotate":
ForestEditorRotateModeBtn.performClick();
case "Scale":
ForestEditorScaleModeBtn.performClick();
}
}
else if ( %tool == ForestTools->BrushTool )
{
%mode = ForestTools->BrushTool.mode;
switch$ (%mode)
{
case "Paint":
ForestEditorPaintModeBtn.performClick();
case "Erase":
ForestEditorEraseModeBtn.performClick();
case "EraseSelected":
ForestEditorEraseSelectedModeBtn.performClick();
}
}
EWorldEditor.isDirty = true;
}
function ForestEditorGui::newBrush( %this )
{
%internalName = getUniqueInternalName( "Brush", ForestBrushGroup, true );
%brush = new ForestBrush()
{
internalName = %internalName;
parentGroup = ForestBrushGroup;
};
MECreateUndoAction::submit( %brush );
ForestEditBrushTree.open( ForestBrushGroup );
ForestEditBrushTree.buildVisibleTree(true);
%item = ForestEditBrushTree.findItemByObjectId( %brush );
ForestEditBrushTree.clearSelection();
ForestEditBrushTree.addSelection( %item );
ForestEditBrushTree.scrollVisible( %item );
ForestEditorPlugin.dirty = true;
}
function ForestEditorGui::newElement( %this )
{
%sel = ForestEditBrushTree.getSelectedObject();
if ( !isObject( %sel ) )
%parentGroup = ForestBrushGroup;
else
{
if ( %sel.getClassName() $= "ForestBrushElement" )
%parentGroup = %sel.parentGroup;
else
%parentGroup = %sel;
}
%internalName = getUniqueInternalName( "Element", ForestBrushGroup, true );
%element = new ForestBrushElement()
{
internalName = %internalName;
parentGroup = %parentGroup;
};
MECreateUndoAction::submit( %element );
ForestEditBrushTree.clearSelection();
ForestEditBrushTree.buildVisibleTree( true );
%item = ForestEditBrushTree.findItemByObjectId( %element.getId() );
ForestEditBrushTree.scrollVisible( %item );
ForestEditBrushTree.addSelection( %item );
ForestEditorPlugin.dirty = true;
}
function ForestEditorGui::deleteBrushOrElement( %this )
{
ForestEditBrushTree.deleteSelection();
ForestEditorPlugin.dirty = true;
}
function ForestEditorGui::newMesh( %this )
{
%spec = "All Mesh Files|*.dts;*.dae|DTS|*.dts|DAE|*.dae";
%dlg = new OpenFileDialog()
{
Filters = %spec;
DefaultPath = $Pref::WorldEditor::LastPath;
DefaultFile = "";
ChangePath = true;
};
%ret = %dlg.Execute();
if ( %ret )
{
$Pref::WorldEditor::LastPath = filePath( %dlg.FileName );
%fullPath = makeRelativePath( %dlg.FileName, getMainDotCSDir() );
%file = fileBase( %fullPath );
}
%dlg.delete();
if ( !%ret )
return;
%name = getUniqueName( %file );
%str = "datablock TSForestItemData( " @ %name @ " ) { shapeFile = \"" @ %fullPath @ "\"; };";
eval( %str );
if ( isObject( %name ) )
{
ForestEditMeshTree.clearSelection();
ForestEditMeshTree.buildVisibleTree( true );
%item = ForestEditMeshTree.findItemByObjectId( %name.getId() );
ForestEditMeshTree.scrollVisible( %item );
ForestEditMeshTree.addSelection( %item );
ForestDataManager.setDirty( %name, "art/forest/managedItemData.cs" );
%element = new ForestBrushElement()
{
internalName = %name;
forestItemData = %name;
parentGroup = ForestBrushGroup;
};
ForestEditBrushTree.clearSelection();
ForestEditBrushTree.buildVisibleTree( true );
%item = ForestEditBrushTree.findItemByObjectId( %element.getId() );
ForestEditBrushTree.scrollVisible( %item );
ForestEditBrushTree.addSelection( %item );
pushInstantGroup();
%action = new MECreateUndoAction()
{
actionName = "Create TSForestItemData";
};
popInstantGroup();
%action.addObject( %name );
%action.addObject( %element );
%action.addToManager( Editor.getUndoManager() );
ForestEditorPlugin.dirty = true;
}
}
function ForestEditorGui::deleteMesh( %this )
{
%obj = ForestEditMeshTree.getSelectedObject();
// Can't delete itemData's that are in use without
// crashing at the moment...
if ( isObject( %obj ) )
{
MessageBoxOKCancel( "Warning",
"Deleting this mesh will also delete BrushesElements and ForestItems referencing it.",
"ForestEditorGui.okDeleteMesh(" @ %obj @ ");",
"" );
}
}
function ForestEditorGui::okDeleteMesh( %this, %mesh )
{
// Remove mesh from file
ForestDataManager.removeObjectFromFile( %mesh, "art/forest/managedItemData.cs" );
// Submitting undo actions is handled in code.
%this.deleteMeshSafe( %mesh );
// Update TreeViews.
ForestEditBrushTree.buildVisibleTree( true );
ForestEditMeshTree.buildVisibleTree( true );
ForestEditorPlugin.dirty = true;
}
function ForestEditorGui::validateBrushSize( %this )
{
%minBrushSize = 1;
%maxBrushSize = getWord(ETerrainEditor.maxBrushSize, 0);
%val = $ThisControl.getText();
if(%val < %minBrushSize)
$ThisControl.setValue(%minBrushSize);
else if(%val > %maxBrushSize)
$ThisControl.setValue(%maxBrushSize);
}
// Child-control Script Methods
function ForestEditMeshTree::onSelect( %this, %obj )
{
ForestEditorInspector.inspect( %obj );
}
function ForestEditBrushTree::onRemoveSelection( %this, %obj )
{
%this.buildVisibleTree( true );
ForestTools->BrushTool.collectElements();
if ( %this.getSelectedItemsCount() == 1 )
ForestEditorInspector.inspect( %obj );
else
ForestEditorInspector.inspect( "" );
}
function ForestEditBrushTree::onAddSelection( %this, %obj )
{
%this.buildVisibleTree( true );
ForestTools->BrushTool.collectElements();
if ( %this.getSelectedItemsCount() == 1 )
ForestEditorInspector.inspect( %obj );
else
ForestEditorInspector.inspect( "" );
}
function ForestEditTabBook::onTabSelected( %this, %text, %idx )
{
%bbg = ForestEditorPalleteWindow.findObjectByInternalName("BrushButtonGroup");
%mbg = ForestEditorPalleteWindow.findObjectByInternalName("MeshButtonGroup");
%bbg.setVisible( false );
%mbg.setVisible( false );
if ( %text $= "Brushes" )
{
%bbg.setVisible( true );
%obj = ForestEditBrushTree.getSelectedObject();
ForestEditorInspector.inspect( %obj );
}
else if ( %text $= "Meshes" )
{
%mbg.setVisible( true );
%obj = ForestEditMeshTree.getSelectedObject();
ForestEditorInspector.inspect( %obj );
}
}
function ForestEditBrushTree::onDeleteSelection( %this )
{
%list = ForestEditBrushTree.getSelectedObjectList();
MEDeleteUndoAction::submit( %list, true );
ForestEditorPlugin.dirty = true;
}
function ForestEditBrushTree::onDragDropped( %this )
{
ForestEditorPlugin.dirty = true;
}
function ForestEditMeshTree::onDragDropped( %this )
{
ForestEditorPlugin.dirty = true;
}
function ForestEditMeshTree::onDeleteObject( %this, %obj )
{
// return true - skip delete.
return true;
}
function ForestEditMeshTree::onDoubleClick( %this )
{
%obj = %this.getSelectedObject();
%name = getUniqueInternalName( %obj.getName(), ForestBrushGroup, true );
%element = new ForestBrushElement()
{
internalName = %name;
forestItemData = %obj.getName();
parentGroup = ForestBrushGroup;
};
//ForestDataManager.setDirty( %element, "art/forest/brushes.cs" );
ForestEditBrushTree.clearSelection();
ForestEditBrushTree.buildVisibleTree( true );
%item = ForestEditBrushTree.findItemByObjectId( %element );
ForestEditBrushTree.scrollVisible( %item );
ForestEditBrushTree.addSelection( %item );
ForestEditorPlugin.dirty = true;
}
function ForestEditBrushTree::handleRenameObject( %this, %name, %obj )
{
if ( %name !$= "" )
{
%found = ForestBrushGroup.findObjectByInternalName( %name );
if ( isObject( %found ) && %found.getId() != %obj.getId() )
{
MessageBoxOK( "Error", "Brush or Element with that name already exists.", "" );
// true as in, we handled it, don't rename the object.
return true;
}
}
// Since we aren't showing any groups whens inspecting a ForestBrushGroup
// we can't push this event off to the inspector to handle.
//return GuiTreeViewCtrl::handleRenameObject( %this, %name, %obj );
// The instant group will try to add our
// UndoAction if we don't disable it.
pushInstantGroup();
%nameOrClass = %obj.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %obj.getClassname();
%action = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ "internalName" @ " Change";
objectId = %obj.getId();
fieldName = "internalName";
fieldValue = %obj.internalName;
arrayIndex = 0;
inspectorGui = "";
};
// Restore the instant group.
popInstantGroup();
%action.addToManager( Editor.getUndoManager() );
EWorldEditor.isDirty = true;
return false;
}
function ForestEditorInspector::inspect( %this, %obj )
{
if ( isObject( %obj ) )
%class = %obj.getClassName();
%this.showObjectName = false;
%this.showCustomFields = false;
switch$ ( %class )
{
case "ForestBrush":
%this.groupFilters = "+NOTHING,-Ungrouped";
case "ForestBrushElement":
%this.groupFilters = "+ForestBrushElement,-Ungrouped";
case "TSForestItemData":
%this.groupFilters = "+Media,+Wind";
default:
%this.groupFilters = "";
}
Parent::inspect( %this, %obj );
}
function ForestEditorInspector::onInspectorFieldModified( %this, %object, %fieldName, %oldValue, %newValue )
{
// The instant group will try to add our
// UndoAction if we don't disable it.
%instantGroup = $InstantGroup;
$InstantGroup = 0;
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%action = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %oldValue;
inspectorGui = %this;
};
// Restore the instant group.
$InstantGroup = %instantGroup;
%action.addToManager( Editor.getUndoManager() );
if ( %object.getClassName() $= "TSForestItemData" )
ForestDataManager.setDirty( %object );
ForestEditorPlugin.dirty = true;
}
function ForestEditorInspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc )
{
//FieldInfoControl.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc );
}
function ForestBrushSizeSliderCtrlContainer::onWake(%this)
{
%this-->slider.range = "1" SPC getWord(ETerrainEditor.maxBrushSize, 0);
%this-->slider.setValue(ForestBrushSizeTextEditContainer-->textEdit.getValue());
}
| |
// 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.Globalization;
using System.IO;
using System.Security;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using Internal.Win32;
using REG_TZI_FORMAT = Interop.Kernel32.REG_TZI_FORMAT;
using TIME_ZONE_INFORMATION = Interop.Kernel32.TIME_ZONE_INFORMATION;
using TIME_DYNAMIC_ZONE_INFORMATION = Interop.Kernel32.TIME_DYNAMIC_ZONE_INFORMATION;
namespace System
{
public sealed partial class TimeZoneInfo
{
// registry constants for the 'Time Zones' hive
//
private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";
private const string DisplayValue = "Display";
private const string DaylightValue = "Dlt";
private const string StandardValue = "Std";
private const string MuiDisplayValue = "MUI_Display";
private const string MuiDaylightValue = "MUI_Dlt";
private const string MuiStandardValue = "MUI_Std";
private const string TimeZoneInfoValue = "TZI";
private const string FirstEntryValue = "FirstEntry";
private const string LastEntryValue = "LastEntry";
private const int MaxKeyLength = 255;
private sealed partial class CachedData
{
private static TimeZoneInfo GetCurrentOneYearLocal()
{
// load the data from the OS
TIME_ZONE_INFORMATION timeZoneInformation;
uint result = Interop.Kernel32.GetTimeZoneInformation(out timeZoneInformation);
return result == Interop.Kernel32.TIME_ZONE_ID_INVALID ?
CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) :
GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false);
}
private volatile OffsetAndRule? _oneYearLocalFromUtc;
public OffsetAndRule GetOneYearLocalFromUtc(int year)
{
OffsetAndRule? oneYearLocFromUtc = _oneYearLocalFromUtc;
if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year)
{
TimeZoneInfo currentYear = GetCurrentOneYearLocal();
AdjustmentRule? rule = currentYear._adjustmentRules?[0];
oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);
_oneYearLocalFromUtc = oneYearLocFromUtc;
}
return oneYearLocFromUtc;
}
}
private sealed class OffsetAndRule
{
public readonly int Year;
public readonly TimeSpan Offset;
public readonly AdjustmentRule? Rule;
public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule? rule)
{
Year = year;
Offset = offset;
Rule = rule;
}
}
/// <summary>
/// Returns a cloned array of AdjustmentRule objects
/// </summary>
public AdjustmentRule[] GetAdjustmentRules()
{
if (_adjustmentRules == null)
{
return Array.Empty<AdjustmentRule>();
}
return (AdjustmentRule[])_adjustmentRules.Clone();
}
private static void PopulateAllSystemTimeZones(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
using (RegistryKey? reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
{
if (reg != null)
{
foreach (string keyName in reg.GetSubKeyNames())
{
TryGetTimeZone(keyName, false, out _, out _, cachedData); // populate the cache
}
}
}
}
private TimeZoneInfo(in TIME_ZONE_INFORMATION zone, bool dstDisabled)
{
string standardName = zone.GetStandardName();
if (standardName.Length == 0)
{
_id = LocalId; // the ID must contain at least 1 character - initialize _id to "Local"
}
else
{
_id = standardName;
}
_baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0);
if (!dstDisabled)
{
// only create the adjustment rule if DST is enabled
REG_TZI_FORMAT regZone = new REG_TZI_FORMAT(zone);
AdjustmentRule? rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias);
if (rule != null)
{
_adjustmentRules = new[] { rule };
}
}
ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
_displayName = standardName;
_standardDisplayName = standardName;
_daylightDisplayName = zone.GetDaylightName();
}
/// <summary>
/// Helper function to check if the current TimeZoneInformation struct does not support DST.
/// This check returns true when the DaylightDate == StandardDate.
/// This check is only meant to be used for "Local".
/// </summary>
private static bool CheckDaylightSavingTimeNotSupported(in TIME_ZONE_INFORMATION timeZone) =>
timeZone.DaylightDate.Equals(timeZone.StandardDate);
/// <summary>
/// Converts a REG_TZI_FORMAT struct to an AdjustmentRule.
/// </summary>
private static AdjustmentRule? CreateAdjustmentRuleFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset)
{
bool supportsDst = timeZoneInformation.StandardDate.Month != 0;
if (!supportsDst)
{
if (timeZoneInformation.Bias == defaultBaseUtcOffset)
{
// this rule will not contain any information to be used to adjust dates. just ignore it
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startDate,
endDate,
TimeSpan.Zero, // no daylight saving transition
TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),
TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),
new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule
noDaylightTransitions: false);
}
//
// Create an AdjustmentRule with TransitionTime objects
//
TransitionTime daylightTransitionStart;
if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true))
{
return null;
}
TransitionTime daylightTransitionEnd;
if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false))
{
return null;
}
if (daylightTransitionStart.Equals(daylightTransitionEnd))
{
// this happens when the time zone does support DST but the OS has DST disabled
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startDate,
endDate,
new TimeSpan(0, -timeZoneInformation.DaylightBias, 0),
daylightTransitionStart,
daylightTransitionEnd,
new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),
noDaylightTransitions: false);
}
/// <summary>
/// Helper function that searches the registry for a time zone entry
/// that matches the TimeZoneInformation struct.
/// </summary>
private static string? FindIdFromTimeZoneInformation(in TIME_ZONE_INFORMATION timeZone, out bool dstDisabled)
{
dstDisabled = false;
using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
{
if (key == null)
{
return null;
}
foreach (string keyName in key.GetSubKeyNames())
{
if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))
{
return keyName;
}
}
}
return null;
}
/// <summary>
/// Helper function for retrieving the local system time zone.
/// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
/// Assumes cachedData lock is taken.
/// </summary>
/// <returns>A new TimeZoneInfo instance.</returns>
private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
//
// Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"
//
TIME_DYNAMIC_ZONE_INFORMATION dynamicTimeZoneInformation;
// call kernel32!GetDynamicTimeZoneInformation...
uint result = Interop.Kernel32.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);
if (result == Interop.Kernel32.TIME_ZONE_ID_INVALID)
{
// return a dummy entry
return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
}
// check to see if we can use the key name returned from the API call
string dynamicTimeZoneKeyName = dynamicTimeZoneInformation.GetTimeZoneKeyName();
if (dynamicTimeZoneKeyName.Length != 0)
{
if (TryGetTimeZone(dynamicTimeZoneKeyName, dynamicTimeZoneInformation.DynamicDaylightTimeDisabled != 0, out TimeZoneInfo? zone, out _, cachedData) == TimeZoneInfoResult.Success)
{
// successfully loaded the time zone from the registry
return zone!;
}
}
var timeZoneInformation = new TIME_ZONE_INFORMATION(dynamicTimeZoneInformation);
// the key name was not returned or it pointed to a bogus entry - search for the entry ourselves
string? id = FindIdFromTimeZoneInformation(timeZoneInformation, out bool dstDisabled);
if (id != null)
{
if (TryGetTimeZone(id, dstDisabled, out TimeZoneInfo? zone, out _, cachedData) == TimeZoneInfoResult.Success)
{
// successfully loaded the time zone from the registry
return zone!;
}
}
// We could not find the data in the registry. Fall back to using
// the data from the Win32 API
return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
}
/// <summary>
/// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of
/// try/catch logic for handling the TimeZoneInfo private constructor that takes
/// a TIME_ZONE_INFORMATION structure.
/// </summary>
private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(in TIME_ZONE_INFORMATION timeZoneInformation, bool dstDisabled)
{
// first try to create the TimeZoneInfo with the original 'dstDisabled' flag
try
{
return new TimeZoneInfo(timeZoneInformation, dstDisabled);
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
// if 'dstDisabled' was false then try passing in 'true' as a last ditch effort
if (!dstDisabled)
{
try
{
return new TimeZoneInfo(timeZoneInformation, dstDisabled: true);
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
}
// the data returned from Windows is completely bogus; return a dummy entry
return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
}
/// <summary>
/// Helper function for retrieving a TimeZoneInfo object by time_zone_name.
/// This function wraps the logic necessary to keep the private
/// SystemTimeZones cache in working order
///
/// This function will either return a valid TimeZoneInfo instance or
/// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
/// </summary>
public static TimeZoneInfo FindSystemTimeZoneById(string id)
{
// Special case for Utc to avoid having TryGetTimeZone creating a new Utc object
if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
{
return Utc;
}
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains('\0'))
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
}
TimeZoneInfo? value;
Exception? e;
TimeZoneInfoResult result;
CachedData cachedData = s_cachedData;
lock (cachedData)
{
result = TryGetTimeZone(id, false, out value, out e, cachedData);
}
if (result == TimeZoneInfoResult.Success)
{
return value!;
}
else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
{
throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e);
}
else if (result == TimeZoneInfoResult.SecurityException)
{
throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e);
}
else
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
}
}
// DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
{
isAmbiguousLocalDst = false;
int timeYear = time.Year;
OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
TimeSpan baseOffset = match.Offset;
if (match.Rule != null)
{
baseOffset += match.Rule.BaseUtcOffsetDelta;
if (match.Rule.HasDaylightSaving)
{
bool isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, null, out isAmbiguousLocalDst, Local);
baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
}
}
return baseOffset;
}
/// <summary>
/// Converts a REG_TZI_FORMAT struct to a TransitionTime
/// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
/// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
/// </summary>
private static bool TransitionTimeFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, out TransitionTime transitionTime, bool readStartDate)
{
//
// SYSTEMTIME -
//
// If the time zone does not support daylight saving time or if the caller needs
// to disable daylight saving time, the wMonth member in the SYSTEMTIME structure
// must be zero. If this date is specified, the DaylightDate value in the
// TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system
// assumes the time zone data is invalid and no changes will be applied.
//
bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
if (!supportsDst)
{
transitionTime = default;
return false;
}
//
// SYSTEMTIME -
//
// * FixedDateRule -
// If the Year member is not zero, the transition date is absolute; it will only occur one time
//
// * FloatingDateRule -
// To select the correct day in the month, set the Year member to zero, the Hour and Minute
// members to the transition time, the DayOfWeek member to the appropriate weekday, and the
// Day member to indicate the occurence of the day of the week within the month (first through fifth).
//
// Using this notation, specify the 2:00a.m. on the first Sunday in April as follows:
// Hour = 2,
// Month = 4,
// DayOfWeek = 0,
// Day = 1.
//
// Specify 2:00a.m. on the last Thursday in October as follows:
// Hour = 2,
// Month = 10,
// DayOfWeek = 4,
// Day = 5.
//
if (readStartDate)
{
//
// read the "daylightTransitionStart"
//
if (timeZoneInformation.DaylightDate.Year == 0)
{
transitionTime = TransitionTime.CreateFloatingDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds),
timeZoneInformation.DaylightDate.Month,
timeZoneInformation.DaylightDate.Day, /* Week 1-5 */
(DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek);
}
else
{
transitionTime = TransitionTime.CreateFixedDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds),
timeZoneInformation.DaylightDate.Month,
timeZoneInformation.DaylightDate.Day);
}
}
else
{
//
// read the "daylightTransitionEnd"
//
if (timeZoneInformation.StandardDate.Year == 0)
{
transitionTime = TransitionTime.CreateFloatingDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.StandardDate.Hour,
timeZoneInformation.StandardDate.Minute,
timeZoneInformation.StandardDate.Second,
timeZoneInformation.StandardDate.Milliseconds),
timeZoneInformation.StandardDate.Month,
timeZoneInformation.StandardDate.Day, /* Week 1-5 */
(DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek);
}
else
{
transitionTime = TransitionTime.CreateFixedDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.StandardDate.Hour,
timeZoneInformation.StandardDate.Minute,
timeZoneInformation.StandardDate.Second,
timeZoneInformation.StandardDate.Milliseconds),
timeZoneInformation.StandardDate.Month,
timeZoneInformation.StandardDate.Day);
}
}
return true;
}
/// <summary>
/// Helper function that takes:
/// 1. A string representing a time_zone_name registry key name.
/// 2. A REG_TZI_FORMAT struct containing the default rule.
/// 3. An AdjustmentRule[] out-parameter.
/// </summary>
private static bool TryCreateAdjustmentRules(string id, in REG_TZI_FORMAT defaultTimeZoneInformation, out AdjustmentRule[]? rules, out Exception? e, int defaultBaseUtcOffset)
{
rules = null;
e = null;
try
{
// Optional, Dynamic Time Zone Registry Data
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// HKLM
// Software
// Microsoft
// Windows NT
// CurrentVersion
// Time Zones
// <time_zone_name>
// Dynamic DST
// * "FirstEntry" REG_DWORD "1980"
// First year in the table. If the current year is less than this value,
// this entry will be used for DST boundaries
// * "LastEntry" REG_DWORD "2038"
// Last year in the table. If the current year is greater than this value,
// this entry will be used for DST boundaries"
// * "<year1>" REG_BINARY REG_TZI_FORMAT
// * "<year2>" REG_BINARY REG_TZI_FORMAT
// * "<year3>" REG_BINARY REG_TZI_FORMAT
//
using (RegistryKey? dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false))
{
if (dynamicKey == null)
{
AdjustmentRule? rule = CreateAdjustmentRuleFromTimeZoneInformation(
defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
if (rule != null)
{
rules = new[] { rule };
}
return true;
}
//
// loop over all of the "<time_zone_name>\Dynamic DST" hive entries
//
// read FirstEntry {MinValue - (year1, 12, 31)}
// read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}
// read LastEntry {(yearN, 1, 1) - MaxValue }
// read the FirstEntry and LastEntry key values (ex: "1980", "2038")
int first = (int)dynamicKey.GetValue(FirstEntryValue, -1);
int last = (int)dynamicKey.GetValue(LastEntryValue, -1);
if (first == -1 || last == -1 || first > last)
{
return false;
}
// read the first year entry
REG_TZI_FORMAT dtzi;
if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, first.ToString(CultureInfo.InvariantCulture), out dtzi))
{
return false;
}
if (first == last)
{
// there is just 1 dynamic rule for this time zone.
AdjustmentRule? rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
if (rule != null)
{
rules = new[] { rule };
}
return true;
}
List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
// there are more than 1 dynamic rules for this time zone.
AdjustmentRule? firstRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
DateTime.MinValue.Date, // MinValue
new DateTime(first, 12, 31), // December 31, <FirstYear>
defaultBaseUtcOffset);
if (firstRule != null)
{
rulesList.Add(firstRule);
}
// read the middle year entries
for (int i = first + 1; i < last; i++)
{
if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, i.ToString(CultureInfo.InvariantCulture), out dtzi))
{
return false;
}
AdjustmentRule? middleRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
new DateTime(i, 1, 1), // January 01, <Year>
new DateTime(i, 12, 31), // December 31, <Year>
defaultBaseUtcOffset);
if (middleRule != null)
{
rulesList.Add(middleRule);
}
}
// read the last year entry
if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, last.ToString(CultureInfo.InvariantCulture), out dtzi))
{
return false;
}
AdjustmentRule? lastRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
new DateTime(last, 1, 1), // January 01, <LastYear>
DateTime.MaxValue.Date, // MaxValue
defaultBaseUtcOffset);
if (lastRule != null)
{
rulesList.Add(lastRule);
}
// convert the List to an AdjustmentRule array
if (rulesList.Count != 0)
{
rules = rulesList.ToArray();
}
} // end of: using (RegistryKey dynamicKey...
}
catch (InvalidCastException ex)
{
// one of the RegistryKey.GetValue calls could not be cast to an expected value type
e = ex;
return false;
}
catch (ArgumentOutOfRangeException ex)
{
e = ex;
return false;
}
catch (ArgumentException ex)
{
e = ex;
return false;
}
return true;
}
private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi)
{
if (!(key.GetValue(name, null) is byte[] regValue) || regValue.Length != sizeof(REG_TZI_FORMAT))
{
dtzi = default;
return false;
}
fixed (byte* pBytes = ®Value[0])
dtzi = *(REG_TZI_FORMAT*)pBytes;
return true;
}
/// <summary>
/// Helper function that compares the StandardBias and StandardDate portion a
/// TimeZoneInformation struct to a time zone registry entry.
/// </summary>
private static bool TryCompareStandardDate(in TIME_ZONE_INFORMATION timeZone, in REG_TZI_FORMAT registryTimeZoneInfo) =>
timeZone.Bias == registryTimeZoneInfo.Bias &&
timeZone.StandardBias == registryTimeZoneInfo.StandardBias &&
timeZone.StandardDate.Equals(registryTimeZoneInfo.StandardDate);
/// <summary>
/// Helper function that compares a TimeZoneInformation struct to a time zone registry entry.
/// </summary>
private static bool TryCompareTimeZoneInformationToRegistry(in TIME_ZONE_INFORMATION timeZone, string id, out bool dstDisabled)
{
dstDisabled = false;
using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
{
if (key == null)
{
return false;
}
REG_TZI_FORMAT registryTimeZoneInfo;
if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out registryTimeZoneInfo))
{
return false;
}
//
// first compare the bias and standard date information between the data from the Win32 API
// and the data from the registry...
//
bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
if (!result)
{
return false;
}
result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) ||
//
// since Daylight Saving Time is not "disabled", do a straight comparision between
// the Win32 API data and the registry data ...
//
(timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias &&
timeZone.DaylightDate.Equals(registryTimeZoneInfo.DaylightDate));
// Finally compare the "StandardName" string value...
//
// we do not compare "DaylightName" as this TimeZoneInformation field may contain
// either "StandardName" or "DaylightName" depending on the time of year and current machine settings
//
if (result)
{
string? registryStandardName = key.GetValue(StandardValue, string.Empty) as string;
result = string.Equals(registryStandardName, timeZone.GetStandardName(), StringComparison.Ordinal);
}
return result;
}
}
/// <summary>
/// Helper function for retrieving a localized string resource via MUI.
/// The function expects a string in the form: "@resource.dll, -123"
///
/// "resource.dll" is a language-neutral portable executable (LNPE) file in
/// the %windir%\system32 directory. The OS is queried to find the best-fit
/// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui).
/// If a localized resource file exists, we LoadString resource ID "123" and
/// return it to our caller.
/// </summary>
private static string TryGetLocalizedNameByMuiNativeResource(string resource)
{
if (string.IsNullOrEmpty(resource))
{
return string.Empty;
}
// parse "@tzres.dll, -100"
//
// filePath = "C:\Windows\System32\tzres.dll"
// resourceId = -100
//
string[] resources = resource.Split(',');
if (resources.Length != 2)
{
return string.Empty;
}
string filePath;
int resourceId;
// get the path to Windows\System32
string system32 = Environment.SystemDirectory;
// trim the string "@tzres.dll" => "tzres.dll"
string tzresDll = resources[0].TrimStart('@');
try
{
filePath = Path.Combine(system32, tzresDll);
}
catch (ArgumentException)
{
// there were probably illegal characters in the path
return string.Empty;
}
if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId))
{
return string.Empty;
}
resourceId = -resourceId;
try
{
unsafe
{
char* fileMuiPath = stackalloc char[Interop.Kernel32.MAX_PATH];
int fileMuiPathLength = Interop.Kernel32.MAX_PATH;
int languageLength = 0;
long enumerator = 0;
bool succeeded = Interop.Kernel32.GetFileMUIPath(
Interop.Kernel32.MUI_PREFERRED_UI_LANGUAGES,
filePath, null /* language */, ref languageLength,
fileMuiPath, ref fileMuiPathLength, ref enumerator);
return succeeded ?
TryGetLocalizedNameByNativeResource(new string(fileMuiPath, 0, fileMuiPathLength), resourceId) :
string.Empty;
}
}
catch (EntryPointNotFoundException)
{
return string.Empty;
}
}
/// <summary>
/// Helper function for retrieving a localized string resource via a native resource DLL.
/// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"
///
/// "resource.dll" is a language-specific resource DLL.
/// If the localized resource DLL exists, LoadString(resource) is returned.
/// </summary>
private static unsafe string TryGetLocalizedNameByNativeResource(string filePath, int resource)
{
using (SafeLibraryHandle handle = Interop.Kernel32.LoadLibraryEx(filePath, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE))
{
if (!handle.IsInvalid)
{
const int LoadStringMaxLength = 500;
char* localizedResource = stackalloc char[LoadStringMaxLength];
int charsWritten = Interop.User32.LoadString(handle, (uint)resource, localizedResource, LoadStringMaxLength);
if (charsWritten != 0)
{
return new string(localizedResource, 0, charsWritten);
}
}
}
return string.Empty;
}
/// <summary>
/// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry
///
/// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI
/// resource dll(s). When the keys do not exist, the function falls back to reading from the standard
/// key-values
/// </summary>
private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string? displayName, out string? standardName, out string? daylightName)
{
displayName = string.Empty;
standardName = string.Empty;
daylightName = string.Empty;
// read the MUI_ registry keys
string? displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty) as string;
string? standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty) as string;
string? daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty) as string;
// try to load the strings from the native resource DLL(s)
if (!string.IsNullOrEmpty(displayNameMuiResource))
{
displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource);
}
if (!string.IsNullOrEmpty(standardNameMuiResource))
{
standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource);
}
if (!string.IsNullOrEmpty(daylightNameMuiResource))
{
daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource);
}
// fallback to using the standard registry keys
if (string.IsNullOrEmpty(displayName))
{
displayName = key.GetValue(DisplayValue, string.Empty) as string;
}
if (string.IsNullOrEmpty(standardName))
{
standardName = key.GetValue(StandardValue, string.Empty) as string;
}
if (string.IsNullOrEmpty(daylightName))
{
daylightName = key.GetValue(DaylightValue, string.Empty) as string;
}
}
/// <summary>
/// Helper function that takes a string representing a time_zone_name registry key name
/// and returns a TimeZoneInfo instance.
/// </summary>
private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo? value, out Exception? e)
{
e = null;
// Standard Time Zone Registry Data
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// HKLM
// Software
// Microsoft
// Windows NT
// CurrentVersion
// Time Zones
// <time_zone_name>
// * STD, REG_SZ "Standard Time Name"
// (For OS installed zones, this will always be English)
// * MUI_STD, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for Standard Time,
// add "%windir%\system32\" after "@"
// * DLT, REG_SZ "Daylight Time Name"
// (For OS installed zones, this will always be English)
// * MUI_DLT, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for Daylight Time,
// add "%windir%\system32\" after "@"
// * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..."
// * MUI_Display, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for the Display,
// add "%windir%\system32\" after "@"
// * TZI, REG_BINARY REG_TZI_FORMAT
//
using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
{
if (key == null)
{
value = null;
return TimeZoneInfoResult.TimeZoneNotFoundException;
}
REG_TZI_FORMAT defaultTimeZoneInformation;
if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out defaultTimeZoneInformation))
{
// the registry value could not be cast to a byte array
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
AdjustmentRule[]? adjustmentRules;
if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias))
{
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
GetLocalizedNamesByRegistryKey(key, out string? displayName, out string? standardName, out string? daylightName);
try
{
value = new TimeZoneInfo(
id,
new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0),
displayName,
standardName,
daylightName,
adjustmentRules,
disableDaylightSavingTime: false);
return TimeZoneInfoResult.Success;
}
catch (ArgumentException ex)
{
// TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
value = null;
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
catch (InvalidTimeZoneException ex)
{
// TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
value = null;
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ExtractUInt32129()
{
var test = new ExtractScalarTest__ExtractUInt32129();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ExtractScalarTest__ExtractUInt32129
{
private struct TestStruct
{
public Vector128<UInt32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ExtractScalarTest__ExtractUInt32129 testClass)
{
var result = Sse41.Extract(_fld, 129);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector128<UInt32> _clsVar;
private Vector128<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static ExtractScalarTest__ExtractUInt32129()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public ExtractScalarTest__ExtractUInt32129()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.Extract(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.Extract(
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.Extract(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)),
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (UInt32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (UInt32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)129
});
Unsafe.Write(_dataTable.outArrayPtr, (UInt32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Extract(
_clsVar,
129
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr);
var result = Sse41.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ExtractScalarTest__ExtractUInt32129();
var result = Sse41.Extract(test._fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Extract(_fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Extract(test._fld, 129);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((result[0] != firstOp[1]))
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<UInt32>(Vector128<UInt32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
namespace ALinq.SqlClient
{
internal class SqlMultiplexer
{
// Fields
private readonly Visitor visitor;
private readonly SqlIdentifier sqlIdentity;
// Methods
internal SqlMultiplexer(Options options, IEnumerable<SqlParameter> parentParameters, SqlFactory sqlFactory, SqlIdentifier sqlIdentity)
{
this.sqlIdentity = sqlIdentity;
this.visitor = new Visitor(options, parentParameters, sqlFactory, sqlIdentity);
}
internal SqlNode Multiplex(SqlNode node)
{
return this.visitor.Visit(node);
}
// Nested Types
internal enum Options
{
None,
EnableBigJoin
}
private class Visitor : SqlVisitor
{
// Fields
private bool canJoin;
private bool hasBigJoin;
private bool isTopLevel;
private readonly Options options;
private SqlSelect outerSelect;
private readonly IEnumerable<SqlParameter> parentParameters;
private readonly SqlFactory sql;
private readonly SqlIdentifier sqlIdentity;
// Methods
internal Visitor(Options options, IEnumerable<SqlParameter> parentParameters,
SqlFactory sqlFactory, SqlIdentifier sqlIdentity)
{
this.options = options;
this.sql = sqlFactory;
this.canJoin = true;
this.isTopLevel = true;
this.parentParameters = parentParameters;
this.sqlIdentity = sqlIdentity;
}
internal override SqlExpression VisitClientCase(SqlClientCase c)
{
SqlExpression expression;
bool canJoin = this.canJoin;
this.canJoin = false;
try
{
expression = base.VisitClientCase(c);
}
finally
{
this.canJoin = canJoin;
}
return expression;
}
internal override SqlExpression VisitElement(SqlSubSelect elem)
{
return QueryExtractor.Extract(elem, this.parentParameters, sqlIdentity);
}
internal override SqlExpression VisitExists(SqlSubSelect ss)
{
SqlExpression expression;
bool isTopLevel = this.isTopLevel;
this.isTopLevel = false;
bool canJoin = this.canJoin;
this.canJoin = false;
try
{
expression = base.VisitExists(ss);
}
finally
{
this.isTopLevel = isTopLevel;
this.canJoin = canJoin;
}
return expression;
}
internal override SqlExpression VisitMultiset(SqlSubSelect sms)
{
if (((((this.options & SqlMultiplexer.Options.EnableBigJoin) != SqlMultiplexer.Options.None) && !this.hasBigJoin) &&
(this.canJoin && this.isTopLevel)) && (((this.outerSelect != null) && !MultisetChecker.HasMultiset(sms.Select.Selection)) &&
BigJoinChecker.CanBigJoin(sms.Select)))
{
sms.Select = this.VisitSelect(sms.Select);
SqlAlias right = new SqlAlias(sms.Select);
SqlJoin join = new SqlJoin(SqlJoinType.OuterApply, this.outerSelect.From, right, null, sms.SourceExpression);
this.outerSelect.From = join;
this.outerSelect.OrderingType = SqlOrderingType.Always;
SqlExpression expression = (SqlExpression)SqlDuplicator.Copy(sms.Select.Selection);
SqlSelect node = (SqlSelect)SqlDuplicator.Copy(sms.Select);
SqlAlias from = new SqlAlias(node);
SqlSelect select = new SqlSelect(this.sql.Unary(SqlNodeType.Count, null, sms.SourceExpression), from, sms.SourceExpression);
select.OrderingType = SqlOrderingType.Never;
SqlExpression count = this.sql.SubSelect(SqlNodeType.ScalarSubSelect, select);
SqlJoinedCollection joineds = new SqlJoinedCollection(sms.ClrType, sms.SqlType, expression, count, sms.SourceExpression);
this.hasBigJoin = true;
return joineds;
}
return QueryExtractor.Extract(sms, this.parentParameters, sqlIdentity);
}
internal override SqlExpression VisitOptionalValue(SqlOptionalValue sov)
{
SqlExpression expression;
bool canJoin = this.canJoin;
this.canJoin = false;
try
{
expression = base.VisitOptionalValue(sov);
}
finally
{
this.canJoin = canJoin;
}
return expression;
}
internal override SqlExpression VisitScalarSubSelect(SqlSubSelect ss)
{
SqlExpression expression;
bool isTopLevel = this.isTopLevel;
this.isTopLevel = false;
bool canJoin = this.canJoin;
this.canJoin = false;
try
{
expression = base.VisitScalarSubSelect(ss);
}
finally
{
this.isTopLevel = isTopLevel;
this.canJoin = canJoin;
}
return expression;
}
internal override SqlExpression VisitSearchedCase(SqlSearchedCase c)
{
SqlExpression expression;
bool canJoin = this.canJoin;
this.canJoin = false;
try
{
expression = base.VisitSearchedCase(c);
}
finally
{
this.canJoin = canJoin;
}
return expression;
}
internal override SqlSelect VisitSelect(SqlSelect select)
{
SqlSelect outerSelect = this.outerSelect;
this.outerSelect = select;
this.canJoin &= ((select.GroupBy.Count == 0) && (select.Top == null)) && !select.IsDistinct;
bool isTopLevel = this.isTopLevel;
this.isTopLevel = false;
select.From = this.VisitSource(select.From);
select.Where = this.VisitExpression(select.Where);
int num = 0;
int count = select.GroupBy.Count;
while (num < count)
{
select.GroupBy[num] = this.VisitExpression(select.GroupBy[num]);
num++;
}
select.Having = this.VisitExpression(select.Having);
int num3 = 0;
int num4 = select.OrderBy.Count;
while (num3 < num4)
{
select.OrderBy[num3].Expression = this.VisitExpression(select.OrderBy[num3].Expression);
num3++;
}
select.Top = this.VisitExpression(select.Top);
select.Row = (SqlRow)this.Visit(select.Row);
this.isTopLevel = isTopLevel;
select.Selection = this.VisitExpression(select.Selection);
this.isTopLevel = isTopLevel;
this.outerSelect = outerSelect;
if (select.IsDistinct && HierarchyChecker.HasHierarchy(select.Selection))
{
select.IsDistinct = false;
}
return select;
}
internal override SqlExpression VisitSimpleCase(SqlSimpleCase c)
{
SqlExpression expression;
bool canJoin = this.canJoin;
this.canJoin = false;
try
{
expression = base.VisitSimpleCase(c);
}
finally
{
this.canJoin = canJoin;
}
return expression;
}
internal override SqlExpression VisitTypeCase(SqlTypeCase tc)
{
SqlExpression expression;
bool canJoin = this.canJoin;
this.canJoin = false;
try
{
expression = base.VisitTypeCase(tc);
}
finally
{
this.canJoin = canJoin;
}
return expression;
}
internal override SqlNode VisitUnion(SqlUnion su)
{
this.canJoin = false;
return base.VisitUnion(su);
}
internal override SqlUserQuery VisitUserQuery(SqlUserQuery suq)
{
this.canJoin = false;
return base.VisitUserQuery(suq);
}
//internal override SqlExpression VisitValue(SqlValue value)
//{
// return base.VisitValue(value);
//}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Net.Test.Common;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
[PlatformSpecific(PlatformID.Windows)] // NegotiateStream only supports client-side functionality on Unix
public class NegotiateStreamStreamToStreamTest
{
private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
[Fact]
public void NegotiateStream_StreamToStream_Authentication_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync();
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(false, serverIdentity.IsAuthenticated);
Assert.Equal("", serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[Fact]
public void NegotiateStream_StreamToStream_Authentication_TargetName_Success()
{
string targetName = "testTargetName";
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName);
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[Fact]
public void NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails()
{
string targetName = "testTargetName";
// Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a
// NetworkCredential object with empty user, password and domain.
NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", "");
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials);
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials);
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync(emptyNetworkCredential, targetName);
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
// TODO #5241: Behavior difference:
Assert.Equal(false, clientIdentity.IsAuthenticated);
// On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertHasName(clientIdentity, @"NT AUTHORITY\ANONYMOUS LOGON");
}
}
[Fact]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync();
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
[Fact]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Async_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = client.AuthenticateAsClientAsync();
auth[1] = server.AuthenticateAsServerAsync();
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osuTK.Graphics;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osuTK;
namespace osu.Game.Graphics.UserInterface
{
public class OsuDropdown<T> : Dropdown<T>, IHasAccentColour
{
private Color4 accentColour;
public Color4 AccentColour
{
get => accentColour;
set
{
accentColour = value;
updateAccentColour();
}
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
if (accentColour == default)
accentColour = colours.PinkDarker;
updateAccentColour();
}
private void updateAccentColour()
{
if (Header is IHasAccentColour header) header.AccentColour = accentColour;
if (Menu is IHasAccentColour menu) menu.AccentColour = accentColour;
}
protected override DropdownHeader CreateHeader() => new OsuDropdownHeader();
protected override DropdownMenu CreateMenu() => new OsuDropdownMenu();
#region OsuDropdownMenu
protected class OsuDropdownMenu : DropdownMenu, IHasAccentColour
{
public override bool HandleNonPositionalInput => State == MenuState.Open;
// todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring
public OsuDropdownMenu()
{
CornerRadius = 4;
BackgroundColour = Color4.Black.Opacity(0.5f);
// todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring
ItemsContainer.Padding = new MarginPadding(5);
}
// todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring
protected override void AnimateOpen() => this.FadeIn(300, Easing.OutQuint);
protected override void AnimateClose() => this.FadeOut(300, Easing.OutQuint);
// todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring
protected override void UpdateSize(Vector2 newSize)
{
if (Direction == Direction.Vertical)
{
Width = newSize.X;
this.ResizeHeightTo(newSize.Y, 300, Easing.OutQuint);
}
else
{
Height = newSize.Y;
this.ResizeWidthTo(newSize.X, 300, Easing.OutQuint);
}
}
private Color4 accentColour;
public Color4 AccentColour
{
get => accentColour;
set
{
accentColour = value;
foreach (var c in Children.OfType<IHasAccentColour>())
c.AccentColour = value;
}
}
protected override Menu CreateSubMenu() => new OsuMenu(Direction.Vertical);
protected override DrawableDropdownMenuItem CreateDrawableDropdownMenuItem(MenuItem item) => new DrawableOsuDropdownMenuItem(item) { AccentColour = accentColour };
protected override ScrollContainer<Drawable> CreateScrollContainer(Direction direction) => new OsuScrollContainer(direction);
#region DrawableOsuDropdownMenuItem
public class DrawableOsuDropdownMenuItem : DrawableDropdownMenuItem, IHasAccentColour
{
// IsHovered is used
public override bool HandlePositionalInput => true;
private Color4? accentColour;
public Color4 AccentColour
{
get => accentColour ?? nonAccentSelectedColour;
set
{
accentColour = value;
updateColours();
}
}
private void updateColours()
{
BackgroundColourHover = accentColour ?? nonAccentHoverColour;
BackgroundColourSelected = accentColour ?? nonAccentSelectedColour;
UpdateBackgroundColour();
UpdateForegroundColour();
}
private Color4 nonAccentHoverColour;
private Color4 nonAccentSelectedColour;
public DrawableOsuDropdownMenuItem(MenuItem item)
: base(item)
{
Foreground.Padding = new MarginPadding(2);
Masking = true;
CornerRadius = 6;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = Color4.Transparent;
nonAccentHoverColour = colours.PinkDarker;
nonAccentSelectedColour = Color4.Black.Opacity(0.5f);
updateColours();
AddInternal(new HoverClickSounds(HoverSampleSet.Soft));
}
protected override void UpdateForegroundColour()
{
base.UpdateForegroundColour();
if (Foreground.Children.FirstOrDefault() is Content content) content.Chevron.Alpha = IsHovered ? 1 : 0;
}
protected override Drawable CreateContent() => new Content();
protected new class Content : FillFlowContainer, IHasText
{
public string Text
{
get => Label.Text;
set => Label.Text = value;
}
public readonly OsuSpriteText Label;
public readonly SpriteIcon Chevron;
public Content()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Direction = FillDirection.Horizontal;
Children = new Drawable[]
{
Chevron = new SpriteIcon
{
AlwaysPresent = true,
Icon = FontAwesome.Solid.ChevronRight,
Colour = Color4.Black,
Alpha = 0.5f,
Size = new Vector2(8),
Margin = new MarginPadding { Left = 3, Right = 3 },
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
},
Label = new OsuSpriteText
{
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
},
};
}
}
}
#endregion
}
#endregion
public class OsuDropdownHeader : DropdownHeader, IHasAccentColour
{
protected readonly SpriteText Text;
protected override string Label
{
get => Text.Text;
set => Text.Text = value;
}
protected readonly SpriteIcon Icon;
private Color4 accentColour;
public virtual Color4 AccentColour
{
get => accentColour;
set
{
accentColour = value;
BackgroundColourHover = accentColour;
}
}
public OsuDropdownHeader()
{
Foreground.Padding = new MarginPadding(4);
AutoSizeAxes = Axes.None;
Margin = new MarginPadding { Bottom = 4 };
CornerRadius = 4;
Height = 40;
Foreground.Children = new Drawable[]
{
Text = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
},
Icon = new SpriteIcon
{
Icon = FontAwesome.Solid.ChevronDown,
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
Margin = new MarginPadding { Right = 5 },
Size = new Vector2(12),
},
};
AddInternal(new HoverClickSounds());
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = Color4.Black.Opacity(0.5f);
BackgroundColourHover = colours.PinkDarker;
}
}
}
}
| |
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json.Linq;
namespace Facility.Core;
/// <summary>
/// Helper methods for service data.
/// </summary>
public static class ServiceDataUtility
{
/// <summary>
/// True if the DTOs are equivalent.
/// </summary>
public static bool AreEquivalentDtos(ServiceDto? first, ServiceDto? second) => first == second || first != null && first.IsEquivalentTo(second);
/// <summary>
/// True if the results are equivalent.
/// </summary>
public static bool AreEquivalentResults(ServiceResult? first, ServiceResult? second) => first == second || first != null && first.IsEquivalentTo(second);
/// <summary>
/// True if the objects are equivalent.
/// </summary>
public static bool AreEquivalentObjects(JObject? first, JObject? second) => JToken.DeepEquals(first, second);
/// <summary>
/// True if the objects are equivalent.
/// </summary>
public static bool AreEquivalentObjects(ServiceObject? first, ServiceObject? second) => first == second || first != null && first.IsEquivalentTo(second);
/// <summary>
/// True if the bytes are equivalent.
/// </summary>
public static bool AreEquivalentBytes(byte[]? first, byte[]? second)
{
if (first == null)
return second == null;
if (second == null)
return false;
if (first.Length != second.Length)
return false;
for (var i = 0; i < first.Length; i++)
{
if (first[i] != second[i])
return false;
}
return true;
}
/// <summary>
/// True if the arrays are equivalent.
/// </summary>
public static bool AreEquivalentArrays<T>(IReadOnlyList<T>? first, IReadOnlyList<T>? second, Func<T, T, bool> areEquivalent)
{
if (ReferenceEquals(first, second))
return true;
if (first == null || second == null || first.Count != second.Count)
return false;
for (var i = 0; i < first.Count; i++)
{
if (!areEquivalent(first[i], second[i]))
return false;
}
return true;
}
/// <summary>
/// True if the maps are equivalent.
/// </summary>
public static bool AreEquivalentMaps<T>(IReadOnlyDictionary<string, T>? first, IReadOnlyDictionary<string, T>? second, Func<T, T, bool> areEquivalent)
{
if (ReferenceEquals(first, second))
return true;
if (first == null || second == null || first.Count != second.Count)
return false;
foreach (var pair in first)
{
if (!second.TryGetValue(pair.Key, out var value) || !areEquivalent(pair.Value, value))
return false;
}
return true;
}
/// <summary>
/// True if the field values are equal.
/// </summary>
public static bool AreEquivalentFieldValues<T>(T x, T y) => EquivalenceComparerCache<T>.Instance.Equals(x, y);
/// <summary>
/// Validates the field value.
/// </summary>
public static bool ValidateFieldValue<T>(T value, out string? errorMessage)
{
errorMessage = ValidatorCache<T>.Instance.GetErrorMessage(value, null);
return errorMessage is null;
}
/// <summary>
/// Validates the field value.
/// </summary>
public static bool ValidateFieldValue<T>(T value, string fieldName, out string? errorMessage)
{
errorMessage = ValidatorCache<T>.Instance.GetErrorMessage(value, fieldName);
return errorMessage is null;
}
/// <summary>
/// Clones the data element.
/// </summary>
[return: NotNullIfNotNull("value")]
public static T Clone<T>(T value) => JsonServiceSerializer.Legacy.Clone(value);
/// <summary>
/// Attempts to parse a Boolean.
/// </summary>
public static bool? TryParseBoolean(string? text) => bool.TryParse(text, out var value) ? value : default(bool?);
/// <summary>
/// Attempts to parse an Int32.
/// </summary>
public static int? TryParseInt32(string? text) => int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : default(int?);
/// <summary>
/// Attempts to parse an Int64.
/// </summary>
public static long? TryParseInt64(string? text) => long.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : default(long?);
/// <summary>
/// Attempts to parse a Double.
/// </summary>
public static double? TryParseDouble(string? text) => double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : default(double?);
/// <summary>
/// Attempts to parse a Decimal.
/// </summary>
public static decimal? TryParseDecimal(string? text) => decimal.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : default(decimal?);
/// <summary>
/// Returns the required field error message.
/// </summary>
public static string GetRequiredFieldErrorMessage(string fieldName) => $"'{fieldName}' is required.";
/// <summary>
/// Returns the invalid field error message prefix.
/// </summary>
public static string GetInvalidFieldErrorMessage(string fieldName, string errorMessage) => $"'{fieldName}' is invalid: {errorMessage}";
private static class EquivalenceComparerCache<T>
{
public static readonly IEqualityComparer<T> Instance = CreateInstance();
private static IEqualityComparer<T> CreateInstance()
{
var type = typeof(T);
var typeInfo = type.GetTypeInfo();
if (Nullable.GetUnderlyingType(type) != null || typeof(IEquatable<T>).GetTypeInfo().IsAssignableFrom(typeInfo))
return EqualityComparer<T>.Default;
if (typeof(ServiceDto).GetTypeInfo().IsAssignableFrom(typeInfo))
return (IEqualityComparer<T>) Activator.CreateInstance(typeof(ServiceDtoEquivalenceComparer<>).MakeGenericType(type))!;
if (typeof(ServiceResult).GetTypeInfo().IsAssignableFrom(typeInfo))
return (IEqualityComparer<T>) Activator.CreateInstance(typeof(ServiceResultEquivalenceComparer<>).MakeGenericType(type))!;
if (type == typeof(ServiceObject))
return (IEqualityComparer<T>) Activator.CreateInstance(typeof(ServiceObjectEquivalenceComparer))!;
if (type == typeof(JObject))
return (IEqualityComparer<T>) Activator.CreateInstance(typeof(JObjectEquivalenceComparer))!;
var interfaces = new[] { type }.Concat(typeInfo.ImplementedInterfaces).ToList();
var mapInterface = interfaces.FirstOrDefault(x => x.IsConstructedGenericType &&
x.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>) && x.GetTypeInfo().GenericTypeArguments[0] == typeof(string));
if (mapInterface != null)
{
var genericTypeArguments = mapInterface.GetTypeInfo().GenericTypeArguments;
var valueType = genericTypeArguments[1];
return (IEqualityComparer<T>) Activator.CreateInstance(typeof(MapEquivalenceComparer<,>).MakeGenericType(type, valueType))!;
}
var arrayInterface = interfaces.FirstOrDefault(x => x.IsConstructedGenericType &&
x.GetGenericTypeDefinition() == typeof(IReadOnlyList<>));
if (arrayInterface != null)
{
var itemType = arrayInterface.GetTypeInfo().GenericTypeArguments[0];
return (IEqualityComparer<T>) Activator.CreateInstance(typeof(ArrayEquivalenceComparer<,>).MakeGenericType(type, itemType))!;
}
throw new InvalidOperationException($"Type not supported for equivalence: {typeof(T)}");
}
}
private abstract class NoHashCodeEqualityComparer<T> : EqualityComparer<T>
{
public sealed override int GetHashCode(T obj) => throw new NotImplementedException();
}
private sealed class ServiceDtoEquivalenceComparer<T> : NoHashCodeEqualityComparer<T>
where T : ServiceDto
{
public override bool Equals(T? x, T? y) => AreEquivalentDtos(x, y);
}
private sealed class ServiceResultEquivalenceComparer<T> : NoHashCodeEqualityComparer<T>
where T : ServiceResult
{
public override bool Equals(T? x, T? y) => AreEquivalentResults(x, y);
}
private sealed class ServiceObjectEquivalenceComparer : NoHashCodeEqualityComparer<ServiceObject>
{
public override bool Equals(ServiceObject? x, ServiceObject? y) => AreEquivalentObjects(x, y);
}
private sealed class JObjectEquivalenceComparer : NoHashCodeEqualityComparer<JObject>
{
public override bool Equals(JObject? x, JObject? y) => AreEquivalentObjects(x, y);
}
private sealed class ArrayEquivalenceComparer<T, TItem> : NoHashCodeEqualityComparer<T>
where T : IReadOnlyList<TItem>
{
public override bool Equals(T? x, T? y) => AreEquivalentArrays(x, y, EquivalenceComparerCache<TItem>.Instance.Equals);
}
private sealed class MapEquivalenceComparer<T, TValue> : NoHashCodeEqualityComparer<T>
where T : IReadOnlyDictionary<string, TValue>
{
public override bool Equals(T? x, T? y) => AreEquivalentMaps(x, y, EquivalenceComparerCache<TValue>.Instance.Equals);
}
private interface IValidator<in T>
{
string? GetErrorMessage(T value, string? fieldName);
}
private static class ValidatorCache<T>
{
public static readonly IValidator<T> Instance = CreateInstance();
private static IValidator<T> CreateInstance()
{
var type = typeof(T);
var typeInfo = type.GetTypeInfo();
if (Nullable.GetUnderlyingType(type) != null || typeof(IEquatable<T>).GetTypeInfo().IsAssignableFrom(typeInfo))
return new AlwaysValidValidator<T>();
if (typeof(ServiceDto).GetTypeInfo().IsAssignableFrom(typeInfo))
return (IValidator<T>) Activator.CreateInstance(typeof(ServiceDtoValidator<>).MakeGenericType(type))!;
if (typeof(ServiceResult).GetTypeInfo().IsAssignableFrom(typeInfo))
return (IValidator<T>) Activator.CreateInstance(typeof(ServiceResultValidator<>).MakeGenericType(type))!;
if (type == typeof(JObject) || type == typeof(byte[]))
return new AlwaysValidValidator<T>();
var interfaces = new[] { type }.Concat(typeInfo.ImplementedInterfaces).ToList();
var mapInterface = interfaces.FirstOrDefault(x => x.IsConstructedGenericType &&
x.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>) && x.GetTypeInfo().GenericTypeArguments[0] == typeof(string));
if (mapInterface != null)
{
var genericTypeArguments = mapInterface.GetTypeInfo().GenericTypeArguments;
var valueType = genericTypeArguments[1];
return (IValidator<T>) Activator.CreateInstance(typeof(MapValidator<,>).MakeGenericType(type, valueType))!;
}
var arrayInterface = interfaces.FirstOrDefault(x => x.IsConstructedGenericType &&
x.GetGenericTypeDefinition() == typeof(IReadOnlyList<>));
if (arrayInterface != null)
{
var itemType = arrayInterface.GetTypeInfo().GenericTypeArguments[0];
return (IValidator<T>) Activator.CreateInstance(typeof(ArrayValidator<,>).MakeGenericType(type, itemType))!;
}
throw new InvalidOperationException($"Type not supported for validation: {typeof(T)}");
}
}
private sealed class AlwaysValidValidator<T> : IValidator<T>
{
public string? GetErrorMessage(T value, string? fieldName) => null;
}
private sealed class ServiceDtoValidator<T> : IValidator<T>
where T : ServiceDto
{
public string? GetErrorMessage(T? value, string? fieldName)
{
if (value is null || value.Validate(out var errorMessage))
return null;
return fieldName is null ? errorMessage : GetInvalidFieldErrorMessage(fieldName, errorMessage!);
}
}
private sealed class ServiceResultValidator<T> : IValidator<T>
where T : ServiceResult
{
public string? GetErrorMessage(T? value, string? fieldName)
{
if (value is null || value.Validate(out var errorMessage))
return null;
return fieldName is null ? errorMessage : GetInvalidFieldErrorMessage(fieldName, errorMessage!);
}
}
private sealed class ArrayValidator<T, TItem> : IValidator<T>
where T : class, IReadOnlyList<TItem>
{
public string? GetErrorMessage(T? value, string? fieldName)
{
if (value is null)
return null;
var itemValidator = ValidatorCache<TItem>.Instance;
for (var index = 0; index < value.Count; index++)
{
var item = value[index];
if (itemValidator.GetErrorMessage(item, fieldName is null ? null : $"{fieldName}[{index}]") is { } errorMessage)
return errorMessage;
}
return null;
}
}
private sealed class MapValidator<T, TValue> : IValidator<T>
where T : class, IReadOnlyDictionary<string, TValue>
{
public string? GetErrorMessage(T? value, string? fieldName)
{
if (value is null)
return null;
var itemValidator = ValidatorCache<TValue>.Instance;
foreach (var keyValuePair in value)
{
if (itemValidator.GetErrorMessage(keyValuePair.Value, fieldName is null ? null : $"{fieldName}.{keyValuePair.Key}") is { } errorMessage)
return errorMessage;
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using EPiServer.Core;
using EPiServer.ServiceLocation;
using EPiServerSimpleSite.Business;
using EPiServer.Web.Mvc.Html;
using EPiServer.Web.Routing;
using EPiServer;
namespace EPiServerSimpleSite.Helpers
{
public static class HtmlHelpers
{
/// <summary>
/// Returns an element for each child page of the rootLink using the itemTemplate.
/// </summary>
/// <param name="helper">The html helper in whose context the list should be created</param>
/// <param name="rootLink">A reference to the root whose children should be listed</param>
/// <param name="itemTemplate">A template for each page which will be used to produce the return value. Can be either a delegate or a Razor helper.</param>
/// <param name="includeRoot">Wether an element for the root page should be returned</param>
/// <param name="requireVisibleInMenu">Wether pages that do not have the "Display in navigation" checkbox checked should be excluded</param>
/// <param name="requirePageTemplate">Wether page that do not have a template (i.e. container pages) should be excluded</param>
/// <remarks>
/// Filter by access rights and publication status.
/// </remarks>
public static IHtmlString MenuList(
this HtmlHelper helper,
ContentReference rootLink,
Func<MenuItem, HelperResult> itemTemplate = null,
bool includeRoot = false,
bool requireVisibleInMenu = true,
bool requirePageTemplate = true)
{
itemTemplate = itemTemplate ?? GetDefaultItemTemplate(helper);
var currentContentLink = helper.ViewContext.RequestContext.GetContentLink();
var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();
Func<IEnumerable<PageData>, IEnumerable<PageData>> filter =
pages => pages.FilterForDisplay(requirePageTemplate, requireVisibleInMenu);
var pagePath = contentLoader.GetAncestors(currentContentLink)
.Reverse()
.Select(x => x.ContentLink)
.SkipWhile(x => !x.CompareToIgnoreWorkID(rootLink))
.ToList();
var menuItems = contentLoader.GetChildren<PageData>(rootLink)
.FilterForDisplay(requirePageTemplate, requireVisibleInMenu)
.Select(x => CreateMenuItem(x, currentContentLink, pagePath, contentLoader, filter))
.ToList();
if (includeRoot)
{
menuItems.Insert(0,
CreateMenuItem(contentLoader.Get<PageData>(rootLink), currentContentLink, pagePath, contentLoader,
filter));
}
var buffer = new StringBuilder();
var writer = new StringWriter(buffer);
foreach (var menuItem in menuItems)
{
itemTemplate(menuItem).WriteTo(writer);
}
return new MvcHtmlString(buffer.ToString());
}
private static MenuItem CreateMenuItem(PageData page, ContentReference currentContentLink,
List<ContentReference> pagePath, IContentLoader contentLoader,
Func<IEnumerable<PageData>, IEnumerable<PageData>> filter)
{
var menuItem = new MenuItem(page)
{
Selected = page.ContentLink.CompareToIgnoreWorkID(currentContentLink) ||
pagePath.Contains(page.ContentLink),
HasChildren =
new Lazy<bool>(() => filter(contentLoader.GetChildren<PageData>(page.ContentLink)).Any())
};
return menuItem;
}
private static Func<MenuItem, HelperResult> GetDefaultItemTemplate(HtmlHelper helper)
{
return x => new HelperResult(writer => writer.Write(helper.PageLink(x.Page)));
}
public class MenuItem
{
public MenuItem(PageData page)
{
Page = page;
}
public PageData Page { get; set; }
public bool Selected { get; set; }
public Lazy<bool> HasChildren { get; set; }
}
/// <summary>
/// Writes an opening <![CDATA[ <a> ]]> tag to the response if the shouldWriteLink argument is true.
/// Returns a ConditionalLink object which when disposed will write a closing <![CDATA[ </a> ]]> tag
/// to the response if the shouldWriteLink argument is true.
/// </summary>
public static ConditionalLink BeginConditionalLink(this HtmlHelper helper, bool shouldWriteLink, IHtmlString url,
string title = null, string cssClass = null)
{
if (shouldWriteLink)
{
var linkTag = new TagBuilder("a");
linkTag.Attributes.Add("href", url.ToHtmlString());
if (!string.IsNullOrWhiteSpace(title))
{
linkTag.Attributes.Add("title", helper.Encode(title));
}
if (!string.IsNullOrWhiteSpace(cssClass))
{
linkTag.Attributes.Add("class", cssClass);
}
helper.ViewContext.Writer.Write(linkTag.ToString(TagRenderMode.StartTag));
}
return new ConditionalLink(helper.ViewContext, shouldWriteLink);
}
/// <summary>
/// Writes an opening <![CDATA[ <a> ]]> tag to the response if the shouldWriteLink argument is true.
/// Returns a ConditionalLink object which when disposed will write a closing <![CDATA[ </a> ]]> tag
/// to the response if the shouldWriteLink argument is true.
/// </summary>
/// <remarks>
/// Overload which only executes the delegate for retrieving the URL if the link should be written.
/// This may be used to prevent null reference exceptions by adding null checkes to the shouldWriteLink condition.
/// </remarks>
public static ConditionalLink BeginConditionalLink(this HtmlHelper helper, bool shouldWriteLink,
Func<IHtmlString> urlGetter, string title = null, string cssClass = null)
{
IHtmlString url = MvcHtmlString.Empty;
if (shouldWriteLink)
{
url = urlGetter();
}
return helper.BeginConditionalLink(shouldWriteLink, url, title, cssClass);
}
public class ConditionalLink : IDisposable
{
private readonly ViewContext _viewContext;
private readonly bool _linked;
private bool _disposed;
public ConditionalLink(ViewContext viewContext, bool isLinked)
{
_viewContext = viewContext;
_linked = isLinked;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (_linked)
{
_viewContext.Writer.Write("</a>");
}
}
}
public static string ActivePage(this HtmlHelper helper, string controller, string action)
{
string classValue = "";
var overrideList = new List<PageCheck>
{
new PageCheck("Index", "ChangePassword"),
new PageCheck("Index", "ManageUserRoles")
};
string currentController =
helper.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
string currentAction = helper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();
if (overrideList.Any(x => x.OrginalPage == action && x.MappedPage == currentAction))
currentAction = action;
classValue = currentController.ToLower() == controller.ToLower() && currentAction.ToLower() == action.ToLower()
? "epi-tabView-navigation-item-selected"
: "epi-tabView-navigation-item";
return classValue;
}
}
internal class PageCheck
{
public string OrginalPage { get; set; }
public string MappedPage { get; set; }
public PageCheck(string op, string mp)
{
OrginalPage = op;
MappedPage = mp;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. 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 Microsoft.DotNet.PlatformAbstractions;
namespace Microsoft.DotNet.ProjectModel.Utilities
{
internal static class PathUtility
{
public static bool IsChildOfDirectory(string dir, string candidate)
{
if (dir == null)
{
throw new ArgumentNullException(nameof(dir));
}
if (candidate == null)
{
throw new ArgumentNullException(nameof(candidate));
}
dir = Path.GetFullPath(dir);
dir = EnsureTrailingSlash(dir);
candidate = Path.GetFullPath(candidate);
return candidate.StartsWith(dir, StringComparison.OrdinalIgnoreCase);
}
public static string EnsureTrailingSlash(string path)
{
return EnsureTrailingCharacter(path, Path.DirectorySeparatorChar);
}
public static string EnsureTrailingForwardSlash(string path)
{
return EnsureTrailingCharacter(path, '/');
}
private static string EnsureTrailingCharacter(string path, char trailingCharacter)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
// if the path is empty, we want to return the original string instead of a single trailing character.
if (path.Length == 0 || path[path.Length - 1] == trailingCharacter)
{
return path;
}
return path + trailingCharacter;
}
public static void EnsureParentDirectory(string filePath)
{
string directory = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
}
/// <summary>
/// Returns <paramref name="path2"/> relative to <paramref name="path1"/>, with Path.DirectorySeparatorChar as separator
/// </summary>
public static string GetRelativePath(string path1, string path2)
{
return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, includeDirectoryTraversals: true);
}
/// <summary>
/// Returns <paramref name="path2"/> relative to <paramref name="path1"/>, with <c>Path.DirectorySeparatorChar</c>
/// as separator but ignoring directory traversals.
/// </summary>
public static string GetRelativePathIgnoringDirectoryTraversals(string path1, string path2)
{
return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, false);
}
/// <summary>
/// Returns <paramref name="path2"/> relative to <paramref name="path1"/>, with given path separator
/// </summary>
public static string GetRelativePath(string path1, string path2, char separator, bool includeDirectoryTraversals)
{
if (string.IsNullOrEmpty(path1))
{
throw new ArgumentException("Path must have a value", nameof(path1));
}
if (string.IsNullOrEmpty(path2))
{
throw new ArgumentException("Path must have a value", nameof(path2));
}
StringComparison compare;
if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows)
{
compare = StringComparison.OrdinalIgnoreCase;
// check if paths are on the same volume
if (!string.Equals(Path.GetPathRoot(path1), Path.GetPathRoot(path2)))
{
// on different volumes, "relative" path is just path2
return path2;
}
}
else
{
compare = StringComparison.Ordinal;
}
var index = 0;
var path1Segments = path1.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var path2Segments = path2.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// if path1 does not end with / it is assumed the end is not a directory
// we will assume that is isn't a directory by ignoring the last split
var len1 = path1Segments.Length - 1;
var len2 = path2Segments.Length;
// find largest common absolute path between both paths
var min = Math.Min(len1, len2);
while (min > index)
{
if (!string.Equals(path1Segments[index], path2Segments[index], compare))
{
break;
}
// Handle scenarios where folder and file have same name (only if os supports same name for file and directory)
// e.g. /file/name /file/name/app
else if ((len1 == index && len2 > index + 1) || (len1 > index && len2 == index + 1))
{
break;
}
++index;
}
var path = "";
// check if path2 ends with a non-directory separator and if path1 has the same non-directory at the end
if (len1 + 1 == len2 && !string.IsNullOrEmpty(path1Segments[index]) &&
string.Equals(path1Segments[index], path2Segments[index], compare))
{
return path;
}
if (includeDirectoryTraversals)
{
for (var i = index; len1 > i; ++i)
{
path += ".." + separator;
}
}
for (var i = index; len2 - 1 > i; ++i)
{
path += path2Segments[i] + separator;
}
// if path2 doesn't end with an empty string it means it ended with a non-directory name, so we add it back
if (!string.IsNullOrEmpty(path2Segments[len2 - 1]))
{
path += path2Segments[len2 - 1];
}
return path;
}
public static string GetAbsolutePath(string basePath, string relativePath)
{
if (basePath == null)
{
throw new ArgumentNullException(nameof(basePath));
}
if (relativePath == null)
{
throw new ArgumentNullException(nameof(relativePath));
}
Uri resultUri = new Uri(new Uri(basePath), new Uri(relativePath, UriKind.Relative));
return resultUri.LocalPath;
}
public static string GetDirectoryName(string path)
{
path = path.TrimEnd(Path.DirectorySeparatorChar);
return path.Substring(Path.GetDirectoryName(path).Length).Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
public static string GetPathWithForwardSlashes(string path)
{
return path.Replace('\\', '/');
}
public static string GetPathWithBackSlashes(string path)
{
return path.Replace('/', '\\');
}
public static string GetPathWithDirectorySeparator(string path)
{
if (Path.DirectorySeparatorChar == '/')
{
return GetPathWithForwardSlashes(path);
}
else
{
return GetPathWithBackSlashes(path);
}
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
/// OrderLine
/// </summary>
[DataContract]
public partial class OrderLine : IEquatable<OrderLine>
{
/// <summary>
/// Initializes a new instance of the <see cref="OrderLine" /> class.
/// </summary>
[JsonConstructorAttribute]
protected OrderLine() { }
/// <summary>
/// Initializes a new instance of the <see cref="OrderLine" /> class.
/// </summary>
/// <param name="ItemAccountCodeId">ItemAccountCodeId (required).</param>
/// <param name="ItemLegacyLowStockContactId">ItemLegacyLowStockContactId (required).</param>
/// <param name="ItemMajorGroupId">ItemMajorGroupId (required).</param>
/// <param name="ItemSubGroupId">ItemSubGroupId (required).</param>
/// <param name="ItemProductCodeId">ItemProductCodeId.</param>
/// <param name="ItemSummaryCodeId">ItemSummaryCodeId (required).</param>
public OrderLine(int? ItemAccountCodeId = null, int? ItemLegacyLowStockContactId = null, int? ItemMajorGroupId = null, int? ItemSubGroupId = null, int? ItemProductCodeId = null, int? ItemSummaryCodeId = null)
{
// to ensure "ItemAccountCodeId" is required (not null)
if (ItemAccountCodeId == null)
{
throw new InvalidDataException("ItemAccountCodeId is a required property for OrderLine and cannot be null");
}
else
{
this.ItemAccountCodeId = ItemAccountCodeId;
}
// to ensure "ItemLegacyLowStockContactId" is required (not null)
if (ItemLegacyLowStockContactId == null)
{
throw new InvalidDataException("ItemLegacyLowStockContactId is a required property for OrderLine and cannot be null");
}
else
{
this.ItemLegacyLowStockContactId = ItemLegacyLowStockContactId;
}
// to ensure "ItemMajorGroupId" is required (not null)
if (ItemMajorGroupId == null)
{
throw new InvalidDataException("ItemMajorGroupId is a required property for OrderLine and cannot be null");
}
else
{
this.ItemMajorGroupId = ItemMajorGroupId;
}
// to ensure "ItemSubGroupId" is required (not null)
if (ItemSubGroupId == null)
{
throw new InvalidDataException("ItemSubGroupId is a required property for OrderLine and cannot be null");
}
else
{
this.ItemSubGroupId = ItemSubGroupId;
}
// to ensure "ItemSummaryCodeId" is required (not null)
if (ItemSummaryCodeId == null)
{
throw new InvalidDataException("ItemSummaryCodeId is a required property for OrderLine and cannot be null");
}
else
{
this.ItemSummaryCodeId = ItemSummaryCodeId;
}
this.ItemProductCodeId = ItemProductCodeId;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets OrderNo
/// </summary>
[DataMember(Name="orderNo", EmitDefaultValue=false)]
public double? OrderNo { get; private set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; private set; }
/// <summary>
/// Gets or Sets Sku
/// </summary>
[DataMember(Name="sku", EmitDefaultValue=false)]
public string Sku { get; private set; }
/// <summary>
/// Gets or Sets PoNoId
/// </summary>
[DataMember(Name="poNoId", EmitDefaultValue=false)]
public int? PoNoId { get; private set; }
/// <summary>
/// Gets or Sets OrderedQty
/// </summary>
[DataMember(Name="orderedQty", EmitDefaultValue=false)]
public int? OrderedQty { get; private set; }
/// <summary>
/// Gets or Sets AllowedQty
/// </summary>
[DataMember(Name="allowedQty", EmitDefaultValue=false)]
public int? AllowedQty { get; private set; }
/// <summary>
/// Gets or Sets ShippedQty
/// </summary>
[DataMember(Name="shippedQty", EmitDefaultValue=false)]
public int? ShippedQty { get; private set; }
/// <summary>
/// Gets or Sets BackorderQty
/// </summary>
[DataMember(Name="backorderQty", EmitDefaultValue=false)]
public int? BackorderQty { get; private set; }
/// <summary>
/// Gets or Sets RevDate
/// </summary>
[DataMember(Name="revDate", EmitDefaultValue=false)]
public string RevDate { get; private set; }
/// <summary>
/// Gets or Sets ChargeCode
/// </summary>
[DataMember(Name="chargeCode", EmitDefaultValue=false)]
public string ChargeCode { get; private set; }
/// <summary>
/// Gets or Sets DistributionCode
/// </summary>
[DataMember(Name="distributionCode", EmitDefaultValue=false)]
public string DistributionCode { get; private set; }
/// <summary>
/// Gets or Sets Upc
/// </summary>
[DataMember(Name="upc", EmitDefaultValue=false)]
public string Upc { get; private set; }
/// <summary>
/// Gets or Sets VendorSKU
/// </summary>
[DataMember(Name="vendorSKU", EmitDefaultValue=false)]
public string VendorSKU { get; private set; }
/// <summary>
/// Gets or Sets OrderSourceSKU
/// </summary>
[DataMember(Name="orderSourceSKU", EmitDefaultValue=false)]
public string OrderSourceSKU { get; private set; }
/// <summary>
/// Gets or Sets UnitCost
/// </summary>
[DataMember(Name="unitCost", EmitDefaultValue=false)]
public double? UnitCost { get; private set; }
/// <summary>
/// Gets or Sets UnitSell
/// </summary>
[DataMember(Name="unitSell", EmitDefaultValue=false)]
public double? UnitSell { get; private set; }
/// <summary>
/// Gets or Sets ExtendedCost
/// </summary>
[DataMember(Name="extendedCost", EmitDefaultValue=false)]
public double? ExtendedCost { get; private set; }
/// <summary>
/// Gets or Sets ExtendedSell
/// </summary>
[DataMember(Name="extendedSell", EmitDefaultValue=false)]
public double? ExtendedSell { get; private set; }
/// <summary>
/// Gets or Sets NcExtendedSell
/// </summary>
[DataMember(Name="ncExtendedSell", EmitDefaultValue=false)]
public double? NcExtendedSell { get; private set; }
/// <summary>
/// Gets or Sets ItemWeight
/// </summary>
[DataMember(Name="itemWeight", EmitDefaultValue=false)]
public double? ItemWeight { get; private set; }
/// <summary>
/// Gets or Sets WeightPerWrap
/// </summary>
[DataMember(Name="weightPerWrap", EmitDefaultValue=false)]
public double? WeightPerWrap { get; private set; }
/// <summary>
/// Gets or Sets Sector
/// </summary>
[DataMember(Name="sector", EmitDefaultValue=false)]
public string Sector { get; private set; }
/// <summary>
/// Gets or Sets ItemAccountCodeId
/// </summary>
[DataMember(Name="itemAccountCodeId", EmitDefaultValue=false)]
public int? ItemAccountCodeId { get; set; }
/// <summary>
/// Gets or Sets ItemLegacyLowStockContactId
/// </summary>
[DataMember(Name="itemLegacyLowStockContactId", EmitDefaultValue=false)]
public int? ItemLegacyLowStockContactId { get; set; }
/// <summary>
/// Gets or Sets ItemMajorGroupId
/// </summary>
[DataMember(Name="itemMajorGroupId", EmitDefaultValue=false)]
public int? ItemMajorGroupId { get; set; }
/// <summary>
/// Gets or Sets ItemSubGroupId
/// </summary>
[DataMember(Name="itemSubGroupId", EmitDefaultValue=false)]
public int? ItemSubGroupId { get; set; }
/// <summary>
/// Gets or Sets ItemProductCodeId
/// </summary>
[DataMember(Name="itemProductCodeId", EmitDefaultValue=false)]
public int? ItemProductCodeId { get; set; }
/// <summary>
/// Gets or Sets ItemSummaryCodeId
/// </summary>
[DataMember(Name="itemSummaryCodeId", EmitDefaultValue=false)]
public int? ItemSummaryCodeId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OrderLine {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" OrderNo: ").Append(OrderNo).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" Sku: ").Append(Sku).Append("\n");
sb.Append(" PoNoId: ").Append(PoNoId).Append("\n");
sb.Append(" OrderedQty: ").Append(OrderedQty).Append("\n");
sb.Append(" AllowedQty: ").Append(AllowedQty).Append("\n");
sb.Append(" ShippedQty: ").Append(ShippedQty).Append("\n");
sb.Append(" BackorderQty: ").Append(BackorderQty).Append("\n");
sb.Append(" RevDate: ").Append(RevDate).Append("\n");
sb.Append(" ChargeCode: ").Append(ChargeCode).Append("\n");
sb.Append(" DistributionCode: ").Append(DistributionCode).Append("\n");
sb.Append(" Upc: ").Append(Upc).Append("\n");
sb.Append(" VendorSKU: ").Append(VendorSKU).Append("\n");
sb.Append(" OrderSourceSKU: ").Append(OrderSourceSKU).Append("\n");
sb.Append(" UnitCost: ").Append(UnitCost).Append("\n");
sb.Append(" UnitSell: ").Append(UnitSell).Append("\n");
sb.Append(" ExtendedCost: ").Append(ExtendedCost).Append("\n");
sb.Append(" ExtendedSell: ").Append(ExtendedSell).Append("\n");
sb.Append(" NcExtendedSell: ").Append(NcExtendedSell).Append("\n");
sb.Append(" ItemWeight: ").Append(ItemWeight).Append("\n");
sb.Append(" WeightPerWrap: ").Append(WeightPerWrap).Append("\n");
sb.Append(" Sector: ").Append(Sector).Append("\n");
sb.Append(" ItemAccountCodeId: ").Append(ItemAccountCodeId).Append("\n");
sb.Append(" ItemLegacyLowStockContactId: ").Append(ItemLegacyLowStockContactId).Append("\n");
sb.Append(" ItemMajorGroupId: ").Append(ItemMajorGroupId).Append("\n");
sb.Append(" ItemSubGroupId: ").Append(ItemSubGroupId).Append("\n");
sb.Append(" ItemProductCodeId: ").Append(ItemProductCodeId).Append("\n");
sb.Append(" ItemSummaryCodeId: ").Append(ItemSummaryCodeId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as OrderLine);
}
/// <summary>
/// Returns true if OrderLine instances are equal
/// </summary>
/// <param name="other">Instance of OrderLine to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OrderLine other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.OrderNo == other.OrderNo ||
this.OrderNo != null &&
this.OrderNo.Equals(other.OrderNo)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.Sku == other.Sku ||
this.Sku != null &&
this.Sku.Equals(other.Sku)
) &&
(
this.PoNoId == other.PoNoId ||
this.PoNoId != null &&
this.PoNoId.Equals(other.PoNoId)
) &&
(
this.OrderedQty == other.OrderedQty ||
this.OrderedQty != null &&
this.OrderedQty.Equals(other.OrderedQty)
) &&
(
this.AllowedQty == other.AllowedQty ||
this.AllowedQty != null &&
this.AllowedQty.Equals(other.AllowedQty)
) &&
(
this.ShippedQty == other.ShippedQty ||
this.ShippedQty != null &&
this.ShippedQty.Equals(other.ShippedQty)
) &&
(
this.BackorderQty == other.BackorderQty ||
this.BackorderQty != null &&
this.BackorderQty.Equals(other.BackorderQty)
) &&
(
this.RevDate == other.RevDate ||
this.RevDate != null &&
this.RevDate.Equals(other.RevDate)
) &&
(
this.ChargeCode == other.ChargeCode ||
this.ChargeCode != null &&
this.ChargeCode.Equals(other.ChargeCode)
) &&
(
this.DistributionCode == other.DistributionCode ||
this.DistributionCode != null &&
this.DistributionCode.Equals(other.DistributionCode)
) &&
(
this.Upc == other.Upc ||
this.Upc != null &&
this.Upc.Equals(other.Upc)
) &&
(
this.VendorSKU == other.VendorSKU ||
this.VendorSKU != null &&
this.VendorSKU.Equals(other.VendorSKU)
) &&
(
this.OrderSourceSKU == other.OrderSourceSKU ||
this.OrderSourceSKU != null &&
this.OrderSourceSKU.Equals(other.OrderSourceSKU)
) &&
(
this.UnitCost == other.UnitCost ||
this.UnitCost != null &&
this.UnitCost.Equals(other.UnitCost)
) &&
(
this.UnitSell == other.UnitSell ||
this.UnitSell != null &&
this.UnitSell.Equals(other.UnitSell)
) &&
(
this.ExtendedCost == other.ExtendedCost ||
this.ExtendedCost != null &&
this.ExtendedCost.Equals(other.ExtendedCost)
) &&
(
this.ExtendedSell == other.ExtendedSell ||
this.ExtendedSell != null &&
this.ExtendedSell.Equals(other.ExtendedSell)
) &&
(
this.NcExtendedSell == other.NcExtendedSell ||
this.NcExtendedSell != null &&
this.NcExtendedSell.Equals(other.NcExtendedSell)
) &&
(
this.ItemWeight == other.ItemWeight ||
this.ItemWeight != null &&
this.ItemWeight.Equals(other.ItemWeight)
) &&
(
this.WeightPerWrap == other.WeightPerWrap ||
this.WeightPerWrap != null &&
this.WeightPerWrap.Equals(other.WeightPerWrap)
) &&
(
this.Sector == other.Sector ||
this.Sector != null &&
this.Sector.Equals(other.Sector)
) &&
(
this.ItemAccountCodeId == other.ItemAccountCodeId ||
this.ItemAccountCodeId != null &&
this.ItemAccountCodeId.Equals(other.ItemAccountCodeId)
) &&
(
this.ItemLegacyLowStockContactId == other.ItemLegacyLowStockContactId ||
this.ItemLegacyLowStockContactId != null &&
this.ItemLegacyLowStockContactId.Equals(other.ItemLegacyLowStockContactId)
) &&
(
this.ItemMajorGroupId == other.ItemMajorGroupId ||
this.ItemMajorGroupId != null &&
this.ItemMajorGroupId.Equals(other.ItemMajorGroupId)
) &&
(
this.ItemSubGroupId == other.ItemSubGroupId ||
this.ItemSubGroupId != null &&
this.ItemSubGroupId.Equals(other.ItemSubGroupId)
) &&
(
this.ItemProductCodeId == other.ItemProductCodeId ||
this.ItemProductCodeId != null &&
this.ItemProductCodeId.Equals(other.ItemProductCodeId)
) &&
(
this.ItemSummaryCodeId == other.ItemSummaryCodeId ||
this.ItemSummaryCodeId != null &&
this.ItemSummaryCodeId.Equals(other.ItemSummaryCodeId)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.OrderNo != null)
hash = hash * 59 + this.OrderNo.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.Sku != null)
hash = hash * 59 + this.Sku.GetHashCode();
if (this.PoNoId != null)
hash = hash * 59 + this.PoNoId.GetHashCode();
if (this.OrderedQty != null)
hash = hash * 59 + this.OrderedQty.GetHashCode();
if (this.AllowedQty != null)
hash = hash * 59 + this.AllowedQty.GetHashCode();
if (this.ShippedQty != null)
hash = hash * 59 + this.ShippedQty.GetHashCode();
if (this.BackorderQty != null)
hash = hash * 59 + this.BackorderQty.GetHashCode();
if (this.RevDate != null)
hash = hash * 59 + this.RevDate.GetHashCode();
if (this.ChargeCode != null)
hash = hash * 59 + this.ChargeCode.GetHashCode();
if (this.DistributionCode != null)
hash = hash * 59 + this.DistributionCode.GetHashCode();
if (this.Upc != null)
hash = hash * 59 + this.Upc.GetHashCode();
if (this.VendorSKU != null)
hash = hash * 59 + this.VendorSKU.GetHashCode();
if (this.OrderSourceSKU != null)
hash = hash * 59 + this.OrderSourceSKU.GetHashCode();
if (this.UnitCost != null)
hash = hash * 59 + this.UnitCost.GetHashCode();
if (this.UnitSell != null)
hash = hash * 59 + this.UnitSell.GetHashCode();
if (this.ExtendedCost != null)
hash = hash * 59 + this.ExtendedCost.GetHashCode();
if (this.ExtendedSell != null)
hash = hash * 59 + this.ExtendedSell.GetHashCode();
if (this.NcExtendedSell != null)
hash = hash * 59 + this.NcExtendedSell.GetHashCode();
if (this.ItemWeight != null)
hash = hash * 59 + this.ItemWeight.GetHashCode();
if (this.WeightPerWrap != null)
hash = hash * 59 + this.WeightPerWrap.GetHashCode();
if (this.Sector != null)
hash = hash * 59 + this.Sector.GetHashCode();
if (this.ItemAccountCodeId != null)
hash = hash * 59 + this.ItemAccountCodeId.GetHashCode();
if (this.ItemLegacyLowStockContactId != null)
hash = hash * 59 + this.ItemLegacyLowStockContactId.GetHashCode();
if (this.ItemMajorGroupId != null)
hash = hash * 59 + this.ItemMajorGroupId.GetHashCode();
if (this.ItemSubGroupId != null)
hash = hash * 59 + this.ItemSubGroupId.GetHashCode();
if (this.ItemProductCodeId != null)
hash = hash * 59 + this.ItemProductCodeId.GetHashCode();
if (this.ItemSummaryCodeId != null)
hash = hash * 59 + this.ItemSummaryCodeId.GetHashCode();
return hash;
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Runtime.InteropServices.TCEAdapterGen {
using System.Runtime.InteropServices;
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Diagnostics.Contracts;
internal class EventSinkHelperWriter
{
public static readonly String GeneratedTypeNamePostfix = "_SinkHelper";
public EventSinkHelperWriter( ModuleBuilder OutputModule, Type InputType, Type EventItfType )
{
m_InputType = InputType;
m_OutputModule = OutputModule;
m_EventItfType = EventItfType;
}
public Type Perform()
{
// Create the output Type.
Type[] aInterfaces = new Type[1];
aInterfaces[0] = m_InputType;
String strFullName = null;
String strNameSpace = NameSpaceExtractor.ExtractNameSpace( m_EventItfType.FullName );
if (strNameSpace != "")
strFullName = strNameSpace + ".";
strFullName += m_InputType.Name + GeneratedTypeNamePostfix;
TypeBuilder OutputTypeBuilder = TCEAdapterGenerator.DefineUniqueType(
strFullName,
TypeAttributes.Sealed | TypeAttributes.Public,
null,
aInterfaces,
m_OutputModule
);
// Hide the _SinkProvider interface
TCEAdapterGenerator.SetHiddenAttribute(OutputTypeBuilder);
// Set the class interface to none.
TCEAdapterGenerator.SetClassInterfaceTypeToNone(OutputTypeBuilder);
// Retrieve the property methods on the input interface and give them a dummy implementation.
MethodInfo[] pMethods = TCEAdapterGenerator.GetPropertyMethods(m_InputType);
foreach (MethodInfo method in pMethods)
{
DefineBlankMethod(OutputTypeBuilder, method);
}
// Retrieve the non-property methods on the input interface.
MethodInfo[] aMethods = TCEAdapterGenerator.GetNonPropertyMethods(m_InputType);
// Allocate an array to contain the delegate fields.
FieldBuilder[] afbDelegates = new FieldBuilder[aMethods.Length];
// Process all the methods on the input interface.
for ( int cMethods = 0; cMethods < aMethods.Length; cMethods++ )
{
if ( m_InputType == aMethods[cMethods].DeclaringType )
{
// Retrieve the delegate type from the add_XXX method.
MethodInfo AddMeth = m_EventItfType.GetMethod( "add_" + aMethods[cMethods].Name );
ParameterInfo[] aParams = AddMeth.GetParameters();
Contract.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type");
Type DelegateCls = aParams[0].ParameterType;
// Define the delegate instance field.
afbDelegates[cMethods] = OutputTypeBuilder.DefineField(
"m_" + aMethods[cMethods].Name + "Delegate",
DelegateCls,
FieldAttributes.Public
);
// Define the event method itself.
DefineEventMethod( OutputTypeBuilder, aMethods[cMethods], DelegateCls, afbDelegates[cMethods] );
}
}
// Create the cookie field.
FieldBuilder fbCookie = OutputTypeBuilder.DefineField(
"m_dwCookie",
typeof(Int32),
FieldAttributes.Public
);
// Define the constructor.
DefineConstructor( OutputTypeBuilder, fbCookie, afbDelegates );
return OutputTypeBuilder.CreateType();
}
private void DefineBlankMethod(TypeBuilder OutputTypeBuilder, MethodInfo Method)
{
ParameterInfo[] PIs = Method.GetParameters();
Type[] parameters = new Type[PIs.Length];
for (int i=0; i < PIs.Length; i++)
{
parameters[i] = PIs[i].ParameterType;
}
MethodBuilder Meth = OutputTypeBuilder.DefineMethod(Method.Name,
Method.Attributes & ~MethodAttributes.Abstract,
Method.CallingConvention,
Method.ReturnType,
parameters);
ILGenerator il = Meth.GetILGenerator();
AddReturn(Method.ReturnType, il, Meth);
il.Emit(OpCodes.Ret);
}
private void DefineEventMethod( TypeBuilder OutputTypeBuilder, MethodInfo Method, Type DelegateCls, FieldBuilder fbDelegate )
{
// Retrieve the method info for the invoke method on the delegate.
MethodInfo DelegateInvokeMethod = DelegateCls.GetMethod( "Invoke" );
Contract.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()");
// Retrieve the return type.
Type ReturnType = Method.ReturnType;
// Define the actual event method.
ParameterInfo[] paramInfos = Method.GetParameters();
Type[] parameterTypes;
if (paramInfos != null)
{
parameterTypes = new Type[paramInfos.Length];
for (int i = 0; i < paramInfos.Length; i++)
{
parameterTypes[i] = paramInfos[i].ParameterType;
}
}
else
parameterTypes = null;
MethodAttributes attr = MethodAttributes.Public | MethodAttributes.Virtual;
MethodBuilder Meth = OutputTypeBuilder.DefineMethod( Method.Name,
attr,
CallingConventions.Standard,
ReturnType,
parameterTypes);
// We explicitly do not specify parameter name and attributes since this Type
// is not meant to be exposed to the user. It is only used internally to do the
// connection point to TCE mapping.
ILGenerator il = Meth.GetILGenerator();
// Create the exit branch.
Label ExitLabel = il.DefineLabel();
// Generate the code that verifies that the delegate is not null.
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbDelegate );
il.Emit( OpCodes.Brfalse, ExitLabel );
// The delegate is not NULL so we need to invoke it.
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldfld, fbDelegate );
// Generate the code to load the arguments before we call invoke.
ParameterInfo[] aParams = Method.GetParameters();
for ( int cParams = 0; cParams < aParams.Length; cParams++ )
{
il.Emit( OpCodes.Ldarg, (short)(cParams + 1) );
}
// Generate a tail call to invoke. This will cause the callvirt to return
// directly to the caller of the current method instead of actually coming
// back to the current method and returning. This will cause the value returned
// from the call to the COM server to be returned to the caller of this method.
il.Emit( OpCodes.Callvirt, DelegateInvokeMethod );
il.Emit( OpCodes.Ret );
// This is the label that will be jumped to if no delegate is present.
il.MarkLabel( ExitLabel );
AddReturn(ReturnType, il, Meth);
il.Emit( OpCodes.Ret );
}
private void AddReturn(Type ReturnType, ILGenerator il, MethodBuilder Meth)
{
// Place a dummy return value on the stack before we return.
if ( ReturnType == typeof(void) )
{
// There is nothing to place on the stack.
}
else if ( ReturnType.IsPrimitive )
{
switch (System.Type.GetTypeCode(ReturnType))
{
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
il.Emit( OpCodes.Ldc_I4_0 );
break;
case TypeCode.Int64:
case TypeCode.UInt64:
il.Emit( OpCodes.Ldc_I4_0 );
il.Emit( OpCodes.Conv_I8 );
break;
case TypeCode.Single:
il.Emit( OpCodes.Ldc_R4, 0 );
break;
case TypeCode.Double:
il.Emit( OpCodes.Ldc_R4, 0 );
il.Emit( OpCodes.Conv_R8 );
break;
default:
// "TypeCode" does not include IntPtr, so special case it.
if ( ReturnType == typeof(IntPtr) )
il.Emit( OpCodes.Ldc_I4_0 );
else
Contract.Assert(false, "Unexpected type for Primitive type.");
break;
}
}
else if ( ReturnType.IsValueType )
{
// Allocate stack space for the return value type. Zero-init.
Meth.InitLocals = true;
LocalBuilder ltRetVal = il.DeclareLocal( ReturnType );
// Load the value class on the stack.
il.Emit( OpCodes.Ldloc_S, ltRetVal );
}
else
{
// The return type is a normal type.
il.Emit( OpCodes.Ldnull );
}
}
private void DefineConstructor( TypeBuilder OutputTypeBuilder, FieldBuilder fbCookie, FieldBuilder[] afbDelegates )
{
// Retrieve the constructor info for the base classe's constructor.
ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, new Type[0], null );
Contract.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name);
// Define the default constructor.
MethodBuilder Cons = OutputTypeBuilder.DefineMethod( ".ctor",
MethodAttributes.Assembly | MethodAttributes.SpecialName,
CallingConventions.Standard,
null,
null);
ILGenerator il = Cons.GetILGenerator();
// Generate the code to call the constructor of the base class.
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Call, DefaultBaseClsCons );
// Generate the code to set the cookie field to 0.
il.Emit( OpCodes.Ldarg, (short)0 );
il.Emit( OpCodes.Ldc_I4, 0 );
il.Emit( OpCodes.Stfld, fbCookie );
// Generate the code to set all the delegates to NULL.
for ( int cDelegates = 0; cDelegates < afbDelegates.Length; cDelegates++ )
{
if (afbDelegates[cDelegates] != null)
{
il.Emit( OpCodes.Ldarg,(short)0 );
il.Emit( OpCodes.Ldnull );
il.Emit( OpCodes.Stfld, afbDelegates[cDelegates] );
}
}
// Emit the return opcode.
il.Emit( OpCodes.Ret );
}
private Type m_InputType;
private Type m_EventItfType;
private ModuleBuilder m_OutputModule;
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime.TypeSystem
{
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
[WellKnownType( "Microsoft_Zelig_Runtime_TypeSystem_VTable" )]
[DisableReferenceCounting]
public sealed class VTable
{
[AllowCompileTimeIntrospection]
[Flags]
public enum Shape : byte
{
Invalid = 0x00,
Scalar = ValueType | 0x01,
Struct = ValueType | 0x02,
Interface = Reference | 0x03,
Class = Reference | 0x04,
ArrayRoot = Reference | Array | 0x05,
SzArray = Reference | Array | 0x06,
MultiArray = Reference | Array | 0x07,
ValueType = 0x20,
Reference = 0x40,
Array = 0x80,
}
public struct InterfaceMap
{
public static readonly InterfaceMap[] SharedEmptyArray = new InterfaceMap[0];
//
// State
//
public VTable Interface;
public CodePointer[] MethodPointers;
}
//
// State
//
//
// The two size fields, BaseSize and ElementSize, are only copy of the corresponding values from TypeInfo.
// They are here for performance reasons (copying the values here removes one indirection).
// During heap walking, we need to compute the size of a block, to skip over it.
//
// This is done treating each object as if it were an array and computing the quantity:
//
// <size> = Vt.BaseSize + Vt.ElementSize * <array length>
//
// This works because arrays have an extra uint field at the start, holding the number of elements in the array.
// However, instances of non-array types will have random data at the offset of the Length field.
// This is not a problem, as long as we ensure that ElementSize is set to zero.
// Whatever the value of array length, the multiplication by zero will make it irrelevant.
//
[WellKnownField( "VTable_BaseSize" )] public uint BaseSize;
[WellKnownField( "VTable_ElementSize" )] public uint ElementSize;
[WellKnownField( "VTable_TypeInfo" )] public TypeRepresentation TypeInfo;
[WellKnownField( "VTable_GCInfo" )] public GCInfo GCInfo;
[WellKnownField( "VTable_Type" )] public Type Type;
[WellKnownField( "VTable_ShapeCategory" )] public Shape ShapeCategory;
//
// TODO: We need to embed these pointers in the VTable object itself.
// TODO: This way we can assume a fixed offset between MethodPointers and VTable and hardcode it in the method lookup code.
//
[WellKnownField( "VTable_MethodPointers" )] public CodePointer[] MethodPointers;
[WellKnownField( "VTable_InterfaceMap" )] public InterfaceMap[] InterfaceMethodPointers;
//
// Constructor Methods
//
public VTable( TypeRepresentation owner )
{
this.TypeInfo = owner;
this.InterfaceMethodPointers = InterfaceMap.SharedEmptyArray;
}
//--//
//
// Helper Methods
//
public static bool SameType( object a ,
object b )
{
return Get( a ) == Get( b );
}
//--//
public void ApplyTransformation( TransformationContext context )
{
context.Push( this );
context.Transform( ref this.BaseSize );
context.Transform( ref this.ElementSize );
context.Transform( ref this.TypeInfo );
context.Transform( ref this.GCInfo );
context.Transform( ref this.MethodPointers );
context.Pop();
}
//--//
//
// Access Methods
//
[WellKnownMethod( "VTable_Get" )]
[MethodImpl( MethodImplOptions.InternalCall )]
[DisableAutomaticReferenceCounting]
public extern static VTable Get( object a );
[WellKnownMethod( "VTable_GetInterface" )]
[DisableAutomaticReferenceCounting]
public static CodePointer[] GetInterface( object a ,
VTable vtblInterface )
{
VTable vtbl = Get( a );
InterfaceMap[] array = vtbl.InterfaceMethodPointers;
for(int i = 0; i < array.Length; i++)
{
if(Object.ReferenceEquals( array[i].Interface, vtblInterface ))
{
return array[i].MethodPointers;
}
}
return null;
}
[Inline]
public static VTable GetFromType( Type t )
{
return GetFromTypeHandle( t.TypeHandle );
}
[MethodImpl( MethodImplOptions.InternalCall )]
public extern static VTable GetFromTypeHandle( RuntimeTypeHandle hnd );
//--//
[Inline]
public bool CanBeAssignedFrom( VTable target )
{
if(this == target)
{
return true;
}
return CanBeAssignedFrom_Slow( target );
}
[NoInline]
private bool CanBeAssignedFrom_Slow( VTable source )
{
if(source.IsSubclassOf( this ))
{
return true;
}
if(this.IsArray && source.IsArray)
{
CHECKS.ASSERT( this.ShapeCategory == Shape.SzArray || this.ShapeCategory == Shape.MultiArray, "Found array that does not inherit from System.Array" );
if(this.ShapeCategory == source.ShapeCategory)
{
ArrayReferenceTypeRepresentation tdThis = (ArrayReferenceTypeRepresentation)this .TypeInfo;
ArrayReferenceTypeRepresentation tdSource = (ArrayReferenceTypeRepresentation)source.TypeInfo;
if(tdThis.SameShape( tdSource ))
{
TypeRepresentation subThis = tdThis .ContainedType.UnderlyingType;
TypeRepresentation subSource = tdSource.ContainedType.UnderlyingType;
VTable subVTableThis = subThis .VirtualTable;
VTable subVTableSource = subSource.VirtualTable;
if(subVTableThis == subVTableSource)
{
return true;
}
if(subVTableSource.IsValueType)
{
//
// We require exact matching for value types.
//
return false;
}
if(subVTableThis.IsInterface)
{
return subVTableSource.ImplementsInterface( subVTableThis );
}
return subVTableThis.CanBeAssignedFrom_Slow( subVTableSource );
}
}
}
return false;
}
[NoInline]
public bool IsSubclassOf( VTable target )
{
TypeRepresentation td = this.TypeInfo;
while(td != null)
{
if(target == td.VirtualTable)
{
return true;
}
td = td.Extends;
}
return false;
}
[NoInline]
public bool ImplementsInterface( VTable expectedItf )
{
VTable.InterfaceMap[] itfs = this.InterfaceMethodPointers;
for(int i = itfs.Length; --i >= 0; )
{
if(Object.ReferenceEquals( itfs[i].Interface, expectedItf ))
{
return true;
}
}
return false;
}
//
// Access Methods
//
public bool IsArray
{
[Inline]
get
{
return (this.ShapeCategory & Shape.Array) != 0;
}
}
public bool IsValueType
{
[Inline]
get
{
return (this.ShapeCategory & Shape.ValueType) != 0;
}
}
public bool IsInterface
{
[Inline]
get
{
return this.ShapeCategory == Shape.Interface;
}
}
//
// Debug Methods
//
public override string ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat( "VTable({0})", this.TypeInfo );
return sb.ToString();
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.TestingHost;
using Tester;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.CancellationTests
{
public class GrainCancellationTokenTests : OrleansTestingBase, IClassFixture<GrainCancellationTokenTests.Fixture>
{
private readonly Fixture fixture;
public class Fixture : BaseTestClusterFixture
{
protected override TestCluster CreateTestCluster()
{
return new TestCluster(new TestClusterOptions(2));
}
}
public GrainCancellationTokenTests(Fixture fixture)
{
this.fixture = fixture;
}
[Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")]
// [InlineData(0)] disabled until resolve of the https://github.com/dotnet/orleans/issues/1891
// [InlineData(10)]
[InlineData(300)]
public async Task GrainTaskCancellation(int delay)
{
var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid());
var tcs = new GrainCancellationTokenSource();
var grainTask = grain.LongWait(tcs.Token, TimeSpan.FromSeconds(10));
await Task.Delay(TimeSpan.FromMilliseconds(delay));
await tcs.Cancel();
await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask);
}
[Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")]
// [InlineData(0)]
// [InlineData(10)]
[InlineData(300)]
public async Task MultipleGrainsTaskCancellation(int delay)
{
var tcs = new GrainCancellationTokenSource();
var grainTasks = Enumerable.Range(0, 5)
.Select(i => this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid())
.LongWait(tcs.Token, TimeSpan.FromSeconds(10)))
.Select(task => Assert.ThrowsAsync<TaskCanceledException>(() => task)).ToList();
await Task.Delay(TimeSpan.FromMilliseconds(delay));
await tcs.Cancel();
await Task.WhenAll(grainTasks);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")]
public async Task TokenPassingWithoutCancellation_NoExceptionShouldBeThrown()
{
var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid());
var tcs = new GrainCancellationTokenSource();
try
{
await grain.LongWait(tcs.Token, TimeSpan.FromMilliseconds(1));
}
catch (Exception ex)
{
Assert.True(false, "Expected no exception, but got: " + ex.Message);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")]
public async Task PreCancelledTokenPassing()
{
var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid());
var tcs = new GrainCancellationTokenSource();
await tcs.Cancel();
var grainTask = grain.LongWait(tcs.Token, TimeSpan.FromSeconds(10));
await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")]
public async Task CancellationTokenCallbacksExecutionContext()
{
var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid());
var tcs = new GrainCancellationTokenSource();
var grainTask = grain.CancellationTokenCallbackResolve(tcs.Token);
await Task.Delay(TimeSpan.FromMilliseconds(100));
await tcs.Cancel();
var result = await grainTask;
Assert.Equal(true, result);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")]
public async Task CancellationTokenCallbacksTaskSchedulerContext()
{
var grains = await GetGrains<bool>(false);
var tcs = new GrainCancellationTokenSource();
var grainTask = grains.Item1.CallOtherCancellationTokenCallbackResolve(grains.Item2);
await tcs.Cancel();
var result = await grainTask;
Assert.Equal(true, result);
}
[Fact, TestCategory("Cancellation")]
public async Task CancellationTokenCallbacksThrow_ExceptionShouldBePropagated()
{
var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<bool>>(Guid.NewGuid());
var tcs = new GrainCancellationTokenSource();
var grainTask = grain.CancellationTokenCallbackThrow(tcs.Token);
await Task.Delay(TimeSpan.FromMilliseconds(100));
try
{
await tcs.Cancel();
}
catch (AggregateException ex)
{
Assert.True(ex.InnerException is InvalidOperationException, "Exception thrown has wrong type");
return;
}
Assert.True(false, "No exception was thrown");
}
[Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")]
// [InlineData(0)]
// [InlineData(10)]
[InlineData(300)]
public async Task InSiloGrainCancellation(int delay)
{
await GrainGrainCancellation(false, delay);
}
[Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")]
// [InlineData(0)]
// [InlineData(10)]
[InlineData(300)]
public async Task InterSiloGrainCancellation(int delay)
{
await GrainGrainCancellation(true, delay);
}
[Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")]
// [InlineData(0)]
// [InlineData(10)]
[InlineData(300)]
public async Task InterSiloClientCancellationTokenPassing(int delay)
{
await ClientGrainGrainTokenPassing(delay, true);
}
[Theory, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cancellation")]
// [InlineData(0)]
// [InlineData(10)]
[InlineData(300)]
public async Task InSiloClientCancellationTokenPassing(int delay)
{
await ClientGrainGrainTokenPassing(delay, false);
}
private async Task ClientGrainGrainTokenPassing(int delay, bool interSilo)
{
var grains = await GetGrains<bool>(interSilo);
var grain = grains.Item1;
var target = grains.Item2;
var tcs = new GrainCancellationTokenSource();
var grainTask = grain.CallOtherLongRunningTask(target, tcs.Token, TimeSpan.FromSeconds(10));
await Task.Delay(TimeSpan.FromMilliseconds(delay));
await tcs.Cancel();
await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask);
}
private async Task GrainGrainCancellation(bool interSilo, int delay)
{
var grains = await GetGrains<bool>(interSilo);
var grain = grains.Item1;
var target = grains.Item2;
var grainTask = grain.CallOtherLongRunningTaskWithLocalToken(target, TimeSpan.FromSeconds(10),
TimeSpan.FromMilliseconds(delay));
await Assert.ThrowsAsync<TaskCanceledException>(() => grainTask);
}
private async Task<Tuple<ILongRunningTaskGrain<T1>, ILongRunningTaskGrain<T1>>> GetGrains<T1>(bool placeOnDifferentSilos = true)
{
var grain = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<T1>>(Guid.NewGuid());
var instanceId = await grain.GetRuntimeInstanceId();
var target = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<T1>>(Guid.NewGuid());
var targetInstanceId = await target.GetRuntimeInstanceId();
var retriesCount = 0;
var retriesLimit = 10;
while ((placeOnDifferentSilos && instanceId.Equals(targetInstanceId))
|| (!placeOnDifferentSilos && !instanceId.Equals(targetInstanceId)))
{
if (retriesCount >= retriesLimit) throw new Exception("Could not make requested grains placement");
target = this.fixture.GrainFactory.GetGrain<ILongRunningTaskGrain<T1>>(Guid.NewGuid());
targetInstanceId = await target.GetRuntimeInstanceId();
retriesCount++;
}
return new Tuple<ILongRunningTaskGrain<T1>, ILongRunningTaskGrain<T1>>(grain, target);
}
}
}
| |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using System.ComponentModel;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NakedFramework.Menu;
using NakedObjects;
using NakedObjects.Services;
using NakedObjects.SystemTest;
using NUnit.Framework;
using Assert = NUnit.Framework.Assert;
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMember.Local
// ReSharper disable UnusedVariable
namespace NakedFramework.SystemTest.FrameworkTest;
/// <summary>
/// Tests various functions of the XATs themselves
/// </summary>
[TestFixture]
public class TestFunctions : AbstractSystemTest<XatDbContext> {
[SetUp]
public void SetUp() => StartTest();
[TearDown]
public void TearDown() => EndTest();
[OneTimeSetUp]
public void FixtureSetUp() {
XatDbContext.Delete();
var context = Activator.CreateInstance<XatDbContext>();
context.Database.Create();
InitializeNakedObjectsFramework(this);
}
[OneTimeTearDown]
public void FixtureTearDown() {
CleanupNakedObjectsFramework(this);
XatDbContext.Delete();
}
public enum TestEnum {
Value1,
Value2
}
protected override Type[] ObjectTypes => new[] { typeof(Object1), typeof(TestEnum) };
protected override Type[] Services => new[] { typeof(SimpleRepository<Object1>), typeof(MyService1), typeof(MyService2) };
[Test]
public virtual void IncorrectTitle() {
var obj1 = NewTestObject<Object1>();
try {
obj1.AssertTitleEquals("Yoda");
Assert.Fail("Should not get to here");
}
catch (Exception e) {
IsInstanceOfType(e, typeof(AssertFailedException));
Assert.AreEqual("Assert.IsTrue failed. Expected title 'Yoda' but got 'FooBar'", e.Message);
}
}
[Test]
public virtual void InvokeActionWithIncorrectParams() {
var obj1 = NewTestObject<Object1>();
try {
obj1.GetAction("Do Something").InvokeReturnObject(1, 2);
Assert.Fail("Should not get to here");
}
catch (Exception e) {
Assert.AreEqual("Cast error on method: Object1 DoSomething(Int32, System.String) : Unable to cast object of type 'System.Int32' to type 'System.String'.", e.Message);
}
}
[Test]
public virtual void TestActionAssertHasFriendlyName() {
var obj = NewTestObject<Object1>();
obj.GetActionById("ActionNumber1").AssertHasFriendlyName("Action Number1");
obj.GetActionById("ActionNumber2").AssertHasFriendlyName("Action Two");
}
[Test]
public virtual void TestEnumDefault() {
var obj = NewTestObject<Object1>();
var a1 = obj.GetAction("Do Something Else");
var p1 = a1.Parameters.First();
var p2 = a1.Parameters.Last();
var def1 = p1.GetDefault();
var def2 = p2.GetDefault();
Assert.AreEqual(TestEnum.Value2, def1.NakedObject.Object);
Assert.AreEqual(null, def2);
}
[Test]
public virtual void TestGetAction() {
var obj = NewTestObject<Object1>();
var a1 = obj.GetAction("Action Number1");
Assert.IsNotNull(a1);
var a2 = obj.GetAction("Action Two");
Assert.IsNotNull(a2);
try {
obj.GetAction("ActionNumber1");
Assert.Fail("Shouldn't get to here!");
}
catch (Exception e) {
Assert.AreEqual("Assert.Fail failed. No Action named 'ActionNumber1'", e.Message);
}
//Now with params
var a3 = obj.GetAction("Action Number3", typeof(string), typeof(int));
Assert.IsNotNull(a3);
a3 = obj.GetAction("Action Number3"); //Params not necessary
Assert.IsNotNull(a3);
//And with wrong param types
try {
obj.GetAction("Action Number3", typeof(int), typeof(string)); //wrong way round!
Assert.Fail("Shouldn't get to here!");
}
catch (Exception e) {
Assert.AreEqual("Assert.Fail failed. No Action named 'Action Number3' (with specified parameters)", e.Message);
}
//Now from sub-menu, with & without params
obj.GetAction("Action Number4", "Sub1");
obj.GetAction("Action Number4", "Sub1", typeof(string), typeof(int));
obj.GetAction("Action Number4"); //works without specifying sub-menu
obj.GetAction("Action Number4", typeof(string), typeof(int));
//With wrong sub-menu
try {
obj.GetAction("Action Number4", "Sub2", typeof(string), typeof(int));
Assert.Fail("Shouldn't get to here!");
}
catch (Exception e) {
Assert.AreEqual("Assert.IsNotNull failed. No menu item with name: Sub2", e.Message);
}
//With right sub-menu & wrong params
try {
obj.GetAction("Action Number4", "Sub1", typeof(int), typeof(string));
Assert.Fail("Shouldn't get to here!");
}
catch (Exception e) {
Assert.AreEqual("Assert.IsTrue failed. Parameter Types do not match for action: Action Number4", e.Message);
}
}
[Test]
public virtual void TestGetActionById() {
var obj = NewTestObject<Object1>();
var a1 = obj.GetActionById("ActionNumber1");
Assert.IsNotNull(a1);
var a2 = obj.GetActionById("ActionNumber2");
Assert.IsNotNull(a2);
try {
obj.GetActionById("Action Number1");
Assert.Fail("Shouldn't get to here!");
}
catch (Exception e) {
Assert.AreEqual("Assert.Fail failed. No Action named 'Action Number1' (as method name)", e.Message);
}
//Now with params
var a3 = obj.GetActionById("ActionNumber3", typeof(string), typeof(int));
Assert.IsNotNull(a3);
a3 = obj.GetActionById("ActionNumber3"); //Params not necessary
Assert.IsNotNull(a3);
//And with wrong param types
try {
obj.GetActionById("ActionNumber3", typeof(int), typeof(string)); //wrong way round!
Assert.Fail("Shouldn't get to here!");
}
catch (Exception e) {
Assert.AreEqual("Assert.Fail failed. No Action named 'ActionNumber3' (as method name & with specified parameters)", e.Message);
}
//Now from sub-menu, with & without params
obj.GetActionById("ActionNumber4", "Sub1");
obj.GetActionById("ActionNumber4", "Sub1", typeof(string), typeof(int));
obj.GetActionById("ActionNumber4"); //works without specifying sub-menu
obj.GetActionById("ActionNumber4", typeof(string), typeof(int));
//With wrong sub-menu
try {
obj.GetActionById("ActionNumber4", "Sub2", typeof(string), typeof(int));
Assert.Fail("Shouldn't get to here!");
}
catch (Exception e) {
Assert.AreEqual("Assert.IsNotNull failed. No menu item with name: Sub2", e.Message);
}
//With right sub-menu & wrong params
try {
obj.GetActionById("ActionNumber4", "Sub1", typeof(int), typeof(string));
Assert.Fail("Shouldn't get to here!");
}
catch (Exception e) {
Assert.AreEqual("Assert.IsTrue failed. Parameter Types do not match for action with method name: ActionNumber4", e.Message);
}
}
[Test]
public virtual void TestGetProperty() {
var culture = Thread.CurrentThread.CurrentCulture;
try {
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var obj = NewTestObject<Object1>();
obj.GetPropertyByName("Prop1");
obj.GetPropertyByName("Bar");
obj.GetPropertyById("Prop1");
obj.GetPropertyById("Prop2");
try {
obj.GetPropertyById("Bar");
Assert.Fail("Shouldn't get to here!");
}
catch (Exception e) {
Assert.AreEqual("Assert.Fail failed. No Property with Id 'Bar'", e.Message);
}
try {
obj.GetPropertyByName("Prop4");
Assert.Fail("Shouldn't get to here!");
}
catch (Exception e) {
Assert.AreEqual("Assert.Fail failed. No Property named 'Prop4'", e.Message);
}
}
finally {
Thread.CurrentThread.CurrentCulture = culture;
}
}
[Test]
public virtual void TestGetTestService() {
GetTestService("My Service1");
GetTestService("Service Two");
//Get nonexistent service
try {
GetTestService("My Service3");
Assert.Fail("Should not get to here");
}
catch (Exception e) {
IsInstanceOfType(e, typeof(AssertFailedException));
Assert.AreEqual("Assert.Fail failed. No such service: My Service3", e.Message);
}
//Get service by real name that has been overriden
try {
GetTestService("MyService2");
Assert.Fail("Should not get to here");
}
catch (Exception e) {
IsInstanceOfType(e, typeof(AssertFailedException));
Assert.AreEqual("Assert.Fail failed. No such service: MyService2", e.Message);
}
GetTestService(typeof(MyService1));
GetTestService<MyService2>();
//Get nonexistent service
try {
GetTestService<MyService3>();
Assert.Fail("Should not get to here");
}
catch (Exception e) {
IsInstanceOfType(e, typeof(AssertFailedException));
Assert.AreEqual("Assert.Fail failed. No service of type NakedFramework.SystemTest.FrameworkTest.TestFunctions+MyService3", e.Message);
}
}
[Test]
public virtual void TestPropertyValue() {
var culture = Thread.CurrentThread.CurrentCulture;
try {
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var obj = NewTestObject<Object1>();
obj.GetPropertyById("Prop3").SetValue("08/16/2013");
var p1 = obj.GetPropertyById("Prop3");
p1.AssertValueIsEqual("08/16/2013 00:00:00");
p1.AssertTitleIsEqual("08/16/2013");
}
finally {
Thread.CurrentThread.CurrentCulture = culture;
}
}
[Test]
public virtual void TestReturnString() {
var obj = NewTestObject<Object1>();
var a1 = obj.GetAction("Do Return String");
var res = a1.InvokeReturnObject();
Assert.AreEqual("a string", res.NakedObject.Object);
a1.Invoke();
}
[Test]
public virtual void TestTooFewParms() {
var obj = NewTestObject<Object1>();
var a1 = obj.GetAction("Do Something");
try {
var res = a1.InvokeReturnObject();
Assert.Fail("expect exception");
}
catch (Exception expected) {
Assert.AreEqual("Assert.IsTrue failed. Action 'Do Something' is unusable: wrong number of parameters, got 0, expect 2", expected.Message);
}
}
[Test]
public virtual void VisiblePropertyHasSameNameAsHiddenProperty() {
var obj1 = NewTestObject<Object1>();
try {
var foo = obj1.GetPropertyByName("Foo");
Assert.Fail("Should not get to here");
}
catch (Exception e) {
IsInstanceOfType(e, typeof(AssertFailedException));
Assert.AreEqual("Assert.Fail failed. More than one Property named 'Foo'", e.Message);
}
}
public class MyService1 { }
[DisplayName("Service Two")]
public class MyService2 { }
//Not registered as a service
public class MyService3 { }
public class Object1 {
[DefaultValue(8)]
public int Prop1 { get; set; }
[DisplayName("Foo")]
public string Prop2 { get; set; }
[Mask("d")]
public DateTime Prop3 { get; set; } = new(2013, 8, 16);
[DisplayName("Bar")]
public string Prop4 { get; set; }
[Hidden(WhenTo.Always)]
public string Foo { get; set; }
public IDomainObjectContainer Container { set; protected get; }
public static void Menu(IMenu menu) {
menu.CreateSubMenu("Sub1").AddAction("ActionNumber4");
}
public string Title() {
var t = Container.NewTitleBuilder();
t.Append("FooBar");
return t.ToString();
}
public Object1 DoSomething([DefaultValue(8)] int param0, [DefaultValue("Foo")] string param1) => null;
public Object1 DoSomethingElse([DefaultValue(TestEnum.Value2)] TestEnum param0, TestEnum param1) => null;
public string DoReturnString() => "a string";
public void ActionNumber1() { }
[DisplayName("Action Two")]
public void ActionNumber2() { }
public void ActionNumber3(string p1, int p2) { }
public void ActionNumber4(string p1, int p2) { }
}
}
#region Classes used by tests
public class XatDbContext : DbContext {
public const string DatabaseName = "TestXats";
private static readonly string Cs = @$"Data Source={Constants.Server};Initial Catalog={DatabaseName};Integrated Security=True;";
public XatDbContext() : base(Cs) { }
public static void Delete() => Database.Delete(Cs);
}
#endregion
| |
using UnityEngine;
using System.Collections;
public class GUIManager : MonoBehaviour {
public GUIElement[] elements;
public Vector2 standardSize = new Vector2(1720, 1080);
public Rect unitGraphic = new Rect (0, 0, 0, 0);
public Vector2 UColumnsXRows = new Vector2(10, 5);
public Vector2 unitBDisp = new Vector2(5, 10);
public bool universalBuild = false;
public Rect buildButtonSize = new Rect(50, 900, 75, 75);
public Vector2 BColumnsXRows = new Vector2(10, 5);
public Vector2 buildingBDisp = new Vector2(80, 100);
public Rect resourceSize = new Rect(0, 0, 100, 50);
public Vector2 RColumnsXRows = new Vector2(10, 5);
public Vector2 resourceBDisp = new Vector2(80, 100);
public Rect miniMapSize = new Rect(1520, 880, 200, 200);
BuildingPlacement place;
UnitSelection select;
[HideInInspector]
public Group group;
ResourceManager resourceManager;
Vector2 ratio;
Vector2 lastWindowSize = Vector2.zero;
void OnDrawGizmos () {
if(gameObject.name != "Player Manager"){
gameObject.name = "Player Manager";
}
}
void Start () {
if(place == null){
place = gameObject.GetComponent<BuildingPlacement>();
}
if(select == null){
select = gameObject.GetComponent<UnitSelection>();
}
if(resourceManager == null){
resourceManager = gameObject.GetComponent<ResourceManager>();
}
ReconfigureWindows();
}
void ReconfigureWindows (){
ratio = new Vector2 (Screen.width / standardSize.x, Screen.height / standardSize.y);
GameObject.Find("MiniMap").GetComponent<MiniMap>().localBounds = new Rect(ratio.x*miniMapSize.x, ratio.y*miniMapSize.y, ratio.x*miniMapSize.width, ratio.y*miniMapSize.height);
GameObject.Find("MiniMap").GetComponent<MiniMap>().SetSize();
select.ResizeSelectionWindow(ratio);
lastWindowSize = new Vector2(Screen.width, Screen.height);
Debug.Log("Reconfiguring Windows");
}
void Update () {
Vector2 windowSize = new Vector2(Screen.width, Screen.height);
if(lastWindowSize != windowSize){
ReconfigureWindows();
}
}
void OnGUI () {
useGUILayout = false;
GUI.depth = 10;
for(int x = 0; x < elements.Length; x++){
elements[x].Display(ratio);
}
// Create Building
if(universalBuild){
DisplayBuild();
}
else{
bool canBuild = false;
bool[] buildingCanBuild = new bool[group.buildingList.Length];
for(int x = 0; x < select.curSelectedLength; x++){
UnitController cont = select.curSelectedS[x];
if(cont.build.builderUnit){
for(int a = 0; a < cont.build.build.Length; a++){
if(!buildingCanBuild[a]){
if(cont.build.build[a].canBuild){
buildingCanBuild[a] = true;
}
}
}
canBuild = true;
}
}
if(canBuild){
DisplayBuild(buildingCanBuild);
}
}
// Resource
int y = 0;
int z = 0;
for(int x = 0; x < resourceManager.resourceTypes.Length; x++){
// Displays the Resource and the Amount
GUI.Box(new Rect((resourceSize.x+y*resourceBDisp.x)*ratio.x, (resourceSize.y+z*resourceBDisp.y)*ratio.y,
(resourceSize.width)*ratio.x, (resourceSize.height)*ratio.y),
resourceManager.resourceTypes[x].name + " : " + resourceManager.resourceTypes[x].amount);
y = y + 1;
if(y >= RColumnsXRows.x){
y = 0;
z++;
if(z >= RColumnsXRows.y){
break;
}
}
}
y = 0;
z = 0;
// UnitController
for(int x = 0; x < select.curSelectedLength; x++){
if(GUI.Button(new Rect((unitGraphic.x+(y*unitBDisp.x))*ratio.x, (unitGraphic.y+(z*unitBDisp.y))*ratio.y, unitGraphic.width*ratio.x, unitGraphic.height*ratio.y), "")){
select.Select(x, "Unit");
}
if(select.curSelectedS[x].gui.image){
GUI.DrawTexture(new Rect((unitGraphic.x+(y*unitBDisp.x))*ratio.x, (unitGraphic.y+(z*unitBDisp.y))*ratio.y, unitGraphic.width*ratio.x, unitGraphic.height*ratio.y), select.curSelectedS[x].gui.image);
}
y++;
if(y >= UColumnsXRows.x){
y = 0;
z++;
if(z >= UColumnsXRows.y){
break;
}
}
}
for(int x = 0; x < select.curBuildSelectedLength; x++){
if(GUI.Button(new Rect((unitGraphic.x+(y*unitBDisp.x))*ratio.x, (unitGraphic.y+(z*unitBDisp.y))*ratio.y, unitGraphic.width*ratio.x, unitGraphic.height*ratio.y), "")){
select.Select(x, "Build");
}
GUI.DrawTexture(new Rect((unitGraphic.x+(y*unitBDisp.x))*ratio.x, (unitGraphic.y+(z*unitBDisp.y))*ratio.y, unitGraphic.width*ratio.x, unitGraphic.height*ratio.y), select.curBuildSelectedS[x].gui.image);
y++;
if(y >= UColumnsXRows.x){
y = 0;
z++;
if(z >= UColumnsXRows.y){
break;
}
}
}
// Building
if(select.curBuildSelectedLength > 0){
select.curBuildSelectedS[0].DisplayGUI(ratio.x, ratio.y);
}
}
public void DisplayBuild (){
Vector2 ratio = new Vector2 (Screen.width / standardSize.x, Screen.height / standardSize.y);
int y = 0;
int z = 0;
for(int x = 0; x < group.buildingList.Length; x++){
if(group.buildingList[x].obj){
// Displays the Building Name
if(GUI.Button(new Rect((buildButtonSize.x+y*buildingBDisp.x)*ratio.x, (buildButtonSize.y+z*buildingBDisp.y)*ratio.y,
buildButtonSize.width*ratio.x, buildButtonSize.height*ratio.y), group.buildingList[x].obj.GetComponent<BuildingController>().name)){
place.BeginPlace(group.buildingList[x]);
}
y = y + 1;
if(y >= BColumnsXRows.x){
y = 0;
z++;
if(z >= BColumnsXRows.y){
break;
}
}
}
}
}
public void DisplayBuild (bool[] canBuild){
Vector2 ratio = new Vector2 (Screen.width / standardSize.x, Screen.height / standardSize.y);
int y = 0;
int z = 0;
for(int x = 0; x < group.buildingList.Length; x++){
if(group.buildingList[x].obj && canBuild[x]){
// Displays the Building Name
if(GUI.Button(new Rect((buildButtonSize.x+y*buildingBDisp.x)*ratio.x, (buildButtonSize.y+z*buildingBDisp.y)*ratio.y,
buildButtonSize.width*ratio.x, buildButtonSize.height*ratio.y), group.buildingList[x].obj.GetComponent<BuildingController>().name)){
place.BeginPlace(group.buildingList[x]);
}
y = y + 1;
if(y >= BColumnsXRows.x){
y = 0;
z++;
if(z >= BColumnsXRows.y){
break;
}
}
}
}
}
}
| |
using System.Diagnostics;
using System;
using System.Management;
using System.Collections;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Web.UI.Design;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net.Mail;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
namespace SoftLogik.Mail
{
namespace Mail
{
namespace Pop3
{
// Supporting classes and structs
// ==============================
/// <summary>
/// Combines Email ID with Email UID for one email
/// The POP3 server assigns to each message a unique Email UID, which will not change for the life time
/// of the message and no other message should use the same.
///
/// Exceptions:
/// Throws Pop3Exception if there is a serious communication problem with the POP3 server, otherwise
///
/// </summary>
public struct EmailUid
{
/// <summary>
/// used in POP3 commands to indicate which message (only valid in the present session)
/// </summary>
public int EmailId;
/// <summary>
/// Uid is always the same for a message, regardless of session
/// </summary>
public string Uid;
/// <summary>
///
/// </summary>
/// <param name="EmailId"></param>
/// <param name="Uid"></param>
public EmailUid(int EmailId, string Uid)
{
this.EmailId = EmailId;
this.Uid = Uid;
}
}
/// <summary>
/// If anything goes wrong within Pop3MailClient, a Pop3Exception is raised
/// </summary>
public class Pop3Exception : ApplicationException
{
/// <summary>
///
/// </summary>
public Pop3Exception()
{
}
/// <summary>
///
/// </summary>
/// <param name="ErrorMessage"></param>
public Pop3Exception(string ErrorMessage) : base(ErrorMessage)
{
}
}
/// <summary>
/// A pop 3 connection goes through the following states:
/// </summary>
public enum Pop3ConnectionStateEnum
{
/// <summary>
/// undefined
/// </summary>
None = 0,
/// <summary>
/// not connected yet to POP3 server
/// </summary>
Disconnected,
/// <summary>
/// TCP connection has been opened and the POP3 server has sent the greeting. POP3 server expects user name and password
/// </summary>
Authorization,
/// <summary>
/// client has identified itself successfully with the POP3, server has locked all messages
/// </summary>
Connected,
/// <summary>
/// QUIT command was sent, the server has deleted messages marked for deletion and released the resources
/// </summary>
Closed
}
// Delegates for Pop3MailClient
// ============================
/// <summary>
/// If POP3 Server doesn't react as expected or this code has a problem, but
/// can continue with the execution, a Warning is called.
/// </summary>
/// <param name="WarningText"></param>
/// <param name="Response">string received from POP3 server</param>
public delegate void WarningHandler(string WarningText, string Response);
/// <summary>
/// Traces all the information exchanged between POP3 client and POP3 server plus some
/// status messages from POP3 client.
/// Helpful to investigate any problem.
/// Console.WriteLine() can be used
/// </summary>
/// <param name="TraceText"></param>
public delegate void TraceHandler(string TraceText);
// Pop3MailClient Class
// ====================
/// <summary>
/// provides access to emails on a POP3 Server
/// </summary>
public class Pop3MailClient
{
//Events
//------
/// <summary>
/// Called whenever POP3 server doesn't react as expected, but no runtime error is thrown.
/// </summary>
private WarningHandler WarningEvent;
public event WarningHandler Warning
{
add
{
WarningEvent = (WarningHandler) System.Delegate.Combine(WarningEvent, value);
}
remove
{
WarningEvent = (WarningHandler) System.Delegate.Remove(WarningEvent, value);
}
}
/// <summary>
/// call warning event
/// </summary>
/// <param name="methodName">name of the method where warning is needed</param>
/// <param name="response">answer from POP3 server causing the warning</param>
/// <param name="warningText">explanation what went wrong</param>
/// <param name="warningParameters"></param>
protected void CallWarning(string methodName, string response, string warningText, params object[] warningParameters)
{
warningText = string.Format(warningText, warningParameters);
if (WarningEvent != null)
{
if (WarningEvent != null)
WarningEvent(methodName + ": " + warningText, response);
}
CallTrace("!! {0}", warningText);
}
/// <summary>
/// Shows the communication between PopClient and PopServer, including warnings
/// </summary>
private TraceHandler TraceEvent;
public event TraceHandler Trace
{
add
{
TraceEvent = (TraceHandler) System.Delegate.Combine(TraceEvent, value);
}
remove
{
TraceEvent = (TraceHandler) System.Delegate.Remove(TraceEvent, value);
}
}
/// <summary>
/// call Trace event
/// </summary>
/// <param name="text">string to be traced</param>
/// <param name="parameters"></param>
protected void CallTrace(string text, params object[] parameters)
{
if (TraceEvent != null)
{
if (TraceEvent != null)
TraceEvent(DateTime.Now.ToString("hh:mm:ss ") + PopServer + " " + string.Format(text, parameters));
}
}
/// <summary>
/// Trace information received from POP3 server
/// </summary>
/// <param name="text">string to be traced</param>
/// <param name="parameters"></param>
protected void TraceFrom(string text, params object[] parameters)
{
if (TraceEvent != null)
{
CallTrace(" " + string.Format(text, parameters), null);
}
}
//Properties
//----------
/// <summary>
/// Get POP3 server name
/// </summary>
public string PopServer
{
get
{
return m_popServer;
}
}
/// <summary>
/// POP3 server name
/// </summary>
protected string m_popServer;
/// <summary>
/// Get POP3 server port
/// </summary>
public int Port
{
get
{
return m_port;
}
}
/// <summary>
/// POP3 server port
/// </summary>
protected int m_port;
/// <summary>
/// Should SSL be used for connection with POP3 server
/// </summary>
public bool UseSSL
{
get
{
return m_useSSL;
}
}
/// <summary>
/// Should SSL be used for connection with POP3 server
/// </summary>
private bool m_useSSL;
/// <summary>
/// should Pop3MailClient automatically reconnect if POP3 server has dropped the
/// connection due to a timeout
/// </summary>
public bool IsAutoReconnect
{
get
{
return n_isAutoReconnect;
}
set
{
n_isAutoReconnect = value;
}
}
private bool n_isAutoReconnect = false;
//timeout has occured, we try to perform an autoreconnect
private bool isTimeoutReconnect = false;
/// <summary>
/// Get / set read timeout (miliseconds)
/// </summary>
public int ReadTimeout
{
get
{
return System.Convert.ToInt32(m_readTimeout == 0 ? System.Threading.Timeout.Infinite : m_readTimeout);
}
set
{
m_readTimeout = value;
if (pop3Stream != null&& pop3Stream.CanTimeout)
{
pop3Stream.ReadTimeout = m_readTimeout;
}
}
}
/// <summary>
/// POP3 server read timeout
/// </summary>
protected int m_readTimeout = - 1;
/// <summary>
/// Get owner name of mailbox on POP3 server
/// </summary>
public string Username
{
get
{
return m_username;
}
}
/// <summary>
/// Owner name of mailbox on POP3 server
/// </summary>
protected string m_username;
/// <summary>
/// Get password for mailbox on POP3 server
/// </summary>
public string Password
{
get
{
return m_password;
}
}
/// <summary>
/// Password for mailbox on POP3 server
/// </summary>
protected string m_password;
/// <summary>
/// Get connection status with POP3 server
/// </summary>
public Pop3ConnectionStateEnum Pop3ConnectionState
{
get
{
return m_pop3ConnectionState;
}
}
/// <summary>
/// connection status with POP3 server
/// </summary>
protected Pop3ConnectionStateEnum m_pop3ConnectionState = Pop3ConnectionStateEnum.Disconnected;
// Methods
// -------
/// <summary>
/// set POP3 connection state
/// </summary>
/// <param name="State"></param>
protected void setPop3ConnectionState(Pop3ConnectionStateEnum State)
{
m_pop3ConnectionState = State;
CallTrace(" Pop3MailClient Connection State {0} reached", State);
}
/// <summary>
/// throw exception if POP3 connection is not in the required state
/// </summary>
/// <param name="requiredState"></param>
protected void EnsureState(Pop3ConnectionStateEnum requiredState)
{
if (m_pop3ConnectionState != requiredState)
{
// wrong connection state
throw (new Pop3Exception("GetMailboxStats only accepted during connection state: " + requiredState.ToString() + Environment.NewLine+ " The connection to server " + PopServer + " is in state " + Pop3ConnectionState.ToString()));
}
}
//private fields
//--------------
/// <summary>
/// TCP to POP3 server
/// </summary>
private TcpClient serverTcpConnection;
/// <summary>
/// Stream from POP3 server with or without SSL
/// </summary>
private Stream pop3Stream;
/// <summary>
/// Reader for POP3 message
/// </summary>
protected StreamReader pop3StreamReader;
/// <summary>
/// char 'array' for carriage return / line feed
/// </summary>
protected string CRLF = Environment.NewLine;
//public methods
//--------------
/// <summary>
/// Make POP3 client ready to connect to POP3 server
/// </summary>
/// <param name="PopServer"><example>pop.gmail.com</example></param>
/// <param name="Port"><example>995</example></param>
/// <param name="useSSL">True: SSL is used for connection to POP3 server</param>
/// <param name="Username"><example>abc@gmail.com</example></param>
/// <param name="Password">Secret</param>
public Pop3MailClient(string PopServer, int Port, bool useSSL, string Username, string Password)
{
this.m_popServer = PopServer;
this.m_port = Port;
this.m_useSSL = useSSL;
this.m_username = Username;
this.m_password = Password;
}
/// <summary>
/// Connect to POP3 server
/// </summary>
public void Connect()
{
if (Pop3ConnectionState != Pop3ConnectionStateEnum.Disconnected && Pop3ConnectionState != Pop3ConnectionStateEnum.Closed && (! isTimeoutReconnect))
{
CallWarning("connect", "", "Connect command received, but connection state is: " + Pop3ConnectionState.ToString(), null);
}
else
{
//establish TCP connection
try
{
CallTrace(" Connect at port {0}", Port);
serverTcpConnection = new TcpClient(PopServer, Port);
}
catch (System.Exception ex)
{
throw (new Pop3Exception("Connection to server " + PopServer + ", port " + Port + " failed." + Environment.NewLine+ "Runtime Error: " + ex.ToString()));
}
if (UseSSL)
{
//get SSL stream
try
{
CallTrace(" Get SSL connection", null);
pop3Stream = new SslStream(serverTcpConnection.GetStream(), false);
pop3Stream.ReadTimeout = ReadTimeout;
}
catch (System.Exception ex)
{
throw (new Pop3Exception("Server " + PopServer + " found, but cannot get SSL data stream." + Environment.NewLine+ "Runtime Error: " + ex.ToString()));
}
//perform SSL authentication
try
{
CallTrace(" Get SSL authentication", null);
((SslStream) pop3Stream).AuthenticateAsClient(PopServer);
}
catch (System.Exception ex)
{
throw (new Pop3Exception("Server " + PopServer + " found, but problem with SSL Authentication." + Environment.NewLine+ "Runtime Error: " + ex.ToString()));
}
}
else
{
//create a stream to POP3 server without using SSL
try
{
CallTrace(" Get connection without SSL", null);
pop3Stream = serverTcpConnection.GetStream();
pop3Stream.ReadTimeout = ReadTimeout;
}
catch (System.Exception ex)
{
throw (new Pop3Exception("Server " + PopServer + " found, but cannot get data stream (without SSL)." + Environment.NewLine+ "Runtime Error: " + ex.ToString()));
}
}
//get stream for reading from pop server
//POP3 allows only US-ASCII. The message will be translated in the proper encoding in a later step
try
{
pop3StreamReader = new StreamReader(pop3Stream, Encoding.ASCII);
}
catch (System.Exception ex)
{
if (UseSSL)
{
throw (new Pop3Exception("Server " + PopServer + " found, but cannot read from SSL stream." + Environment.NewLine+ "Runtime Error: " + ex.ToString()));
}
else
{
throw (new Pop3Exception("Server " + PopServer + " found, but cannot read from stream (without SSL)." + Environment.NewLine+ "Runtime Error: " + ex.ToString()));
}
}
//ready for authorisation
string response = string.Empty;
if (! readSingleLine(ref response))
{
throw (new Pop3Exception("Server " + PopServer + " not ready to start AUTHORIZATION." + Environment.NewLine+ "Message: " + response));
}
setPop3ConnectionState(Pop3ConnectionStateEnum.Authorization);
//send user name
if (! executeCommand("USER " + Username, ref response))
{
throw (new Pop3Exception("Server " + PopServer + " doesn\'t accept username \'" + Username + "\'." + Environment.NewLine+ "Message: " + response));
}
//send password
if (! executeCommand("PASS " + Password, ref response))
{
throw (new Pop3Exception("Server " + PopServer + " doesn\'t accept password \'" + Password + "\' for user \'" + Username + "\'." + Environment.NewLine+ "Message: " + response));
}
setPop3ConnectionState(Pop3ConnectionStateEnum.Connected);
}
}
/// <summary>
/// Disconnect from POP3 Server
/// </summary>
public void Disconnect()
{
if (Pop3ConnectionState == Pop3ConnectionStateEnum.Disconnected || Pop3ConnectionState == Pop3ConnectionStateEnum.Closed)
{
CallWarning("disconnect", "", "Disconnect received, but was already disconnected.", null);
}
else
{
//ask server to end session and possibly to remove emails marked for deletion
try
{
string response = string.Empty;
if (executeCommand("QUIT", ref response))
{
//server says everything is ok
setPop3ConnectionState(Pop3ConnectionStateEnum.Closed);
}
else
{
//server says there is a problem
CallWarning("Disconnect", response, "negative response from server while closing connection: " + response, null);
setPop3ConnectionState(Pop3ConnectionStateEnum.Disconnected);
}
}
finally
{
//close connection
if (pop3Stream != null)
{
pop3Stream.Close();
}
pop3StreamReader.Close();
}
}
}
/// <summary>
/// Delete message from server.
/// The POP3 server marks the message as deleted. Any future
/// reference to the message-number associated with the message
/// in a POP3 command generates an error. The POP3 server does
/// not actually delete the message until the POP3 session
/// enters the UPDATE state.
/// </summary>
/// <param name="msg_number"></param>
/// <returns></returns>
public bool DeleteEmail(int msg_number)
{
EnsureState(Pop3ConnectionStateEnum.Connected);
string response = string.Empty;
if (! executeCommand("DELE " + msg_number.ToString(), ref response))
{
CallWarning("DeleteEmail", response, "negative response for email (Id: {0}) delete request", msg_number);
return false;
}
return true;
}
/// <summary>
/// Get a list of all Email IDs available in mailbox
/// </summary>
/// <returns></returns>
public bool GetEmailIdList(ref List<int> EmailIds)
{
EnsureState(Pop3ConnectionStateEnum.Connected);
EmailIds = new List<int>();
//get server response status line
string response = string.Empty;
if (! executeCommand("LIST", ref response))
{
CallWarning("GetEmailIdList", response, "negative response for email list request", null);
return false;
}
//get every email id
int EmailId;
while (readMultiLine(ref response))
{
if (int.TryParse(response.Split(' ')[0], out EmailId))
{
EmailIds.Add(EmailId);
}
else
{
CallWarning("GetEmailIdList", response, "first characters should be integer (EmailId)", null);
}
}
TraceFrom("{0} email ids received", EmailIds.Count);
return true;
}
/// <summary>
/// get size of one particular email
/// </summary>
/// <param name="msg_number"></param>
/// <returns></returns>
public int GetEmailSize(int msg_number)
{
EnsureState(Pop3ConnectionStateEnum.Connected);
string response = string.Empty;
executeCommand("LIST " + msg_number.ToString(), ref response);
int EmailSize = 0;
string[] responseSplit = response.Split(' ');
if (responseSplit.Length < 2 || (! int.TryParse(responseSplit[2], out EmailSize)))
{
CallWarning("GetEmailSize", response, "\'+OK int int\' format expected (EmailId, EmailSize)", null);
}
return EmailSize;
}
/// <summary>
/// Get a list with the unique IDs of all Email available in mailbox.
///
/// Explanation:
/// EmailIds for the same email can change between sessions, whereas the unique Email id
/// never changes for an email.
/// </summary>
/// <param name="EmailIds"></param>
/// <returns></returns>
public bool GetUniqueEmailIdList(ref List<EmailUid> EmailIds)
{
EnsureState(Pop3ConnectionStateEnum.Connected);
EmailIds = new List<EmailUid>();
//get server response status line
string response = string.Empty;
if (! executeCommand("UIDL ", ref response))
{
CallWarning("GetUniqueEmailIdList", response, "negative response for email list request", null);
return false;
}
//get every email unique id
int EmailId;
while (readMultiLine(ref response))
{
string[] responseSplit = response.Split(' ');
if (responseSplit.Length < 2)
{
CallWarning("GetUniqueEmailIdList", response, "response not in format \'int string\'", null);
}
else if (! int.TryParse(responseSplit[0], out EmailId))
{
CallWarning("GetUniqueEmailIdList", response, "first charaters should be integer (Unique EmailId)", null);
}
else
{
EmailIds.Add(new EmailUid(EmailId, responseSplit[1]));
}
}
TraceFrom("{0} unique email ids received", EmailIds.Count);
return true;
}
/// <summary>
/// get a list with all currently available messages and the UIDs
/// </summary>
/// <param name="EmailIds">EmailId Uid list</param>
/// <returns>false: server sent negative response (didn't send list)</returns>
public bool GetUniqueEmailIdList(ref SortedList<string, int> EmailIds)
{
EnsureState(Pop3ConnectionStateEnum.Connected);
EmailIds = new SortedList<string, int>();
//get server response status line
string response = string.Empty;
if (! executeCommand("UIDL", ref response))
{
CallWarning("GetUniqueEmailIdList", response, "negative response for email list request", null);
return false;
}
//get every email unique id
int EmailId;
while (readMultiLine(ref response))
{
string[] responseSplit = response.Split(' ');
if (responseSplit.Length < 2)
{
CallWarning("GetUniqueEmailIdList", response, "response not in format \'int string\'", null);
}
else if (! int.TryParse(responseSplit[0], out EmailId))
{
CallWarning("GetUniqueEmailIdList", response, "first charaters should be integer (Unique EmailId)", null);
}
else
{
EmailIds.Add(responseSplit[1], EmailId);
}
}
TraceFrom("{0} unique email ids received", EmailIds.Count);
return true;
}
/// <summary>
/// get size of one particular email
/// </summary>
/// <param name="msg_number"></param>
/// <returns></returns>
public int GetUniqueEmailId(EmailUid msg_number)
{
EnsureState(Pop3ConnectionStateEnum.Connected);
string response = string.Empty;
executeCommand("LIST " + msg_number.ToString(), ref response);
int EmailSize = 0;
string[] responseSplit = response.Split(' ');
if (responseSplit.Length < 2 || (! int.TryParse(responseSplit[2], out EmailSize)))
{
CallWarning("GetEmailSize", response, "\'+OK int int\' format expected (EmailId, EmailSize)", null);
}
return EmailSize;
}
/// <summary>
/// Sends an 'empty' command to the POP3 server. Server has to respond with +OK
/// </summary>
/// <returns>true: server responds as expected</returns>
public bool NOOP()
{
EnsureState(Pop3ConnectionStateEnum.Connected);
string response = string.Empty;
if (! executeCommand("NOOP", ref response))
{
CallWarning("NOOP", response, "negative response for NOOP request", null);
return false;
}
return true;
}
/// <summary>
/// Should the raw content, the US-ASCII code as received, be traced
/// GetRawEmail will switch it on when it starts and off once finished
///
/// Inheritors might use it to get the raw email
/// </summary>
protected bool isTraceRawEmail = false;
/// <summary>
/// contains one MIME part of the email in US-ASCII, needs to be translated in .NET string (Unicode)
/// contains the complete email in US-ASCII, needs to be translated in .NET string (Unicode)
/// For speed reasons, reuse StringBuilder
/// </summary>
protected StringBuilder RawEmailSB;
/// <summary>
/// Reads the complete text of a message
/// </summary>
/// <param name="MessageNo">Email to retrieve</param>
/// <param name="EmailText">ASCII string of complete message</param>
/// <returns></returns>
public bool GetRawEmail(int MessageNo, ref string EmailText)
{
//send 'RETR int' command to server
if (! SendRetrCommand(MessageNo))
{
EmailText = null;
return false;
}
//get the lines
string response = string.Empty;
int LineCounter = 0;
//empty StringBuilder
if (RawEmailSB == null)
{
RawEmailSB = new StringBuilder(100000);
}
else
{
RawEmailSB.Length = 0;
}
isTraceRawEmail = true;
while (readMultiLine(ref response))
{
LineCounter++;
}
EmailText = RawEmailSB.ToString();
TraceFrom("email with {0} lines, {1} chars received", LineCounter.ToString(), EmailText.Length);
return true;
}
///// <summary>
///// Requests from POP3 server a specific email and returns a stream with the message content (header and body)
///// </summary>
///// <param name="MessageNo"></param>
///// <param name="EmailStreamReader"></param>
///// <returns>false: POP3 server cannot provide this message</returns>
//public bool GetEmailStream(int MessageNo, out StreamReader EmailStreamReader) {
// //send 'RETR int' command to server
// if (!SendRetrCommand(MessageNo)) {
// EmailStreamReader = null;
// return false;
// }
// EmailStreamReader = sslStreamReader;
// return true;
//}
/// <summary>
/// Unmark any emails from deletion. The server only deletes email really
/// once the connection is properly closed.
/// </summary>
/// <returns>true: emails are unmarked from deletion</returns>
public bool UndeleteAllEmails()
{
EnsureState(Pop3ConnectionStateEnum.Connected);
string response = string.Empty;
return executeCommand("RSET", ref response);
}
/// <summary>
/// Get mailbox statistics
/// </summary>
/// <param name="NumberOfMails"></param>
/// <param name="MailboxSize"></param>
/// <returns></returns>
public bool GetMailboxStats(ref int NumberOfMails, ref int MailboxSize)
{
EnsureState(Pop3ConnectionStateEnum.Connected);
//interpret response
string response = string.Empty;
NumberOfMails = 0;
MailboxSize = 0;
if (executeCommand("STAT", ref response))
{
//got a positive response
string[] responseParts = response.Split(' ');
if (responseParts.Length < 2)
{
//response format wrong
throw (new Pop3Exception("Server " + PopServer + " sends illegally formatted response." + Environment.NewLine+ "Expected format: +OK int int" + Environment.NewLine+ "Received response: " + response));
}
NumberOfMails = int.Parse(responseParts[1]);
MailboxSize = int.Parse(responseParts[2]);
return true;
}
return false;
}
/// <summary>
/// Send RETR command to POP 3 server to fetch one particular message
/// </summary>
/// <param name="MessageNo">ID of message required</param>
/// <returns>false: negative server respond, message not delivered</returns>
protected bool SendRetrCommand(int MessageNo)
{
EnsureState(Pop3ConnectionStateEnum.Connected);
// retrieve mail with message number
string response = string.Empty;
if (! executeCommand("RETR " + MessageNo.ToString(), ref response))
{
CallWarning("GetRawEmail", response, "negative response for email (ID: {0}) request", MessageNo);
return false;
}
return true;
}
//Helper methodes
//---------------
public bool isDebug = false;
/// <summary>
/// sends the 4 letter command to POP3 server (adds CRLF) and waits for the
/// response of the server
/// </summary>
/// <param name="commandText">command to be sent to server</param>
/// <param name="response">answer from server</param>
/// <returns>false: server sent negative acknowledge, i.e. server could not execute command</returns>
private bool executeCommand(string commandText, ref string response)
{
//send command to server
byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes((commandText + CRLF).ToCharArray());
CallTrace("Tx \'{0}\'", commandText);
bool isSupressThrow = false;
try
{
pop3Stream.Write(commandBytes, 0, commandBytes.Length);
if (isDebug)
{
isDebug = false;
throw (new IOException("Test", new SocketException(10053)));
}
}
catch (IOException ex)
{
//Unable to write data to the transport connection. Check if reconnection should be tried
isSupressThrow = executeReconnect(ex, commandText, commandBytes);
if (! isSupressThrow)
{
throw;
}
}
pop3Stream.Flush();
//read response from server
response = null;
try
{
response = pop3StreamReader.ReadLine();
}
catch (IOException ex)
{
//Unable to write data to the transport connection. Check if reconnection should be tried
isSupressThrow = executeReconnect(ex, commandText, commandBytes);
if (isSupressThrow)
{
//wait for response one more time
response = pop3StreamReader.ReadLine();
}
else
{
throw;
}
}
if (response == null)
{
throw (new Pop3Exception("Server " + PopServer + " has not responded, timeout has occured."));
}
CallTrace("Rx \'{0}\'", response);
return (response.Length > 0 && response[0] == '+');
}
/// <summary>
/// reconnect, if there is a timeout exception and isAutoReconnect is true
///
/// </summary>
private bool executeReconnect(IOException ex, string command, byte[] commandBytes)
{
if (ex.InnerException != null&& ex.InnerException is SocketException)
{
//SocketException
SocketException innerEx = (SocketException) ex.InnerException;
if (innerEx.ErrorCode == 10053)
{
//probably timeout: An established connection was aborted by the software in your host machine.
CallWarning("ExecuteCommand", "", "probably timeout occured", null);
if (IsAutoReconnect)
{
//try to reconnect and send one more time
isTimeoutReconnect = true;
try
{
CallTrace(" try to auto reconnect", null);
Connect();
CallTrace(" reconnect successful, try to resend command", null);
CallTrace("Tx \'{0}\'", command);
pop3Stream.Write(commandBytes, 0, commandBytes.Length);
pop3Stream.Flush();
return true;
}
finally
{
isTimeoutReconnect = false;
}
}
}
}
return false;
}
//
///// <summary>
///// sends the 4 letter command to POP3 server (adds CRLF)
///// </summary>
///// <param name="command"></param>
//protected void SendCommand(string command) {
//byte[] commandBytes = System.Text.Encoding.ASCII.GetBytes((command + CRLF).ToCharArray());
//CallTrace("Tx '{0}'", command);
//try {
//pop3Stream.Write(commandBytes, 0, commandBytes.Length);
//} catch (IOException ex) {
////Unable to write data to the transport connection:
//if (ex.InnerException!=null && ex.InnerException is SocketException) {
////SocketException
//SocketException innerEx = (SocketException)ex.InnerException;
//if (innerEx.ErrorCode==10053) {
////probably timeout: An established connection was aborted by the software in your host machine.
//CallWarning("SendCommand", "", "probably timeout occured");
//if (isAutoReconnect) {
////try to reconnect and send one more time
//isTimeoutReconnect = true;
//try {
//CallTrace(" try to auto reconnect");
//Connect();
//CallTrace(" reconnect successful, try to resend command");
//CallTrace("Tx '{0}'", command);
//pop3Stream.Write(commandBytes, 0, commandBytes.Length);
//} finally {
//isTimeoutReconnect = false;
//}
//return;
//}
//}
//}
//throw;
//}
//pop3Stream.Flush();
//}
//
/// <summary>
/// read single line response from POP3 server.
/// <example>Example server response: +OK asdfkjahsf</example>
/// </summary>
/// <param name="response">response from POP3 server</param>
/// <returns>true: positive response</returns>
protected bool readSingleLine(ref string response)
{
response = null;
try
{
response = pop3StreamReader.ReadLine();
}
catch (System.Exception ex)
{
string s = ex.Message;
}
if (response == null)
{
throw (new Pop3Exception("Server " + PopServer + " has not responded, timeout has occured."));
}
CallTrace("Rx \'{0}\'", response);
return (response.Length > 0 && response[0] == '+');
}
/// <summary>
/// read one line in multiline mode from the POP3 server.
/// </summary>
/// <param name="response">line received</param>
/// <returns>false: end of message</returns>
protected bool readMultiLine(ref string response)
{
response = null;
response = pop3StreamReader.ReadLine();
if (response == null)
{
throw (new Pop3Exception("Server " + PopServer + " has not responded, probably timeout has occured."));
}
if (isTraceRawEmail)
{
//collect all responses as received
RawEmailSB.Append(response + CRLF);
}
//check for byte stuffing, i.e. if a line starts with a '.', another '.' is added, unless
//it is the last line
if (response.Length > 0 && response[0] == '.')
{
if (response == ".")
{
//closing line found
return false;
}
//remove the first '.'
response = response.Substring(1, response.Length - 1);
}
return true;
}
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections;
using System.Reflection;
using Common.Logging;
using Spring.Util;
using Spring.Core.TypeResolution;
using Spring.Core;
#endregion
namespace Spring.Transaction.Interceptor
{
/// <summary>
/// Simple implementation of the <see cref="Spring.Transaction.Interceptor.ITransactionAttributeSource"/>
/// interface that allows attributes to be stored per method in a map.
/// </summary>
/// <author>Rod Johnson</author>
/// <author>Juergen Hoeller</author>
/// <author>Griffin Caprio (.NET)</author>
public class MethodMapTransactionAttributeSource : ITransactionAttributeSource
{
private IDictionary _methodMap;
private IDictionary _nameMap;
#region Logging Definition
private static readonly ILog LOG = LogManager.GetLogger(typeof (MethodMapTransactionAttributeSource));
#endregion
/// <summary>
/// Creates a new instance of the
/// <see cref="Spring.Transaction.Interceptor.MethodMapTransactionAttributeSource"/> class.
/// </summary>
public MethodMapTransactionAttributeSource()
{
_methodMap = new Hashtable();
_nameMap = new Hashtable();
}
/// <summary>
/// Set a name/attribute map, consisting of "FQCN.method, AssemblyName" method names
/// (e.g. "MyNameSpace.MyClass.MyMethod, MyAssembly") and ITransactionAttribute
/// instances (or Strings to be converted to <see cref="ITransactionAttribute"/> instances).
/// </summary>
/// <remarks>
/// <p>
/// The key values of the supplied <see cref="System.Collections.IDictionary"/>
/// must adhere to the following form:<br/>
/// <code>FQCN.methodName, Assembly</code>.
/// </p>
/// <example>
/// <code>MyNameSpace.MyClass.MyMethod, MyAssembly</code>
/// </example>
/// </remarks>
public IDictionary MethodMap
{
set
{
foreach (DictionaryEntry entry in value)
{
string name = entry.Key as string;
ITransactionAttribute attribute = null;
//Check if we need to convert from a string to ITransactionAttribute
if (entry.Value is ITransactionAttribute)
{
attribute = entry.Value as ITransactionAttribute;
}
else
{
TransactionAttributeEditor editor = new TransactionAttributeEditor();
editor.SetAsText(entry.Value.ToString());
attribute = editor.Value;
}
AddTransactionalMethod( name, attribute );
}
}
}
/// <summary>
/// Add an attribute for a transactional method.
/// </summary>
/// <remarks>
/// Method names can end or start with "*" for matching multiple methods.
/// </remarks>
/// <param name="name">The class and method name, separated by a dot.</param>
/// <param name="attribute">The attribute to be associated with the method.</param>
public void AddTransactionalMethod( string name, ITransactionAttribute attribute )
{
AssertUtils.ArgumentNotNull(name, "name");
int lastCommaIndex = name.LastIndexOf( "," );
if (lastCommaIndex == -1)
{
throw new ArgumentException("'" + name + "'" +
" is not a valid method name, missing AssemblyName. Format is FQN.MethodName, AssemblyName.");
}
string fqnWithMethod = name.Substring(0, lastCommaIndex);
int lastDotIndex = fqnWithMethod.LastIndexOf( "." );
if ( lastDotIndex == -1 )
{
throw new TransactionUsageException("'" + fqnWithMethod + "' is not a valid method name: format is FQN.methodName");
}
string className = fqnWithMethod.Substring(0, lastDotIndex );
string assemblyName = name.Substring(lastCommaIndex + 1);
string methodName = fqnWithMethod.Substring(lastDotIndex + 1 );
string fqnClassName = className + ", " + assemblyName;
try
{
Type type = TypeResolutionUtils.ResolveType(fqnClassName);
AddTransactionalMethod( type, methodName, attribute );
} catch ( TypeLoadException exception )
{
throw new TransactionUsageException( "Type '" + fqnClassName + "' not found.", exception );
}
}
/// <summary>
/// Add an attribute for a transactional method.
/// </summary>
/// <remarks>
/// Method names can end or start with "*" for matching multiple methods.
/// </remarks>
/// <param name="type">The target interface or class.</param>
/// <param name="mappedName">The mapped method name.</param>
/// <param name="transactionAttribute">
/// The attribute to be associated with the method.
/// </param>
public void AddTransactionalMethod(
Type type, string mappedName, ITransactionAttribute transactionAttribute )
{
// TODO address method overloading? At present this will
// simply match all methods that have the given name.
string name = type.Name + "." + mappedName;
MethodInfo[] methods = type.GetMethods();
IList matchingMethods = new ArrayList();
for ( int i = 0; i < methods.Length; i++ )
{
if ( methods[i].Name.Equals( mappedName ) || IsMatch(methods[i].Name, mappedName ))
{
matchingMethods.Add( methods[i] );
}
}
if ( matchingMethods.Count == 0 )
{
throw new TransactionUsageException("Couldn't find method '" + mappedName + "' on Type [" + type.Name + "]");
}
// register all matching methods
foreach ( MethodInfo currentMethod in matchingMethods )
{
string regularMethodName = (string)_nameMap[currentMethod];
if ( regularMethodName == null || ( !regularMethodName.Equals(name) && regularMethodName.Length <= name.Length))
{
// No already registered method name, or more specific
// method name specification now -> (re-)register method.
if (LOG.IsDebugEnabled && regularMethodName != null)
{
LOG.Debug("Replacing attribute for transactional method [" + currentMethod + "]: current name '" +
name + "' is more specific than '" + regularMethodName + "'");
}
_nameMap.Add( currentMethod, name );
AddTransactionalMethod( currentMethod, transactionAttribute );
}
else
{
if (LOG.IsDebugEnabled && regularMethodName != null)
{
LOG.Debug("Keeping attribute for transactional method [" + currentMethod + "]: current name '" +
name + "' is not more specific than '" + regularMethodName + "'");
}
}
}
}
/// <summary>
/// Add an attribute for a transactional method.
/// </summary>
/// <param name="method">The transactional method.</param>
/// <param name="transactionAttribute">
/// The attribute to be associated with the method.
/// </param>
public void AddTransactionalMethod( MethodInfo method, ITransactionAttribute transactionAttribute )
{
_methodMap.Add( method, transactionAttribute );
}
/// <summary>
/// Does the supplied <paramref name="methodName"/> match the supplied <paramref name="mappedName"/>?
/// </summary>
/// <remarks>
/// The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches,
/// as well as direct equality. This behaviour can (of course) be overridden in
/// derived classes.
/// </remarks>
/// <param name="methodName">The method name of the class.</param>
/// <param name="mappedName">The name in the descriptor.</param>
/// <returns><b>True</b> if the names match.</returns>
protected virtual bool IsMatch( string methodName, string mappedName )
{
return PatternMatchUtils.SimpleMatch(mappedName, methodName);
}
#region ITransactionAttributeSource Members
/// <summary>
/// Return the <see cref="Spring.Transaction.Interceptor.ITransactionAttribute"/> for this
/// method.
/// </summary>
/// <param name="method">The method to check.</param>
/// <param name="targetType">
/// The target <see cref="System.Type"/>. May be null, in which case the declaring
/// class of the supplied <paramref name="method"/> must be used.
/// </param>
/// <returns>
/// A <see cref="Spring.Transaction.Interceptor.ITransactionAttribute"/> or
/// null if the method is non-transactional.
/// </returns>
public ITransactionAttribute ReturnTransactionAttribute(MethodInfo method, Type targetType)
{
//Might have registered MethodInfo objects whose declaring type is the interface, so 'downcast'
//to the most specific method which is typically what is passed in as the first method argument.
foreach (DictionaryEntry dictionaryEntry in _methodMap)
{
MethodInfo currentMethod = (MethodInfo)dictionaryEntry.Key;
MethodInfo specificMethod;
if (targetType == null)
{
specificMethod = currentMethod;
}
else
{
ParameterInfo[] parameters = currentMethod.GetParameters();
ComposedCriteria searchCriteria = new ComposedCriteria();
searchCriteria.Add(new MethodNameMatchCriteria(currentMethod.Name));
searchCriteria.Add(new MethodParametersCountCriteria(parameters.Length));
searchCriteria.Add(new MethodGenericArgumentsCountCriteria(currentMethod.GetGenericArguments().Length));
searchCriteria.Add(new MethodParametersCriteria(ReflectionUtils.GetParameterTypes(parameters)));
MemberInfo[] matchingMethods = targetType.FindMembers(
MemberTypes.Method,
BindingFlags.Instance | BindingFlags.Public,
new MemberFilter(new CriteriaMemberFilter().FilterMemberByCriteria),
searchCriteria);
if (matchingMethods != null && matchingMethods.Length == 1)
{
specificMethod = matchingMethods[0] as MethodInfo;
}
else
{
specificMethod = currentMethod;
}
}
if (method == specificMethod)
{
return (ITransactionAttribute)dictionaryEntry.Value;
}
}
return (ITransactionAttribute)_methodMap[method];
}
#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 System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using Internal.NativeCrypto;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
internal sealed partial class CertificatePal : IDisposable, ICertificatePal
{
public static ICertificatePal FromBlob(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
return FromBlobOrFile(rawData, null, password, keyStorageFlags);
}
public static ICertificatePal FromFile(string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
return FromBlobOrFile(null, fileName, password, keyStorageFlags);
}
private static ICertificatePal FromBlobOrFile(byte[] rawData, string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
Debug.Assert(rawData != null || fileName != null);
bool loadFromFile = (fileName != null);
PfxCertStoreFlags pfxCertStoreFlags = MapKeyStorageFlags(keyStorageFlags);
bool persistKeySet = (0 != (keyStorageFlags & X509KeyStorageFlags.PersistKeySet));
CertEncodingType msgAndCertEncodingType;
ContentType contentType;
FormatType formatType;
SafeCertStoreHandle hCertStore = null;
SafeCryptMsgHandle hCryptMsg = null;
SafeCertContextHandle pCertContext = null;
try
{
unsafe
{
fixed (byte* pRawData = rawData)
{
fixed (char* pFileName = fileName)
{
CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(loadFromFile ? 0 : rawData.Length, pRawData);
CertQueryObjectType objectType = loadFromFile ? CertQueryObjectType.CERT_QUERY_OBJECT_FILE : CertQueryObjectType.CERT_QUERY_OBJECT_BLOB;
void* pvObject = loadFromFile ? (void*)pFileName : (void*)&certBlob;
bool success = Interop.crypt32.CryptQueryObject(
objectType,
pvObject,
X509ExpectedContentTypeFlags,
X509ExpectedFormatTypeFlags,
0,
out msgAndCertEncodingType,
out contentType,
out formatType,
out hCertStore,
out hCryptMsg,
out pCertContext
);
if (!success)
{
int hr = Marshal.GetHRForLastWin32Error();
throw hr.ToCryptographicException();
}
}
}
if (contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED || contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED)
{
pCertContext = GetSignerInPKCS7Store(hCertStore, hCryptMsg);
}
else if (contentType == ContentType.CERT_QUERY_CONTENT_PFX)
{
if (loadFromFile)
rawData = File.ReadAllBytes(fileName);
pCertContext = FilterPFXStore(rawData, password, pfxCertStoreFlags);
}
CertificatePal pal = new CertificatePal(pCertContext, deleteKeyContainer: !persistKeySet);
pCertContext = null;
return pal;
}
}
finally
{
if (hCertStore != null)
hCertStore.Dispose();
if (hCryptMsg != null)
hCryptMsg.Dispose();
if (pCertContext != null)
pCertContext.Dispose();
}
}
private static SafeCertContextHandle GetSignerInPKCS7Store(SafeCertStoreHandle hCertStore, SafeCryptMsgHandle hCryptMsg)
{
// make sure that there is at least one signer of the certificate store
int dwSigners;
int cbSigners = sizeof(int);
if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_COUNT_PARAM, 0, out dwSigners, ref cbSigners))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
if (dwSigners == 0)
throw ErrorCode.CRYPT_E_SIGNER_NOT_FOUND.ToCryptographicException();
// get the first signer from the store, and use that as the loaded certificate
int cbData = 0;
if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, null, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
byte[] cmsgSignerBytes = new byte[cbData];
if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, cmsgSignerBytes, ref cbData))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
CERT_INFO certInfo = default(CERT_INFO);
unsafe
{
fixed (byte* pCmsgSignerBytes = cmsgSignerBytes)
{
CMSG_SIGNER_INFO_Partial* pCmsgSignerInfo = (CMSG_SIGNER_INFO_Partial*)pCmsgSignerBytes;
certInfo.Issuer.cbData = pCmsgSignerInfo->Issuer.cbData;
certInfo.Issuer.pbData = pCmsgSignerInfo->Issuer.pbData;
certInfo.SerialNumber.cbData = pCmsgSignerInfo->SerialNumber.cbData;
certInfo.SerialNumber.pbData = pCmsgSignerInfo->SerialNumber.pbData;
}
SafeCertContextHandle pCertContext = null;
if (!Interop.crypt32.CertFindCertificateInStore(hCertStore, CertFindType.CERT_FIND_SUBJECT_CERT, &certInfo, ref pCertContext))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
return pCertContext;
}
}
private static SafeCertContextHandle FilterPFXStore(byte[] rawData, string password, PfxCertStoreFlags pfxCertStoreFlags)
{
SafeCertStoreHandle hStore;
unsafe
{
fixed (byte* pbRawData = rawData)
{
CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(rawData.Length, pbRawData);
hStore = Interop.crypt32.PFXImportCertStore(ref certBlob, password, pfxCertStoreFlags);
if (hStore.IsInvalid)
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
}
}
try
{
// Find the first cert with private key. If none, then simply take the very first cert. Along the way, delete the keycontainers
// of any cert we don't accept.
SafeCertContextHandle pCertContext = SafeCertContextHandle.InvalidHandle;
SafeCertContextHandle pEnumContext = null;
while (Interop.crypt32.CertEnumCertificatesInStore(hStore, ref pEnumContext))
{
if (pEnumContext.ContainsPrivateKey)
{
if ((!pCertContext.IsInvalid) && pCertContext.ContainsPrivateKey)
{
// We already found our chosen one. Free up this one's key and move on.
SafeCertContextHandleWithKeyContainerDeletion.DeleteKeyContainer(pEnumContext);
}
else
{
// Found our first cert that has a private key. Set him up as our chosen one but keep iterating
// as we need to free up the keys of any remaining certs.
pCertContext.Dispose();
pCertContext = pEnumContext.Duplicate();
}
}
else
{
if (pCertContext.IsInvalid)
pCertContext = pEnumContext.Duplicate(); // Doesn't have a private key but hang on to it anyway in case we don't find any certs with a private key.
}
}
if (pCertContext.IsInvalid)
{
// For compat, setting "hr" to ERROR_INVALID_PARAMETER even though ERROR_INVALID_PARAMETER is not actually an HRESULT.
throw ErrorCode.ERROR_INVALID_PARAMETER.ToCryptographicException();
}
return pCertContext;
}
finally
{
hStore.Dispose();
}
}
private static PfxCertStoreFlags MapKeyStorageFlags(X509KeyStorageFlags keyStorageFlags)
{
if ((keyStorageFlags & (X509KeyStorageFlags)~0x1F) != 0)
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(keyStorageFlags));
PfxCertStoreFlags pfxCertStoreFlags = 0;
if ((keyStorageFlags & X509KeyStorageFlags.UserKeySet) == X509KeyStorageFlags.UserKeySet)
pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_USER_KEYSET;
else if ((keyStorageFlags & X509KeyStorageFlags.MachineKeySet) == X509KeyStorageFlags.MachineKeySet)
pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_MACHINE_KEYSET;
if ((keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable)
pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_EXPORTABLE;
if ((keyStorageFlags & X509KeyStorageFlags.UserProtected) == X509KeyStorageFlags.UserProtected)
pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_USER_PROTECTED;
// In the full .NET Framework loading a PFX then adding the key to the Windows Certificate Store would
// enable a native application compiled against CAPI to find that private key and interoperate with it.
//
// For CoreFX this behavior is being retained.
//
// For .NET Native (UWP) the API used to delete the private key (if it wasn't added to a store) is not
// allowed to be called if the key is stored in CAPI. So for UWP force the key to be stored in the
// CNG Key Storage Provider, then deleting the key with CngKey.Delete will clean up the file on disk, too.
#if NETNATIVE
pfxCertStoreFlags |= PfxCertStoreFlags.PKCS12_ALWAYS_CNG_KSP;
#endif
return pfxCertStoreFlags;
}
private const ExpectedContentTypeFlags X509ExpectedContentTypeFlags =
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_CERT |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PFX;
private const ExpectedFormatTypeFlags X509ExpectedFormatTypeFlags = ExpectedFormatTypeFlags.CERT_QUERY_FORMAT_FLAG_ALL;
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.11.3: Inormation abut the addition or modification of a synthecic enviroment object that is anchored to the terrain with a single point. COMPLETE
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(ObjectType))]
[XmlInclude(typeof(Vector3Double))]
[XmlInclude(typeof(Orientation))]
[XmlInclude(typeof(SimulationAddress))]
public partial class PointObjectStatePdu : SyntheticEnvironmentFamilyPdu, IEquatable<PointObjectStatePdu>
{
/// <summary>
/// Object in synthetic environment
/// </summary>
private EntityID _objectID = new EntityID();
/// <summary>
/// Object with which this point object is associated
/// </summary>
private EntityID _referencedObjectID = new EntityID();
/// <summary>
/// unique update number of each state transition of an object
/// </summary>
private ushort _updateNumber;
/// <summary>
/// force ID
/// </summary>
private byte _forceID;
/// <summary>
/// modifications
/// </summary>
private byte _modifications;
/// <summary>
/// Object type
/// </summary>
private ObjectType _objectType = new ObjectType();
/// <summary>
/// Object location
/// </summary>
private Vector3Double _objectLocation = new Vector3Double();
/// <summary>
/// Object orientation
/// </summary>
private Orientation _objectOrientation = new Orientation();
/// <summary>
/// Object apperance
/// </summary>
private double _objectAppearance;
/// <summary>
/// requesterID
/// </summary>
private SimulationAddress _requesterID = new SimulationAddress();
/// <summary>
/// receiver ID
/// </summary>
private SimulationAddress _receivingID = new SimulationAddress();
/// <summary>
/// padding
/// </summary>
private uint _pad2;
/// <summary>
/// Initializes a new instance of the <see cref="PointObjectStatePdu"/> class.
/// </summary>
public PointObjectStatePdu()
{
PduType = (byte)43;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(PointObjectStatePdu left, PointObjectStatePdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(PointObjectStatePdu left, PointObjectStatePdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._objectID.GetMarshalledSize(); // this._objectID
marshalSize += this._referencedObjectID.GetMarshalledSize(); // this._referencedObjectID
marshalSize += 2; // this._updateNumber
marshalSize += 1; // this._forceID
marshalSize += 1; // this._modifications
marshalSize += this._objectType.GetMarshalledSize(); // this._objectType
marshalSize += this._objectLocation.GetMarshalledSize(); // this._objectLocation
marshalSize += this._objectOrientation.GetMarshalledSize(); // this._objectOrientation
marshalSize += 8; // this._objectAppearance
marshalSize += this._requesterID.GetMarshalledSize(); // this._requesterID
marshalSize += this._receivingID.GetMarshalledSize(); // this._receivingID
marshalSize += 4; // this._pad2
return marshalSize;
}
/// <summary>
/// Gets or sets the Object in synthetic environment
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "objectID")]
public EntityID ObjectID
{
get
{
return this._objectID;
}
set
{
this._objectID = value;
}
}
/// <summary>
/// Gets or sets the Object with which this point object is associated
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "referencedObjectID")]
public EntityID ReferencedObjectID
{
get
{
return this._referencedObjectID;
}
set
{
this._referencedObjectID = value;
}
}
/// <summary>
/// Gets or sets the unique update number of each state transition of an object
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "updateNumber")]
public ushort UpdateNumber
{
get
{
return this._updateNumber;
}
set
{
this._updateNumber = value;
}
}
/// <summary>
/// Gets or sets the force ID
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "forceID")]
public byte ForceID
{
get
{
return this._forceID;
}
set
{
this._forceID = value;
}
}
/// <summary>
/// Gets or sets the modifications
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "modifications")]
public byte Modifications
{
get
{
return this._modifications;
}
set
{
this._modifications = value;
}
}
/// <summary>
/// Gets or sets the Object type
/// </summary>
[XmlElement(Type = typeof(ObjectType), ElementName = "objectType")]
public ObjectType ObjectType
{
get
{
return this._objectType;
}
set
{
this._objectType = value;
}
}
/// <summary>
/// Gets or sets the Object location
/// </summary>
[XmlElement(Type = typeof(Vector3Double), ElementName = "objectLocation")]
public Vector3Double ObjectLocation
{
get
{
return this._objectLocation;
}
set
{
this._objectLocation = value;
}
}
/// <summary>
/// Gets or sets the Object orientation
/// </summary>
[XmlElement(Type = typeof(Orientation), ElementName = "objectOrientation")]
public Orientation ObjectOrientation
{
get
{
return this._objectOrientation;
}
set
{
this._objectOrientation = value;
}
}
/// <summary>
/// Gets or sets the Object apperance
/// </summary>
[XmlElement(Type = typeof(double), ElementName = "objectAppearance")]
public double ObjectAppearance
{
get
{
return this._objectAppearance;
}
set
{
this._objectAppearance = value;
}
}
/// <summary>
/// Gets or sets the requesterID
/// </summary>
[XmlElement(Type = typeof(SimulationAddress), ElementName = "requesterID")]
public SimulationAddress RequesterID
{
get
{
return this._requesterID;
}
set
{
this._requesterID = value;
}
}
/// <summary>
/// Gets or sets the receiver ID
/// </summary>
[XmlElement(Type = typeof(SimulationAddress), ElementName = "receivingID")]
public SimulationAddress ReceivingID
{
get
{
return this._receivingID;
}
set
{
this._receivingID = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "pad2")]
public uint Pad2
{
get
{
return this._pad2;
}
set
{
this._pad2 = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._objectID.Marshal(dos);
this._referencedObjectID.Marshal(dos);
dos.WriteUnsignedShort((ushort)this._updateNumber);
dos.WriteUnsignedByte((byte)this._forceID);
dos.WriteUnsignedByte((byte)this._modifications);
this._objectType.Marshal(dos);
this._objectLocation.Marshal(dos);
this._objectOrientation.Marshal(dos);
dos.WriteDouble((double)this._objectAppearance);
this._requesterID.Marshal(dos);
this._receivingID.Marshal(dos);
dos.WriteUnsignedInt((uint)this._pad2);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._objectID.Unmarshal(dis);
this._referencedObjectID.Unmarshal(dis);
this._updateNumber = dis.ReadUnsignedShort();
this._forceID = dis.ReadUnsignedByte();
this._modifications = dis.ReadUnsignedByte();
this._objectType.Unmarshal(dis);
this._objectLocation.Unmarshal(dis);
this._objectOrientation.Unmarshal(dis);
this._objectAppearance = dis.ReadDouble();
this._requesterID.Unmarshal(dis);
this._receivingID.Unmarshal(dis);
this._pad2 = dis.ReadUnsignedInt();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<PointObjectStatePdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<objectID>");
this._objectID.Reflection(sb);
sb.AppendLine("</objectID>");
sb.AppendLine("<referencedObjectID>");
this._referencedObjectID.Reflection(sb);
sb.AppendLine("</referencedObjectID>");
sb.AppendLine("<updateNumber type=\"ushort\">" + this._updateNumber.ToString(CultureInfo.InvariantCulture) + "</updateNumber>");
sb.AppendLine("<forceID type=\"byte\">" + this._forceID.ToString(CultureInfo.InvariantCulture) + "</forceID>");
sb.AppendLine("<modifications type=\"byte\">" + this._modifications.ToString(CultureInfo.InvariantCulture) + "</modifications>");
sb.AppendLine("<objectType>");
this._objectType.Reflection(sb);
sb.AppendLine("</objectType>");
sb.AppendLine("<objectLocation>");
this._objectLocation.Reflection(sb);
sb.AppendLine("</objectLocation>");
sb.AppendLine("<objectOrientation>");
this._objectOrientation.Reflection(sb);
sb.AppendLine("</objectOrientation>");
sb.AppendLine("<objectAppearance type=\"double\">" + this._objectAppearance.ToString(CultureInfo.InvariantCulture) + "</objectAppearance>");
sb.AppendLine("<requesterID>");
this._requesterID.Reflection(sb);
sb.AppendLine("</requesterID>");
sb.AppendLine("<receivingID>");
this._receivingID.Reflection(sb);
sb.AppendLine("</receivingID>");
sb.AppendLine("<pad2 type=\"uint\">" + this._pad2.ToString(CultureInfo.InvariantCulture) + "</pad2>");
sb.AppendLine("</PointObjectStatePdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as PointObjectStatePdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(PointObjectStatePdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._objectID.Equals(obj._objectID))
{
ivarsEqual = false;
}
if (!this._referencedObjectID.Equals(obj._referencedObjectID))
{
ivarsEqual = false;
}
if (this._updateNumber != obj._updateNumber)
{
ivarsEqual = false;
}
if (this._forceID != obj._forceID)
{
ivarsEqual = false;
}
if (this._modifications != obj._modifications)
{
ivarsEqual = false;
}
if (!this._objectType.Equals(obj._objectType))
{
ivarsEqual = false;
}
if (!this._objectLocation.Equals(obj._objectLocation))
{
ivarsEqual = false;
}
if (!this._objectOrientation.Equals(obj._objectOrientation))
{
ivarsEqual = false;
}
if (this._objectAppearance != obj._objectAppearance)
{
ivarsEqual = false;
}
if (!this._requesterID.Equals(obj._requesterID))
{
ivarsEqual = false;
}
if (!this._receivingID.Equals(obj._receivingID))
{
ivarsEqual = false;
}
if (this._pad2 != obj._pad2)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._objectID.GetHashCode();
result = GenerateHash(result) ^ this._referencedObjectID.GetHashCode();
result = GenerateHash(result) ^ this._updateNumber.GetHashCode();
result = GenerateHash(result) ^ this._forceID.GetHashCode();
result = GenerateHash(result) ^ this._modifications.GetHashCode();
result = GenerateHash(result) ^ this._objectType.GetHashCode();
result = GenerateHash(result) ^ this._objectLocation.GetHashCode();
result = GenerateHash(result) ^ this._objectOrientation.GetHashCode();
result = GenerateHash(result) ^ this._objectAppearance.GetHashCode();
result = GenerateHash(result) ^ this._requesterID.GetHashCode();
result = GenerateHash(result) ^ this._receivingID.GetHashCode();
result = GenerateHash(result) ^ this._pad2.GetHashCode();
return result;
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Text;
using System.IO;
using Oranikle.Report.Engine;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// Drillthrough reports; pick report and specify parameters
/// </summary>
internal class DrillParametersDialog : System.Windows.Forms.Form
{
private string _DrillReport;
private DataTable _DataTable;
private DataGridTextBoxColumn dgtbName;
private DataGridTextBoxColumn dgtbValue;
private DataGridTextBoxColumn dgtbOmit;
private System.Windows.Forms.DataGridTableStyle dgTableStyle;
private System.Windows.Forms.Label label1;
private Oranikle.Studio.Controls.StyledButton bFile;
private Oranikle.Studio.Controls.CustomTextControl tbReportFile;
private System.Windows.Forms.DataGrid dgParms;
private Oranikle.Studio.Controls.StyledButton bRefreshParms;
private Oranikle.Studio.Controls.StyledButton bOK;
private Oranikle.Studio.Controls.StyledButton bCancel;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal DrillParametersDialog(string report, List<DrillParameter> parameters)
{
_DrillReport = report;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(parameters);
}
private void InitValues(List<DrillParameter> parameters)
{
this.tbReportFile.Text = _DrillReport;
// Initialize the DataGrid columns
dgtbName = new DataGridTextBoxColumn();
dgtbValue = new DataGridTextBoxColumn();
dgtbOmit = new DataGridTextBoxColumn();
this.dgTableStyle.GridColumnStyles.AddRange(new DataGridColumnStyle[] {
this.dgtbName,
this.dgtbValue,
this.dgtbOmit});
//
// dgtbFE
//
dgtbName.HeaderText = "Parameter Name";
dgtbName.MappingName = "ParameterName";
dgtbName.Width = 75;
//
// dgtbValue
//
this.dgtbValue.HeaderText = "Value";
this.dgtbValue.MappingName = "Value";
this.dgtbValue.Width = 75;
//
// dgtbOmit
//
this.dgtbOmit.HeaderText = "Omit";
this.dgtbOmit.MappingName = "Omit";
this.dgtbOmit.Width = 75;
// Initialize the DataTable
_DataTable = new DataTable();
_DataTable.Columns.Add(new DataColumn("ParameterName", typeof(string)));
_DataTable.Columns.Add(new DataColumn("Value", typeof(string)));
_DataTable.Columns.Add(new DataColumn("Omit", typeof(string)));
string[] rowValues = new string[3];
if (parameters != null)
foreach (DrillParameter dp in parameters)
{
rowValues[0] = dp.ParameterName;
rowValues[1] = dp.ParameterValue;
rowValues[2] = dp.ParameterOmit;
_DataTable.Rows.Add(rowValues);
}
// Don't allow new rows; do this by creating a DataView over the DataTable
// DataView dv = new DataView(_DataTable); // this has bad side effects
// dv.AllowNew = false;
this.dgParms.DataSource = _DataTable;
DataGridTableStyle ts = dgParms.TableStyles[0];
ts.GridColumnStyles[0].Width = 140;
ts.GridColumnStyles[0].ReadOnly = true;
ts.GridColumnStyles[1].Width = 140;
ts.GridColumnStyles[2].Width = 70;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component 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(DrillParametersDialog));
this.dgParms = new System.Windows.Forms.DataGrid();
this.dgTableStyle = new System.Windows.Forms.DataGridTableStyle();
this.label1 = new System.Windows.Forms.Label();
this.tbReportFile = new Oranikle.Studio.Controls.CustomTextControl();
this.bFile = new Oranikle.Studio.Controls.StyledButton();
this.bRefreshParms = new Oranikle.Studio.Controls.StyledButton();
this.bOK = new Oranikle.Studio.Controls.StyledButton();
this.bCancel = new Oranikle.Studio.Controls.StyledButton();
((System.ComponentModel.ISupportInitialize)(this.dgParms)).BeginInit();
this.SuspendLayout();
//
// dgParms
//
this.dgParms.BackgroundColor = System.Drawing.Color.White;
this.dgParms.CaptionVisible = false;
this.dgParms.DataMember = "";
this.dgParms.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgParms.Location = new System.Drawing.Point(8, 40);
this.dgParms.Name = "dgParms";
this.dgParms.Size = new System.Drawing.Size(384, 168);
this.dgParms.TabIndex = 2;
this.dgParms.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.dgTableStyle});
//
// dgTableStyle
//
this.dgTableStyle.AllowSorting = false;
this.dgTableStyle.DataGrid = this.dgParms;
this.dgTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText;
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(88, 23);
this.label1.TabIndex = 3;
this.label1.Text = "Report name";
//
// tbReportFile
//
this.tbReportFile.AddX = 0;
this.tbReportFile.AddY = 0;
this.tbReportFile.AllowSpace = false;
this.tbReportFile.BorderColor = System.Drawing.Color.LightGray;
this.tbReportFile.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbReportFile.ChangeVisibility = false;
this.tbReportFile.ChildControl = null;
this.tbReportFile.ConvertEnterToTab = true;
this.tbReportFile.ConvertEnterToTabForDialogs = false;
this.tbReportFile.Decimals = 0;
this.tbReportFile.DisplayList = new object[0];
this.tbReportFile.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbReportFile.Location = new System.Drawing.Point(104, 8);
this.tbReportFile.Name = "tbReportFile";
this.tbReportFile.OnDropDownCloseFocus = true;
this.tbReportFile.SelectType = 0;
this.tbReportFile.Size = new System.Drawing.Size(312, 20);
this.tbReportFile.TabIndex = 4;
this.tbReportFile.UseValueForChildsVisibilty = false;
this.tbReportFile.Value = true;
//
// bFile
//
this.bFile.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bFile.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bFile.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bFile.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bFile.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bFile.Font = new System.Drawing.Font("Arial", 9F);
this.bFile.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bFile.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bFile.Location = new System.Drawing.Point(424, 8);
this.bFile.Name = "bFile";
this.bFile.OverriddenSize = null;
this.bFile.Size = new System.Drawing.Size(24, 21);
this.bFile.TabIndex = 5;
this.bFile.Text = "...";
this.bFile.UseVisualStyleBackColor = true;
this.bFile.Click += new System.EventHandler(this.bFile_Click);
//
// bRefreshParms
//
this.bRefreshParms.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bRefreshParms.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bRefreshParms.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bRefreshParms.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bRefreshParms.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bRefreshParms.Font = new System.Drawing.Font("Arial", 9F);
this.bRefreshParms.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bRefreshParms.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bRefreshParms.Location = new System.Drawing.Point(400, 40);
this.bRefreshParms.Name = "bRefreshParms";
this.bRefreshParms.OverriddenSize = null;
this.bRefreshParms.Size = new System.Drawing.Size(56, 21);
this.bRefreshParms.TabIndex = 10;
this.bRefreshParms.Text = "Refresh";
this.bRefreshParms.UseVisualStyleBackColor = true;
this.bRefreshParms.Click += new System.EventHandler(this.bRefreshParms_Click);
//
// bOK
//
this.bOK.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bOK.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bOK.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bOK.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.bOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bOK.Font = new System.Drawing.Font("Arial", 9F);
this.bOK.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bOK.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bOK.Location = new System.Drawing.Point(288, 216);
this.bOK.Name = "bOK";
this.bOK.OverriddenSize = null;
this.bOK.Size = new System.Drawing.Size(75, 23);
this.bOK.TabIndex = 11;
this.bOK.Text = "OK";
this.bOK.UseVisualStyleBackColor = true;
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bCancel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bCancel.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bCancel.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bCancel.CausesValidation = false;
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bCancel.Font = new System.Drawing.Font("Arial", 9F);
this.bCancel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bCancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bCancel.Location = new System.Drawing.Point(376, 216);
this.bCancel.Name = "bCancel";
this.bCancel.OverriddenSize = null;
this.bCancel.Size = new System.Drawing.Size(75, 23);
this.bCancel.TabIndex = 12;
this.bCancel.Text = "Cancel";
this.bCancel.UseVisualStyleBackColor = true;
//
// DrillParametersDialog
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(241)))), ((int)(((byte)(249)))));
this.CancelButton = this.bCancel;
this.CausesValidation = false;
this.ClientSize = new System.Drawing.Size(464, 248);
this.ControlBox = false;
this.Controls.Add(this.bOK);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.bRefreshParms);
this.Controls.Add(this.bFile);
this.Controls.Add(this.tbReportFile);
this.Controls.Add(this.label1);
this.Controls.Add(this.dgParms);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DrillParametersDialog";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "Specify Drillthrough Report and Parameters";
((System.ComponentModel.ISupportInitialize)(this.dgParms)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public string DrillthroughReport
{
get {return this._DrillReport;}
}
public List<DrillParameter> DrillParameters
{
get
{
List<DrillParameter> parms = new List<DrillParameter>();
// Loop thru and add all the filters
foreach (DataRow dr in _DataTable.Rows)
{
if (dr[0] == DBNull.Value || dr[1] == DBNull.Value)
continue;
string name = (string) dr[0];
string val = (string) dr[1];
string omit = dr[2] == DBNull.Value? "false": (string) dr[2];
if (name.Length <= 0 || val.Length <= 0)
continue;
DrillParameter dp = new DrillParameter(name, val, omit);
parms.Add(dp);
}
if (parms.Count == 0)
return null;
return parms;
}
}
private void bFile_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Report files (*.rdl)|*.rdl" +
"|All files (*.*)|*.*";
ofd.FilterIndex = 1;
ofd.FileName = "*.rdl";
ofd.Title = "Specify Report File Name";
ofd.DefaultExt = "rdl";
ofd.AddExtension = true;
try
{
if (ofd.ShowDialog() == DialogResult.OK)
{
string file = Path.GetFileNameWithoutExtension(ofd.FileName);
tbReportFile.Text = file;
}
}
finally
{
ofd.Dispose();
}
}
private void bRefreshParms_Click(object sender, System.EventArgs e)
{
// Obtain the source
Cursor savec = Cursor.Current;
Cursor.Current = Cursors.WaitCursor; // this can take some time
try
{
string filename="";
if (tbReportFile.Text.Length > 0)
filename = tbReportFile.Text + ".rdl";
filename = GetFileNameWithPath(filename);
string source = this.GetSource(filename);
if (source == null)
return; // error: message already displayed
// Compile the report
Oranikle.Report.Engine.Report report = this.GetReport(source, filename);
if (report == null)
return; // error: message already displayed
ICollection rps = report.UserReportParameters;
string[] rowValues = new string[3];
_DataTable.Rows.Clear();
foreach (UserReportParameter rp in rps)
{
rowValues[0] = rp.Name;
rowValues[1] = "";
rowValues[2] = "false";
_DataTable.Rows.Add(rowValues);
}
this.dgParms.Refresh();
this.dgParms.Focus();
}
finally
{
Cursor.Current = savec;
}
}
private string GetFileNameWithPath(string file)
{ // todo: should prefix this with the path of the open file
return file;
}
private string GetSource(string file)
{
StreamReader fs=null;
string prog=null;
try
{
fs = new StreamReader(file);
prog = fs.ReadToEnd();
}
catch(Exception e)
{
prog = null;
MessageBox.Show(e.Message, "Error reading report file");
}
finally
{
if (fs != null)
fs.Close();
}
return prog;
}
private Oranikle.Report.Engine.Report GetReport(string prog, string file)
{
// Now parse the file
RDLParser rdlp;
Oranikle.Report.Engine.Report r;
try
{
rdlp = new RDLParser(prog);
string folder = Path.GetDirectoryName(file);
if (folder == "")
{
folder = Environment.CurrentDirectory;
}
rdlp.Folder = folder;
r = rdlp.Parse();
if (r.ErrorMaxSeverity > 4)
{
MessageBox.Show(string.Format("Report {0} has errors and cannot be processed.", "Report"));
r = null; // don't return when severe errors
}
}
catch(Exception e)
{
r = null;
MessageBox.Show(e.Message, "Report load failed");
}
return r;
}
private void DrillParametersDialog_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
foreach (DataRow dr in _DataTable.Rows)
{
if (dr[1] == DBNull.Value)
{
e.Cancel = true;
break;
}
string val = (string) dr[1];
if (val.Length <= 0)
{
e.Cancel = true;
break;
}
}
if (e.Cancel)
{
MessageBox.Show("Value must be specified for every parameter", this.Text);
}
}
private void bOK_Click(object sender, System.EventArgs e)
{
CancelEventArgs ce = new CancelEventArgs();
DrillParametersDialog_Validating(this, ce);
if (ce.Cancel)
{
DialogResult = DialogResult.None;
return;
}
DialogResult = DialogResult.OK;
}
}
internal class DrillParameter
{
internal string ParameterName;
internal string ParameterValue;
internal string ParameterOmit;
internal DrillParameter(string name, string pvalue, string omit)
{
ParameterName = name;
ParameterValue = pvalue;
ParameterOmit = omit;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
**
**
** Purpose: A collection of methods for manipulating Files.
**
** April 09,2000 (some design refactorization)
**
===========================================================*/
using System;
using System.Security.Permissions;
using PermissionSet = System.Security.PermissionSet;
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.InteropServices;
using System.Security;
#if FEATURE_MACL
using System.Security.AccessControl;
#endif
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.IO {
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
[ComVisible(true)]
public static class File
{
private const int GetFileExInfoStandard = 0;
public static StreamReader OpenText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return new StreamReader(path);
}
public static StreamWriter CreateText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return new StreamWriter(path,false);
}
public static StreamWriter AppendText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return new StreamWriter(path,true);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
public static void Copy(String sourceFileName, String destFileName) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, false, true);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
public static void Copy(String sourceFileName, String destFileName, bool overwrite) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, overwrite, true);
}
[System.Security.SecurityCritical]
internal static void UnsafeCopy(String sourceFileName, String destFileName, bool overwrite) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, overwrite, false);
}
/// <devdoc>
/// Note: This returns the fully qualified name of the destination file.
/// </devdoc>
[System.Security.SecuritySafeCritical]
internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost) {
Contract.Requires(sourceFileName != null);
Contract.Requires(destFileName != null);
Contract.Requires(sourceFileName.Length > 0);
Contract.Requires(destFileName.Length > 0);
String fullSourceFileName = Path.GetFullPathInternal(sourceFileName);
String fullDestFileName = Path.GetFullPathInternal(destFileName);
#if FEATURE_CORECLR
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
sourceState.EnsureState();
destState.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullSourceFileName, false, false);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
#endif
bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite);
if (!r) {
// Save Win32 error because subsequent checks will overwrite this HRESULT.
int errorCode = Marshal.GetLastWin32Error();
String fileName = destFileName;
if (errorCode != Win32Native.ERROR_FILE_EXISTS) {
// For a number of error codes (sharing violation, path
// not found, etc) we don't know if the problem was with
// the source or dest file. Try reading the source file.
using(SafeFileHandle handle = Win32Native.UnsafeCreateFile(fullSourceFileName, FileStream.GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero)) {
if (handle.IsInvalid)
fileName = sourceFileName;
}
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
if (Directory.InternalExists(fullDestFileName))
throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName);
}
}
__Error.WinIOError(errorCode, fileName);
}
return fullDestFileName;
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite accessand cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
public static FileStream Create(String path) {
return Create(path, FileStream.DefaultBufferSize);
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
public static FileStream Create(String path, int bufferSize) {
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize);
}
public static FileStream Create(String path, int bufferSize, FileOptions options) {
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite,
FileShare.None, bufferSize, options);
}
#if FEATURE_MACL
public static FileStream Create(String path, int bufferSize, FileOptions options, FileSecurity fileSecurity) {
return new FileStream(path, FileMode.Create, FileSystemRights.Read | FileSystemRights.Write,
FileShare.None, bufferSize, options, fileSecurity);
}
#endif
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped.
//
// Your application must have Delete permission to the target file.
//
[System.Security.SecuritySafeCritical]
public static void Delete(String path) {
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
InternalDelete(path, true);
}
[System.Security.SecurityCritical]
internal static void UnsafeDelete(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
InternalDelete(path, false);
}
[System.Security.SecurityCritical]
internal static void InternalDelete(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, path, fullPath);
state.EnsureState();
}
#else
// For security check, path should be resolved to an absolute path.
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false);
#endif
bool r = Win32Native.DeleteFile(fullPath);
if (!r) {
int hr = Marshal.GetLastWin32Error();
if (hr==Win32Native.ERROR_FILE_NOT_FOUND)
return;
else
__Error.WinIOError(hr, fullPath);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void Decrypt(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, fullPath, false, false);
bool r = Win32Native.DecryptFile(fullPath, 0);
if (!r) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
// Check to see if the file system is not NTFS. If so,
// throw a different exception.
DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath));
if (!String.Equals("NTFS", di.DriveFormat))
throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS"));
}
__Error.WinIOError(errorCode, fullPath);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void Encrypt(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, fullPath, false, false);
bool r = Win32Native.EncryptFile(fullPath);
if (!r) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
// Check to see if the file system is not NTFS. If so,
// throw a different exception.
DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath));
if (!String.Equals("NTFS", di.DriveFormat))
throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS"));
}
__Error.WinIOError(errorCode, fullPath);
}
}
// Tests if a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
//
// Your application must have Read permission for the target directory.
//
[System.Security.SecuritySafeCritical]
public static bool Exists(String path)
{
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
return InternalExistsHelper(path, true);
}
[System.Security.SecurityCritical]
internal static bool UnsafeExists(String path)
{
return InternalExistsHelper(path, false);
}
[System.Security.SecurityCritical]
private static bool InternalExistsHelper(String path, bool checkHost)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
path = Path.GetFullPathInternal(path);
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPathInternal should never return null
Contract.Assert(path != null, "File.Exists: GetFullPathInternal returned null");
if (path.Length > 0 && Path.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, path);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, path, false, false);
#endif
return InternalExists(path);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
[System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path) {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(path, ref data, false, true);
return (dataInitialised == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
}
public static FileStream Open(String path, FileMode mode) {
return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
}
public static FileStream Open(String path, FileMode mode, FileAccess access) {
return Open(path,mode, access, FileShare.None);
}
public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share) {
return new FileStream(path, mode, access, share);
}
public static void SetCreationTime(String path, DateTime creationTime)
{
SetCreationTimeUtc(path, creationTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static void SetCreationTimeUtc(String path, DateTime creationTimeUtc)
{
SafeFileHandle handle;
using(OpenFile(path, FileAccess.Write, out handle)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, &fileTime, null, null);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
[System.Security.SecuritySafeCritical]
public static DateTime GetCreationTime(String path)
{
return InternalGetCreationTimeUtc(path, true).ToLocalTime();
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetCreationTimeUtc(String path)
{
return InternalGetCreationTimeUtc(path, false); // this API isn't exposed in Silverlight
}
[System.Security.SecurityCritical]
private static DateTime InternalGetCreationTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow);
return DateTime.FromFileTimeUtc(dt);
}
public static void SetLastAccessTime(String path, DateTime lastAccessTime)
{
SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
{
SafeFileHandle handle;
using(OpenFile(path, FileAccess.Write, out handle)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, null, &fileTime, null);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
[System.Security.SecuritySafeCritical]
public static DateTime GetLastAccessTime(String path)
{
return InternalGetLastAccessTimeUtc(path, true).ToLocalTime();
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastAccessTimeUtc(String path)
{
return InternalGetLastAccessTimeUtc(path, false); // this API isn't exposed in Silverlight
}
[System.Security.SecurityCritical]
private static DateTime InternalGetLastAccessTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow);
return DateTime.FromFileTimeUtc(dt);
}
public static void SetLastWriteTime(String path, DateTime lastWriteTime)
{
SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
{
SafeFileHandle handle;
using(OpenFile(path, FileAccess.Write, out handle)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, null, null, &fileTime);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
[System.Security.SecuritySafeCritical]
public static DateTime GetLastWriteTime(String path)
{
return InternalGetLastWriteTimeUtc(path, true).ToLocalTime();
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastWriteTimeUtc(String path)
{
return InternalGetLastWriteTimeUtc(path, false); // this API isn't exposed in Silverlight
}
[System.Security.SecurityCritical]
private static DateTime InternalGetLastWriteTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow);
return DateTime.FromFileTimeUtc(dt);
}
[System.Security.SecuritySafeCritical]
public static FileAttributes GetAttributes(String path)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, true);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
return (FileAttributes) data.fileAttributes;
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif
public static void SetAttributes(String path, FileAttributes fileAttributes)
{
String fullPath = Path.GetFullPathInternal(path);
#if !FEATURE_CORECLR
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false);
#endif
bool r = Win32Native.SetFileAttributes(fullPath, (int) fileAttributes);
if (!r) {
int hr = Marshal.GetLastWin32Error();
if (hr==ERROR_INVALID_PARAMETER)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileAttrs"));
__Error.WinIOError(hr, fullPath);
}
}
#if FEATURE_MACL
public static FileSecurity GetAccessControl(String path)
{
return GetAccessControl(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
}
public static FileSecurity GetAccessControl(String path, AccessControlSections includeSections)
{
// Appropriate security check should be done for us by FileSecurity.
return new FileSecurity(path, includeSections);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void SetAccessControl(String path, FileSecurity fileSecurity)
{
if (fileSecurity == null)
throw new ArgumentNullException("fileSecurity");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
// Appropriate security check should be done for us by FileSecurity.
fileSecurity.Persist(fullPath);
}
#endif
#if FEATURE_LEGACYNETCF
[System.Security.SecuritySafeCritical]
#endif // FEATURE_LEGACYNETCF
public static FileStream OpenRead(String path) {
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
}
public static FileStream OpenWrite(String path) {
return new FileStream(path, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllText(path, Encoding.UTF8, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllText(path, encoding, true);
}
[System.Security.SecurityCritical]
internal static String UnsafeReadAllText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllText(path, Encoding.UTF8, false);
}
[System.Security.SecurityCritical]
private static String InternalReadAllText(String path, Encoding encoding, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamReader sr = new StreamReader(path, encoding, true, StreamReader.DefaultBufferSize, checkHost))
return sr.ReadToEnd();
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, encoding, true);
}
[System.Security.SecurityCritical]
internal static void UnsafeWriteAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, false);
}
[System.Security.SecurityCritical]
private static void InternalWriteAllText(String path, String contents, Encoding encoding, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamWriter sw = new StreamWriter(path, false, encoding, StreamWriter.DefaultBufferSize, checkHost))
sw.Write(contents);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static byte[] ReadAllBytes(String path)
{
return InternalReadAllBytes(path, true);
}
[System.Security.SecurityCritical]
internal static byte[] UnsafeReadAllBytes(String path)
{
return InternalReadAllBytes(path, false);
}
[System.Security.SecurityCritical]
private static byte[] InternalReadAllBytes(String path, bool checkHost)
{
byte[] bytes;
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost)) {
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
throw new IOException(Environment.GetResourceString("IO.IO_FileTooLong2GB"));
int count = (int) fileLength;
bytes = new byte[count];
while(count > 0) {
int n = fs.Read(bytes, index, count);
if (n == 0)
__Error.EndOfFile();
index += n;
count -= n;
}
}
return bytes;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllBytes(String path, byte[] bytes)
{
if (path == null)
throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bytes == null)
throw new ArgumentNullException("bytes");
Contract.EndContractBlock();
InternalWriteAllBytes(path, bytes, true);
}
[System.Security.SecurityCritical]
internal static void UnsafeWriteAllBytes(String path, byte[] bytes)
{
if (path == null)
throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bytes == null)
throw new ArgumentNullException("bytes");
Contract.EndContractBlock();
InternalWriteAllBytes(path, bytes, false);
}
[System.Security.SecurityCritical]
private static void InternalWriteAllBytes(String path, byte[] bytes, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(path.Length != 0);
Contract.Requires(bytes != null);
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read,
FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost))
{
fs.Write(bytes, 0, bytes.Length);
}
}
public static String[] ReadAllLines(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllLines(path, Encoding.UTF8);
}
public static String[] ReadAllLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllLines(path, encoding);
}
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length != 0);
String line;
List<String> lines = new List<String>();
using (StreamReader sr = new StreamReader(path, encoding))
while ((line = sr.ReadLine()) != null)
lines.Add(line);
return lines.ToArray();
}
public static IEnumerable<String> ReadLines(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path");
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, Encoding.UTF8);
}
public static IEnumerable<String> ReadLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path");
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, encoding);
}
public static void WriteAllLines(String path, String[] contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, StreamWriter.UTF8NoBOM), contents);
}
public static void WriteAllLines(String path, String[] contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, encoding), contents);
}
public static void WriteAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, StreamWriter.UTF8NoBOM), contents);
}
public static void WriteAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, encoding), contents);
}
private static void InternalWriteAllLines(TextWriter writer, IEnumerable<String> contents)
{
Contract.Requires(writer != null);
Contract.Requires(contents != null);
using (writer)
{
foreach (String line in contents)
{
writer.WriteLine(line);
}
}
}
public static void AppendAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalAppendAllText(path, contents, StreamWriter.UTF8NoBOM);
}
public static void AppendAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalAppendAllText(path, contents, encoding);
}
private static void InternalAppendAllText(String path, String contents, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamWriter sw = new StreamWriter(path, true, encoding))
sw.Write(contents);
}
public static void AppendAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, true, StreamWriter.UTF8NoBOM), contents);
}
public static void AppendAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, true, encoding), contents);
}
// Moves a specified file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
[System.Security.SecuritySafeCritical]
public static void Move(String sourceFileName, String destFileName) {
InternalMove(sourceFileName, destFileName, true);
}
[System.Security.SecurityCritical]
internal static void UnsafeMove(String sourceFileName, String destFileName) {
InternalMove(sourceFileName, destFileName, false);
}
[System.Security.SecurityCritical]
private static void InternalMove(String sourceFileName, String destFileName, bool checkHost) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
String fullSourceFileName = Path.GetFullPathInternal(sourceFileName);
String fullDestFileName = Path.GetFullPathInternal(destFileName);
#if FEATURE_CORECLR
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
sourceState.EnsureState();
destState.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, fullSourceFileName, false, false);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
#endif
if (!InternalExists(fullSourceFileName))
__Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName);
if (!Win32Native.MoveFile(fullSourceFileName, fullDestFileName))
{
__Error.WinIOError();
}
}
public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName");
if (destinationFileName == null)
throw new ArgumentNullException("destinationFileName");
Contract.EndContractBlock();
InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, false);
}
public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName");
if (destinationFileName == null)
throw new ArgumentNullException("destinationFileName");
Contract.EndContractBlock();
InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
}
[System.Security.SecuritySafeCritical]
private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
Contract.Requires(sourceFileName != null);
Contract.Requires(destinationFileName != null);
// Write permission to all three files, read permission to source
// and dest.
String fullSrcPath = Path.GetFullPathInternal(sourceFileName);
String fullDestPath = Path.GetFullPathInternal(destinationFileName);
String fullBackupPath = null;
if (destinationBackupFileName != null)
fullBackupPath = Path.GetFullPathInternal(destinationBackupFileName);
#if FEATURE_CORECLR
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, sourceFileName, fullSrcPath);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationFileName, fullDestPath);
FileSecurityState backupState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationBackupFileName, fullBackupPath);
sourceState.EnsureState();
destState.EnsureState();
backupState.EnsureState();
#else
FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullSrcPath, fullDestPath});
if (destinationBackupFileName != null)
perm.AddPathList(FileIOPermissionAccess.Write, fullBackupPath);
perm.Demand();
#endif
int flags = Win32Native.REPLACEFILE_WRITE_THROUGH;
if (ignoreMetadataErrors)
flags |= Win32Native.REPLACEFILE_IGNORE_MERGE_ERRORS;
bool r = Win32Native.ReplaceFile(fullDestPath, fullSrcPath, fullBackupPath, flags, IntPtr.Zero, IntPtr.Zero);
if (!r)
__Error.WinIOError();
}
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
[System.Security.SecurityCritical] // auto-generated
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
{
int dataInitialised = 0;
if (tryagain) // someone has a handle to the file open, or other error
{
Win32Native.WIN32_FIND_DATA findData;
findData = new Win32Native.WIN32_FIND_DATA ();
// Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
String tempPath = path.TrimEnd(new char [] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar});
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
bool error = false;
SafeFindHandle handle = Win32Native.FindFirstFile(tempPath,findData);
try {
if (handle.IsInvalid) {
error = true;
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready
{
if (!returnErrorOnNotFound) {
// Return default value for backward compatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
return dataInitialised;
}
}
finally {
// Close the Win32 handle
try {
handle.Close();
}
catch {
// if we're already returning an error, don't throw another one.
if (!error) {
Contract.Assert(false, "File::FillAttributeInfo - FindClose failed!");
__Error.WinIOError();
}
}
}
}
finally {
Win32Native.SetErrorMode(oldMode);
}
// Copy the information to data
data.PopulateFrom(findData);
}
else
{
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
bool success = false;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data);
}
finally {
Win32Native.SetErrorMode(oldMode);
}
if (!success) {
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready
{
// In case someone latched onto the file. Take the perf hit only for failure
return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound);
}
else {
if (!returnErrorOnNotFound) {
// Return default value for backward compbatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
}
}
return dataInitialised;
}
[System.Security.SecurityCritical] // auto-generated
private static FileStream OpenFile(String path, FileAccess access, out SafeFileHandle handle)
{
FileStream fs = new FileStream(path, FileMode.Open, access, FileShare.ReadWrite, 1);
handle = fs.SafeFileHandle;
if (handle.IsInvalid) {
// Return a meaningful error, using the RELATIVE path to
// the file to avoid returning extra information to the caller.
// NT5 oddity - when trying to open "C:\" as a FileStream,
// we usually get ERROR_PATH_NOT_FOUND from the OS. We should
// probably be consistent w/ every other directory.
int hr = Marshal.GetLastWin32Error();
String FullPath = Path.GetFullPathInternal(path);
if (hr==__Error.ERROR_PATH_NOT_FOUND && FullPath.Equals(Directory.GetDirectoryRoot(FullPath)))
hr = __Error.ERROR_ACCESS_DENIED;
__Error.WinIOError(hr, path);
}
return fs;
}
// Defined in WinError.h
private const int ERROR_INVALID_PARAMETER = 87;
private const int ERROR_ACCESS_DENIED = 0x5;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.